150
|
1 from . import astnodes
|
|
2
|
288
|
3
|
150
|
4 class Scope:
|
217
|
5 """ A scope contains all symbols in a scope """
|
|
6 def __init__(self, parent=None):
|
|
7 self.symbols = {}
|
|
8 self.parent = parent
|
|
9
|
|
10 def __iter__(self):
|
272
|
11 # Iterate in a deterministic manner:
|
|
12 return iter(self.Constants + self.Variables + self.Functions)
|
217
|
13
|
|
14 @property
|
|
15 def Syms(self):
|
|
16 syms = self.symbols.values()
|
|
17 return sorted(syms, key=lambda v: v.name)
|
|
18
|
|
19 @property
|
|
20 def Constants(self):
|
|
21 return [s for s in self.Syms if type(s) is astnodes.Constant]
|
|
22
|
|
23 @property
|
|
24 def Variables(self):
|
272
|
25 return [s for s in self.Syms if isinstance(s, astnodes.Variable)]
|
217
|
26
|
|
27 @property
|
|
28 def Functions(self):
|
|
29 return [s for s in self.Syms if type(s) is astnodes.Function]
|
|
30
|
|
31 def getSymbol(self, name):
|
272
|
32 if name in self.symbols:
|
|
33 return self.symbols[name]
|
|
34 # Look for symbol:
|
|
35 if self.parent:
|
|
36 return self.parent.getSymbol(name)
|
|
37 raise CompilerException("Symbol {0} not found".format(name), name.loc)
|
217
|
38
|
|
39 def hasSymbol(self, name):
|
272
|
40 if name in self.symbols:
|
|
41 return True
|
|
42 if self.parent:
|
|
43 return self.parent.hasSymbol(name)
|
|
44 return False
|
217
|
45
|
|
46 def addSymbol(self, sym):
|
272
|
47 self.symbols[sym.name] = sym
|
150
|
48
|
217
|
49 def __repr__(self):
|
|
50 return 'Scope with {} symbols'.format(len(self.symbols))
|
|
51
|
272
|
52
|
288
|
53 def createBuiltins(scope):
|
|
54 for tn in ['u64', 'u32', 'u16', 'u8']:
|
|
55 scope.addSymbol(astnodes.BaseType(tn))
|
|
56 for t in [intType, doubleType, voidType, boolType, stringType, byteType]:
|
|
57 scope.addSymbol(t)
|
|
58
|
163
|
59 # buildin types:
|
|
60 intType = astnodes.BaseType('int')
|
231
|
61 intType.bytesize = 4
|
163
|
62 doubleType = astnodes.BaseType('double')
|
|
63 voidType = astnodes.BaseType('void')
|
164
|
64 boolType = astnodes.BaseType('bool')
|
|
65 stringType = astnodes.BaseType('string')
|
|
66 byteType = astnodes.BaseType('byte')
|
163
|
67
|
288
|
68 # Create top level scope:
|
150
|
69 topScope = Scope()
|
|
70 createBuiltins(topScope)
|