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