~kf5jwc/imp-parser

ref: 4a8b0d0c4a9b3e235854c13031f981f55fc7ece5 imp-parser/imp_parser/ast/boolean.py -rw-r--r-- 1.9 KiB View raw
4a8b0d0c — Kyle Jones More typing! 1 year, 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import attr
from .types import Aexp, Bexp


@attr.s
class BinopAexp(Aexp):
    op = attr.ib()
    left = attr.ib()
    right = attr.ib()

    def eval(self, env):
        left_value = self.left.eval(env)
        right_value = self.right.eval(env)

        if   self.op == '+':
            return left_value + right_value
        elif self.op == '-':
            return left_value - right_value
        elif self.op == '*':
            return left_value * right_value
        elif self.op == '/':
            return left_value / right_value

        raise RuntimeError(f"Unknown operator: {self.op}")


@attr.s
class RelopBexp(Bexp):
    op = attr.ib()
    left = attr.ib()
    right = attr.ib()

    def eval(self, env):
        left_value = self.left.eval(env)
        right_value = self.right.eval(env)

        if  self.op == '<':
            return left_value <  right_value
        elif self.op == '<=':
            return left_value <= right_value
        elif self.op == '>':
            return left_value >  right_value
        elif self.op == '>=':
            return left_value >= right_value
        elif self.op == '=':
            return left_value == right_value
        elif self.op == '!=':
            return left_value != right_value

        raise RuntimeError(f"Unknown operator: {self.op}")


@attr.s
class AndBexp(Bexp):
    left = attr.ib()
    right = attr.ib()

    def eval(self, env):
        left_value = self.left.eval(env)
        right_value = self.right.eval(env)
        return (left_value and right_value)


@attr.s
class OrBexp(Bexp):
    left = attr.ib()
    right = attr.ib()

    def eval(self, env):
        left_value = self.left.eval(env)
        right_value = self.right.eval(env)
        return (left_value or right_value)


@attr.s
class NotBexp(Bexp):
    exp = attr.ib()

    def eval(self, env):
        value = self.exp.eval(env)
        return (not value)