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