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):
|
164
|
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):
|
|
24 return [s for s in self.Syms if type(s) is astnodes.Variable]
|
|
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):
|
150
|
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):
|
150
|
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):
|
150
|
46 self.symbols[sym.name] = sym
|
|
47
|
217
|
48 def __repr__(self):
|
|
49 return 'Scope with {} symbols'.format(len(self.symbols))
|
|
50
|
163
|
51 # buildin types:
|
|
52 intType = astnodes.BaseType('int')
|
|
53 doubleType = astnodes.BaseType('double')
|
|
54 voidType = astnodes.BaseType('void')
|
164
|
55 boolType = astnodes.BaseType('bool')
|
|
56 stringType = astnodes.BaseType('string')
|
|
57 byteType = astnodes.BaseType('byte')
|
163
|
58
|
150
|
59 def createBuiltins(scope):
|
163
|
60 for tn in ['u64', 'u32', 'u16', 'u8']:
|
150
|
61 scope.addSymbol(astnodes.BaseType(tn))
|
164
|
62 for t in [intType, doubleType, voidType, boolType, stringType, byteType]:
|
163
|
63 scope.addSymbol(t)
|
150
|
64
|
|
65 topScope = Scope()
|
|
66 createBuiltins(topScope)
|
|
67
|