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