306
|
1 from .astnodes import Constant, Variable, Function, BaseType
|
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
|
272
|
57 self.symbols[sym.name] = sym
|
150
|
58
|
217
|
59 def __repr__(self):
|
|
60 return 'Scope with {} symbols'.format(len(self.symbols))
|
|
61
|
272
|
62
|
306
|
63 def createTopScope(target):
|
|
64 scope = Scope()
|
288
|
65 for tn in ['u64', 'u32', 'u16', 'u8']:
|
306
|
66 scope.addSymbol(BaseType(tn))
|
|
67 # buildin types:
|
|
68 intType = BaseType('int')
|
|
69 intType.bytesize = target.byte_sizes['int']
|
|
70 scope.addSymbol(intType)
|
|
71 scope.addSymbol(BaseType('double'))
|
|
72 scope.addSymbol(BaseType('void'))
|
|
73 scope.addSymbol(BaseType('bool'))
|
|
74 scope.addSymbol(BaseType('string'))
|
|
75 scope.addSymbol(BaseType('byte'))
|
|
76 return scope
|