307
|
1 from .astnodes import Constant, Variable, Function, BaseType, Symbol
|
150
|
2
|
288
|
3
|
150
|
4 class Scope:
|
306
|
5 """ A scope contains all symbols in a scope. It also has a parent scope,
|
|
6 when looking for a symbol, also the parent scopes are checked. """
|
217
|
7 def __init__(self, parent=None):
|
|
8 self.symbols = {}
|
|
9 self.parent = parent
|
|
10
|
|
11 def __iter__(self):
|
272
|
12 # Iterate in a deterministic manner:
|
|
13 return iter(self.Constants + self.Variables + self.Functions)
|
217
|
14
|
|
15 @property
|
|
16 def Syms(self):
|
|
17 syms = self.symbols.values()
|
|
18 return sorted(syms, key=lambda v: v.name)
|
|
19
|
|
20 @property
|
|
21 def Constants(self):
|
306
|
22 return [s for s in self.Syms if type(s) is Constant]
|
217
|
23
|
|
24 @property
|
|
25 def Variables(self):
|
306
|
26 return [s for s in self.Syms if isinstance(s, Variable)]
|
217
|
27
|
|
28 @property
|
|
29 def Functions(self):
|
306
|
30 return [s for s in self.Syms if type(s) is Function]
|
217
|
31
|
|
32 def getSymbol(self, name):
|
272
|
33 if name in self.symbols:
|
|
34 return self.symbols[name]
|
|
35 # Look for symbol:
|
306
|
36 elif self.parent:
|
272
|
37 return self.parent.getSymbol(name)
|
306
|
38 else:
|
|
39 raise KeyError(name)
|
|
40
|
|
41 def __getitem__(self, key):
|
|
42 return self.getSymbol(key)
|
217
|
43
|
|
44 def hasSymbol(self, name):
|
272
|
45 if name in self.symbols:
|
|
46 return True
|
306
|
47 elif self.parent:
|
272
|
48 return self.parent.hasSymbol(name)
|
306
|
49 else:
|
|
50 return False
|
|
51
|
|
52 def __contains__(self, name):
|
|
53 return self.hasSymbol(name)
|
217
|
54
|
|
55 def addSymbol(self, sym):
|
306
|
56 assert sym.name not in self.symbols
|
307
|
57 assert isinstance(sym, Symbol)
|
272
|
58 self.symbols[sym.name] = sym
|
150
|
59
|
217
|
60 def __repr__(self):
|
|
61 return 'Scope with {} symbols'.format(len(self.symbols))
|
|
62
|
272
|
63
|
306
|
64 def createTopScope(target):
|
|
65 scope = Scope()
|
288
|
66 for tn in ['u64', 'u32', 'u16', 'u8']:
|
306
|
67 scope.addSymbol(BaseType(tn))
|
|
68 # buildin types:
|
|
69 intType = BaseType('int')
|
|
70 intType.bytesize = target.byte_sizes['int']
|
|
71 scope.addSymbol(intType)
|
|
72 scope.addSymbol(BaseType('double'))
|
|
73 scope.addSymbol(BaseType('void'))
|
|
74 scope.addSymbol(BaseType('bool'))
|
|
75 scope.addSymbol(BaseType('string'))
|
|
76 scope.addSymbol(BaseType('byte'))
|
|
77 return scope
|