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)
|
163
|
22 def actOnConstDef(self, name, loc, t, val):
|
|
23 s = astnodes.Constant(name, t, val)
|
|
24 s.loc = loc
|
|
25 self.addSymbol(s)
|
150
|
26 def actOnFuncDef1(self, name, loc):
|
|
27 self.curFunc = astnodes.Function(name)
|
|
28 self.curFunc.loc = loc
|
|
29 self.addSymbol(self.curFunc)
|
|
30 self.curScope = self.curFunc.scope = Scope(self.curScope)
|
|
31 def actOnParameter(self, name, loc, t):
|
|
32 p = astnodes.Variable(name, t)
|
|
33 p.loc = loc
|
|
34 p.parameter = True
|
|
35 self.addSymbol(p)
|
|
36 return p
|
|
37 def actOnFuncDef2(self, parameters, returntype, body):
|
|
38 self.curFunc.body = body
|
|
39 self.curFunc.typ = astnodes.FunctionType(parameters, returntype)
|
|
40 self.curFunc = None
|
|
41 self.curScope = self.curScope.parent
|
|
42 def actOnType(self, tok):
|
|
43 # Try to lookup type, in case of failure return void
|
|
44 pass
|
|
45 def actOnDesignator(self, tname, loc):
|
|
46 d = astnodes.Designator(tname)
|
|
47 d.scope = self.curScope
|
|
48 d.loc = loc
|
|
49 return d
|
149
|
50 def actOnBinop(self, lhs, op, rhs, loc):
|
|
51 bo = astnodes.Binop(lhs, op, rhs)
|
|
52 bo.loc = loc
|
|
53 return bo
|
|
54 def actOnNumber(self, num, loc):
|
163
|
55 n = astnodes.Literal(num)
|
149
|
56 n.loc = loc
|
|
57 return n
|
150
|
58 def actOnVariableUse(self, d):
|
164
|
59 vu = astnodes.VariableUse(d)
|
|
60 return vu
|
|
61 def actOnAssignment(self, lval, rval, loc):
|
|
62 a = astnodes.Assignment(lval, rval)
|
|
63 a.loc = loc
|
|
64 return a
|
148
|
65
|