summaryrefslogtreecommitdiffstats
path: root/src/back/tac.py
blob: 720775871f1fca6a0717c936bff808b9afd0bfe3 (plain) (blame)
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
82
83
84
85
86
87
88
89
class Op(object):
    __slots__ = ["name"]

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def __repr__(self):
        return """<Operator: "%s">""" % self

Op.ADD      = Op("ADD")    # x = x + y
Op.SUB      = Op("SUB")    # x = x - y
Op.MUL      = Op("MUL")    # x = x * y
Op.DIV      = Op("DIV")    # x = x / y
Op.MOD      = Op("MOD")    # x = x % y
Op.AND      = Op("AND")    # x = x AND y
Op.OR       = Op("OR")     # x = x OR y

Op.NOT      = Op("NOT")    # x = !x
Op.MINUS    = Op("MINUS")  # x = -x

Op.MOV      = Op("MOV")    # x = y
Op.STORE    = Op("STORE")  # MEM[x] = y
Op.LOAD     = Op("LOAD")   # y = MEM[x]
Op.PUSH     = Op("PUSH")   # push x
Op.POP      = Op("POP")    # pop x

Op.CMP      = Op("CMP")    # Z = x == y, N = x < y
Op.EQ       = Op("EQ")     # x = Z
Op.NE       = Op("NE")     # x = !Z
Op.LT       = Op("LT")     # x = N
Op.LE       = Op("LE")     # x = Z || N
Op.GE       = Op("GE")     # x = !N
Op.GT       = Op("GT")     # x = !Z && !N

Op.BEZ      = Op("BEZ")    # if x == 0 goto y
Op.JMP      = Op("JMP")    # goto x
Op.CALL     = Op("CALL")   # call x return in y
Op.RETURN   = Op("RETURN") # return x

Op.SYS      = Op("SYS")    # system call
Op.PRINT    = Op("PRINT")  # print x

class TAC(object):
    def __init__(self,op,arg1=None,arg2=None):
        self.op = op
        self.arg1 = arg1
        self.arg2 = arg2

    def __repr__(self):
        if self.arg2:
            return "<TAC, op: %s, arg1: %s, arg2: %s>" % (self.op,self.arg1,self.arg2)
        return "<TAC, op: %s, arg1: %s>" % (self.op,self.arg1)

class Label(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "<Label, name: %s>" % self.name

class FunctionPrologue(Label):
    def __repr__(self):
        return "<FunctionPrologue, name: %s>" % self.name

class FunctionEpilogue(Label):
    def __repr__(self):
        return "<FunctionEpilogue, name: %s>" % self.name

class TACList(object):
    __shared_state = {}
    __tac_list = []

    def __init__(self):
        self.__dict__ = self.__shared_state

    def add(self, tac):
        self.__tac_list.append(tac)

    def __repr__(self):
        res = ""
        for i in range(len(self.__tac_list)):
            res += "%04d: %s\n" % (i, repr(self.__tac_list[i]))
        return res

    def __iter__(self):
        return self.__tac_list.__iter__()