148
|
1 from . import astnodes, lexer, semantics
|
152
|
2 from ppci import CompilerError
|
148
|
3
|
|
4 # binop precedence for expressions:
|
|
5 binopPrecs = {'or': 5, 'and': 10, \
|
|
6 '<': 20, '>': 20, '==': 20, '<=': 20, '>=': 20, '!=': 20, \
|
|
7 '+': 30, '-': 30, '*': 40, '/': 40 }
|
|
8
|
|
9 class Parser:
|
|
10 """ Parses sourcecode into an abstract syntax tree (AST) """
|
|
11 def __init__(self, sema, diag):
|
|
12 self.sema = sema
|
|
13 self.diag = diag
|
|
14 def parseSource(self, source):
|
|
15 self.initLex(source)
|
|
16 try:
|
|
17 self.parsePackage()
|
152
|
18 except CompilerError as e:
|
|
19 self.diag.addDiag(e)
|
148
|
20 def Error(self, msg):
|
152
|
21 raise CompilerError(msg, self.token.loc)
|
148
|
22 # Lexer helpers:
|
|
23 def Consume(self, typ):
|
|
24 if self.Peak == typ:
|
|
25 return self.NextToken()
|
|
26 else:
|
|
27 self.Error('Excected: "{0}", got "{1}"'.format(typ, self.Peak))
|
|
28 @property
|
|
29 def Peak(self):
|
|
30 return self.token.typ
|
|
31 @property
|
|
32 def PeakPrec(self):
|
149
|
33 if self.Peak in binopPrecs:
|
|
34 return binopPrecs[self.Peak]
|
|
35 return -1
|
148
|
36 def hasConsumed(self, typ):
|
|
37 if self.Peak == typ:
|
|
38 self.Consume(typ)
|
|
39 return True
|
|
40 return False
|
|
41 def NextToken(self):
|
|
42 t = self.token
|
150
|
43 if t.typ != 'END': self.token = self.tokens.__next__()
|
148
|
44 return t
|
|
45 def initLex(self, source):
|
|
46 self.tokens = lexer.tokenize(source) # Lexical stage
|
|
47 self.token = self.tokens.__next__()
|
|
48
|
|
49 def parsePackage(self):
|
|
50 self.Consume('package')
|
|
51 name = self.Consume('ID')
|
|
52 self.Consume(';')
|
|
53 self.sema.handlePackage(name.val, name.loc)
|
|
54 # TODO: parse uses
|
|
55 while self.Peak != 'END':
|
|
56 self.parseTopLevel()
|
|
57 self.Consume('END')
|
|
58
|
|
59 def parseTopLevel(self):
|
|
60 if self.Peak == 'function':
|
149
|
61 self.parseFunctionDefinition()
|
148
|
62 elif self.Peak == 'var':
|
149
|
63 self.parseVarDef()
|
|
64 self.Consume(';')
|
|
65 else:
|
|
66 self.Error('Expected function or variable')
|
148
|
67
|
|
68 def parseDesignator(self):
|
|
69 """ A designator designates an object """
|
|
70 name = self.Consume('ID')
|
150
|
71 return self.sema.actOnDesignator(name.val, name.loc)
|
148
|
72
|
|
73 # Type system
|
|
74 def parseType(self):
|
|
75 d = self.parseDesignator()
|
|
76 return d
|
|
77
|
|
78 # Variable declarations:
|
149
|
79 def parseVarDef(self):
|
148
|
80 self.Consume('var')
|
149
|
81 t = self.parseType()
|
|
82 def parseVar():
|
|
83 name = self.Consume('ID')
|
|
84 ival = None
|
|
85 if self.hasConsumed('='):
|
|
86 ival = self.parseExpression()
|
|
87 self.sema.actOnVarDef(name.val, name.loc, t, ival)
|
|
88 parseVar()
|
|
89 while self.hasConsumed(','):
|
|
90 parseVar()
|
148
|
91
|
|
92 # Procedures
|
149
|
93 def parseFunctionDefinition(self):
|
148
|
94 self.Consume('function')
|
|
95 returntype = self.parseType()
|
149
|
96 pname = self.Consume('ID')
|
|
97 self.sema.actOnFuncDef1(pname.val, pname.loc)
|
148
|
98 self.Consume('(')
|
|
99 parameters = []
|
|
100 if not self.hasConsumed(')'):
|
150
|
101 def parseParameter():
|
148
|
102 typ = self.parseType()
|
|
103 name = self.Consume('ID')
|
150
|
104 parameters.append(self.sema.actOnParameter(name.val, name.loc, typ))
|
|
105 parseParameter()
|
|
106 while self.hasConsumed(','):
|
|
107 parseParameter()
|
148
|
108 self.Consume(')')
|
|
109 body = self.parseCompoundStatement()
|
149
|
110 self.sema.actOnFuncDef2(parameters, returntype, body)
|
148
|
111
|
|
112 # Statements:
|
|
113 def parseAssignment(self, lval):
|
150
|
114 lval = astnodes.VariableUse(lval)
|
148
|
115 self.Consume('=')
|
|
116 rval = self.parseExpression()
|
|
117 return astnodes.Assignment(lval, rval)
|
|
118
|
|
119 def parseProcedureCall(self, procedure):
|
|
120 self.Consume('(')
|
|
121 args = []
|
|
122 if not self.hasConsumed(')'):
|
|
123 args.append(self.parseExpression())
|
|
124 while self.hasConsumed(','):
|
|
125 args.append(self.parseExpression())
|
|
126 self.Consume(')')
|
|
127 return ProcedureCall(procedure, args)
|
|
128
|
|
129 def parseIfStatement(self):
|
|
130 self.Consume('if')
|
|
131 self.Consume('(')
|
|
132 condition = self.parseExpression()
|
|
133 self.Consume(')')
|
149
|
134 yes = self.parseCompoundStatement()
|
148
|
135 if self.hasConsumed('else'):
|
149
|
136 no = self.parseCompoundStatement()
|
|
137 return astnodes.IfStatement(condition, yes, no)
|
|
138 return astnodes.IfStatement(condition, yes)
|
148
|
139
|
|
140 def parseWhileStatement(self):
|
|
141 self.Consume('while')
|
|
142 self.Consume('(')
|
|
143 condition = self.parseExpression()
|
|
144 self.Consume(')')
|
149
|
145 statements = self.parseCompoundStatement()
|
|
146 return astnodes.WhileStatement(condition, statements)
|
|
147
|
148
|
148 def parseReturnStatement(self):
|
|
149 self.Consume('return')
|
|
150 expr = self.parseExpression()
|
149
|
151 return astnodes.ReturnStatement(expr)
|
148
|
152
|
|
153 def parseCompoundStatement(self):
|
149
|
154 self.Consume('{')
|
|
155 statements = [self.parseStatement()]
|
|
156 while self.hasConsumed(';'):
|
148
|
157 statements.append(self.parseStatement())
|
149
|
158 self.Consume('}')
|
|
159 return astnodes.CompoundStatement(statements)
|
148
|
160
|
|
161 def parseStatement(self):
|
|
162 # Determine statement type based on the pending token:
|
|
163 if self.Peak == 'if':
|
|
164 return self.parseIfStatement()
|
|
165 elif self.Peak == 'while':
|
|
166 return self.parseWhileStatement()
|
|
167 elif self.Peak == '{':
|
|
168 return self.parseCompoundStatement()
|
|
169 elif self.Peak == 'var':
|
149
|
170 return self.parseVarDef()
|
148
|
171 elif self.Peak == 'return':
|
|
172 return self.parseReturnStatement()
|
|
173 elif self.Peak == 'ID':
|
|
174 designator = self.parseDesignator()
|
|
175 if self.Peak == '(':
|
|
176 return self.parseProcedureCall(designator)
|
|
177 elif self.Peak == '=':
|
|
178 return self.parseAssignment(designator)
|
|
179 self.Error('Unable to determine statement')
|
|
180
|
|
181 # Parsing expressions:
|
|
182 def parseExpression(self):
|
|
183 return self.parseBinopRhs(self.parsePrimary(), 0)
|
|
184 def parsePrimary(self):
|
|
185 if self.hasConsumed('('):
|
|
186 e = self.parseExpression()
|
|
187 self.Consume(')')
|
|
188 return e
|
|
189 elif self.Peak == 'NUMBER':
|
|
190 val = self.Consume('NUMBER')
|
149
|
191 return self.sema.actOnNumber(val.val, val.loc)
|
148
|
192 elif self.Peak == 'ID':
|
|
193 d = self.parseDesignator()
|
150
|
194 return self.sema.actOnVariableUse(d)
|
148
|
195 self.Error('Expected NUM, ID or (expr), got {0}'.format(self.Peak))
|
|
196
|
|
197 def parseBinopRhs(self, lhs, min_prec):
|
|
198 while self.PeakPrec >= min_prec:
|
|
199 op_prec = self.PeakPrec
|
|
200 op = self.Consume(self.Peak)
|
|
201 rhs = self.parsePrimary()
|
|
202 while self.PeakPrec > op_prec:
|
|
203 rhs = self.parseBinopRhs(rhs, self.PeakPrec)
|
149
|
204 lhs = self.sema.actOnBinop(lhs, op.typ, rhs, op.loc)
|
148
|
205 return lhs
|
|
206
|