summaryrefslogtreecommitdiffstats
path: root/src/front/scope.py
blob: 6559a261d8421359e0f697f275ab0b51a25a9343 (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
class Scope(object):
    __shared_state = {}
    __current_function = None
    __functions = {}

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

    def set_function(self, name):
        self.__current_function = name

    def new(self, name, symbols = []):
        if getattr(self.__functions, name, None):
            raise ScopeError("multiple definitions of %s" % name)
        self.__functions[name] = ([], [])
        self.set_function(name)

    def add(self, symbols, i):
        if type(symbols) != type([]):
            symbols = [symbols]
        for symbol in symbols:
            if symbol not in self.__functions[self.__current_function][i]:
                self.__functions[self.__current_function][i].append(symbol)

    def add_params(self, symbols):
        self.add(symbols, 0)

    def add_locals(self, symbols):
        self.add(symbols, 1)

    def contains(self, name):
        return name in reduce(lambda x,y: x+y, self.__functions[self.__current_function])

    def get_variable_offset(self, name):
        try:
            return self.__functions[self.__current_function][0].index(name) + 2
        except:
            return -self.__functions[self.__current_function][1].index(name) - 1

    def get_variables(self):
        return self.__functions[self.__current_function]

    def __str__(self):
        return "<Scope: %s>" % str(self.__functions)