148
|
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
|
149
|
8 def __iter__(self):
|
|
9 return iter(self.symbols.values())
|
148
|
10 def getType(self, name):
|
|
11 t = self.getSymbol(name)
|
|
12 print(t)
|
|
13 assert isinstance(t, astnodes.Type)
|
|
14 return t
|
|
15 def getSymbol(self, name):
|
|
16 if name in self.symbols:
|
|
17 return self.symbols[name]
|
|
18 # Look for symbol:
|
|
19 if self.parent:
|
|
20 return self.parent.getSymbol(name)
|
|
21 raise CompilerException("Symbol {0} not found".format(name), name.loc)
|
|
22 def hasSymbol(self, name):
|
|
23 if name in self.symbols:
|
|
24 return True
|
|
25 if self.parent:
|
|
26 return self.parent.hasSymbol(name)
|
|
27 return False
|
|
28
|
|
29 def addSymbol(self, sym):
|
|
30 self.symbols[sym.name] = sym
|
|
31
|
|
32 def createBuiltins(scope):
|
|
33 scope.addSymbol(astnodes.BaseType('int'))
|
|
34
|
|
35 class Semantics:
|
|
36 """ This class constructs the AST from parser input """
|
|
37 def __init__(self, diag):
|
|
38 self.diag = diag
|
|
39 def handlePackage(self, name, loc):
|
|
40 self.mod = astnodes.Package(name)
|
|
41 self.mod.loc = loc
|
|
42 self.mod.scope = self.curScope = Scope()
|
|
43 createBuiltins(self.curScope)
|
149
|
44 def actOnBinop(self, lhs, op, rhs, loc):
|
|
45 bo = astnodes.Binop(lhs, op, rhs)
|
|
46 bo.loc = loc
|
|
47 return bo
|
|
48 def actOnNumber(self, num, loc):
|
|
49 n = astnodes.Constant(num)
|
|
50 n.loc = loc
|
|
51 return n
|
|
52 def actOnVarDef(self, name, loc, t, ival):
|
|
53 s = astnodes.Variable(name, t)
|
|
54 s.loc = loc
|
148
|
55 self.curScope.addSymbol(s)
|
149
|
56 def actOnFuncDef1(self, name, loc):
|
|
57 self.curFunc = astnodes.Procedure(name)
|
|
58 self.curFunc.loc = loc
|
|
59 self.curScope.addSymbol(self.curFunc)
|
|
60 self.curScope = self.curFunc.scope = Scope(self.curScope)
|
|
61 def actOnFuncDef2(self, parameters, returntype, body):
|
|
62 self.curFunc.body = body
|
|
63 self.curFunc.typ = astnodes.FunctionType(parameters, returntype)
|
|
64 self.curFunc = None
|
|
65 self.curScope = self.curScope.parent
|
148
|
66 def actOnType(self, tok):
|
|
67 # Try to lookup type, in case of failure return void
|
|
68 pass
|
|
69
|