comparison python/ppci/c3/scope.py @ 300:158068af716c

yafm
author Windel Bouwman
date Tue, 03 Dec 2013 18:00:22 +0100
parents python/c3/scope.py@a747a45dcd78
children b145f8e6050b
comparison
equal deleted inserted replaced
299:674789d9ff37 300:158068af716c
1 from . import astnodes
2
3
4 class Scope:
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):
11 # Iterate in a deterministic manner:
12 return iter(self.Constants + self.Variables + self.Functions)
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):
25 return [s for s in self.Syms if isinstance(s, astnodes.Variable)]
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):
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)
38
39 def hasSymbol(self, name):
40 if name in self.symbols:
41 return True
42 if self.parent:
43 return self.parent.hasSymbol(name)
44 return False
45
46 def addSymbol(self, sym):
47 self.symbols[sym.name] = sym
48
49 def __repr__(self):
50 return 'Scope with {} symbols'.format(len(self.symbols))
51
52
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
59 # buildin types:
60 intType = astnodes.BaseType('int')
61 intType.bytesize = 4
62 doubleType = astnodes.BaseType('double')
63 voidType = astnodes.BaseType('void')
64 boolType = astnodes.BaseType('bool')
65 stringType = astnodes.BaseType('string')
66 byteType = astnodes.BaseType('byte')
67
68 # Create top level scope:
69 topScope = Scope()
70 createBuiltins(topScope)