148
|
1 from . import astnodes
|
150
|
2 from .scope import Scope, topScope
|
|
3 from ppci.errors import CompilerException
|
148
|
4
|
|
5 class Semantics:
|
|
6 """ This class constructs the AST from parser input """
|
|
7 def __init__(self, diag):
|
|
8 self.diag = diag
|
150
|
9 def addSymbol(self, s):
|
|
10 if self.curScope.hasSymbol(s.name):
|
|
11 msg = 'Redefinition of {0}'.format(s.name)
|
|
12 self.diag.diag(CompilerException(msg, s.loc))
|
|
13 else:
|
|
14 self.curScope.addSymbol(s)
|
148
|
15 def handlePackage(self, name, loc):
|
|
16 self.mod = astnodes.Package(name)
|
|
17 self.mod.loc = loc
|
150
|
18 self.mod.scope = self.curScope = Scope(topScope)
|
|
19 def actOnVarDef(self, name, loc, t, ival):
|
|
20 s = astnodes.Variable(name, t)
|
|
21 s.loc = loc
|
|
22 self.addSymbol(s)
|
|
23 def actOnFuncDef1(self, name, loc):
|
|
24 self.curFunc = astnodes.Function(name)
|
|
25 self.curFunc.loc = loc
|
|
26 self.addSymbol(self.curFunc)
|
|
27 self.curScope = self.curFunc.scope = Scope(self.curScope)
|
|
28 def actOnParameter(self, name, loc, t):
|
|
29 p = astnodes.Variable(name, t)
|
|
30 p.loc = loc
|
|
31 p.parameter = True
|
|
32 self.addSymbol(p)
|
|
33 return p
|
|
34 def actOnFuncDef2(self, parameters, returntype, body):
|
|
35 self.curFunc.body = body
|
|
36 self.curFunc.typ = astnodes.FunctionType(parameters, returntype)
|
|
37 self.curFunc = None
|
|
38 self.curScope = self.curScope.parent
|
|
39 def actOnType(self, tok):
|
|
40 # Try to lookup type, in case of failure return void
|
|
41 pass
|
|
42 def actOnDesignator(self, tname, loc):
|
|
43 d = astnodes.Designator(tname)
|
|
44 d.scope = self.curScope
|
|
45 d.loc = loc
|
|
46 return d
|
149
|
47 def actOnBinop(self, lhs, op, rhs, loc):
|
|
48 bo = astnodes.Binop(lhs, op, rhs)
|
|
49 bo.loc = loc
|
|
50 return bo
|
|
51 def actOnNumber(self, num, loc):
|
|
52 n = astnodes.Constant(num)
|
|
53 n.loc = loc
|
|
54 return n
|
150
|
55 def actOnVariableUse(self, d):
|
|
56 return astnodes.VariableUse(d)
|
148
|
57
|