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