213
|
1 from . import astnodes, lexer
|
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:
|
213
|
10 """ Parses sourcecode into an abstract syntax tree (AST) """
|
|
11 def __init__(self, diag):
|
|
12 self.diag = diag
|
|
13
|
|
14 def parseSource(self, source):
|
148
|
15 self.initLex(source)
|
|
16 try:
|
|
17 self.parsePackage()
|
213
|
18 return self.mod
|
152
|
19 except CompilerError as e:
|
|
20 self.diag.addDiag(e)
|
213
|
21 def Error(self, msg):
|
152
|
22 raise CompilerError(msg, self.token.loc)
|
213
|
23 # Lexer helpers:
|
|
24 def Consume(self, typ):
|
148
|
25 if self.Peak == typ:
|
|
26 return self.NextToken()
|
|
27 else:
|
|
28 self.Error('Excected: "{0}", got "{1}"'.format(typ, self.Peak))
|
213
|
29 @property
|
|
30 def Peak(self):
|
148
|
31 return self.token.typ
|
213
|
32 @property
|
|
33 def PeakPrec(self):
|
149
|
34 if self.Peak in binopPrecs:
|
|
35 return binopPrecs[self.Peak]
|
|
36 return -1
|
213
|
37 def hasConsumed(self, typ):
|
148
|
38 if self.Peak == typ:
|
|
39 self.Consume(typ)
|
|
40 return True
|
|
41 return False
|
213
|
42
|
|
43 def NextToken(self):
|
148
|
44 t = self.token
|
166
|
45 if t.typ != 'END':
|
|
46 self.token = self.tokens.__next__()
|
148
|
47 return t
|
213
|
48
|
|
49 def initLex(self, source):
|
148
|
50 self.tokens = lexer.tokenize(source) # Lexical stage
|
|
51 self.token = self.tokens.__next__()
|
213
|
52
|
|
53 def parseUses(self):
|
|
54 pass
|
|
55
|
|
56 def parsePackage(self):
|
148
|
57 self.Consume('package')
|
|
58 name = self.Consume('ID')
|
|
59 self.Consume(';')
|
213
|
60 self.mod = astnodes.Package(name.val, name.loc)
|
|
61 self.parseUses()
|
148
|
62 # TODO: parse uses
|
|
63 while self.Peak != 'END':
|
|
64 self.parseTopLevel()
|
|
65 self.Consume('END')
|
|
66
|
213
|
67 def parseTopLevel(self):
|
148
|
68 if self.Peak == 'function':
|
213
|
69 self.parseFunctionDef()
|
148
|
70 elif self.Peak == 'var':
|
149
|
71 self.parseVarDef()
|
163
|
72 elif self.Peak == 'const':
|
|
73 self.parseConstDef()
|
213
|
74 elif self.Peak == 'type':
|
|
75 self.parseTypeDef()
|
149
|
76 else:
|
213
|
77 self.Error('Expected function, var, const or type')
|
148
|
78
|
213
|
79 def parseDesignator(self):
|
148
|
80 """ A designator designates an object """
|
|
81 name = self.Consume('ID')
|
213
|
82 d = astnodes.Designator(name.val, name.loc)
|
148
|
83 return d
|
|
84
|
213
|
85 # Type system
|
|
86 def parseTypeSpec(self):
|
|
87 # For now, do simple type spec, just parse an ID:
|
|
88 return self.parseDesignator()
|
|
89 if self.Peak == 'struct':
|
|
90 self.Consume('struct')
|
|
91 self.Consume('{')
|
|
92 mems = []
|
|
93 while self.Peak != '}':
|
|
94 mem_t = self.parseTypeSpec()
|
|
95 mem_n = self.Consume('ID')
|
|
96 mems.append((mem_t, mem_n))
|
|
97 while self.hasConsumed(','):
|
|
98 mem_n = self.Consume('ID')
|
|
99 mems.append((mem_t, mem_n))
|
|
100 self.Consume(';')
|
|
101 self.Consume('}')
|
|
102 theT = astnodes.StructureType(mems)
|
|
103 else:
|
|
104 theT = self.parseDesignator()
|
|
105 # Check for pointer suffix:
|
|
106 while self.hasConsumed('*'):
|
|
107 theT = astnodes.PointerType(theT)
|
|
108 return theT
|
|
109
|
|
110 def parseTypeDef(self):
|
|
111 self.Consume('type')
|
|
112 newtype = self.parseTypeSpec()
|
|
113 typename = self.Consume('ID')
|
|
114 # TODO: action here :)
|
|
115 self.Consume(';')
|
|
116 return astnodes.DefinedType(typename, newtype)
|
|
117
|
|
118 # Variable declarations:
|
|
119 def parseVarDef(self):
|
148
|
120 self.Consume('var')
|
213
|
121 t = self.parseTypeSpec()
|
149
|
122 def parseVar():
|
|
123 name = self.Consume('ID')
|
213
|
124 v = astnodes.Variable(name.val, t)
|
|
125 v.loc = name.loc
|
149
|
126 if self.hasConsumed('='):
|
213
|
127 v.ival = self.parseExpression()
|
149
|
128 parseVar()
|
|
129 while self.hasConsumed(','):
|
|
130 parseVar()
|
157
|
131 self.Consume(';')
|
148
|
132
|
213
|
133 def parseConstDef(self):
|
163
|
134 self.Consume('const')
|
213
|
135 t = self.parseTypeSpec()
|
163
|
136 def parseConst():
|
|
137 name = self.Consume('ID')
|
|
138 self.Consume('=')
|
|
139 val = self.parseExpression()
|
213
|
140 c = astnodes.Constant(name.val, t, val)
|
|
141 c.loc = name.loc
|
163
|
142 parseConst()
|
|
143 while self.hasConsumed(','):
|
|
144 parseConst()
|
|
145 self.Consume(';')
|
|
146
|
213
|
147 # Procedures
|
|
148 def parseFunctionDef(self):
|
|
149 loc = self.Consume('function').loc
|
|
150 returntype = self.parseTypeSpec()
|
|
151 fname = self.Consume('ID').val
|
|
152 f = astnodes.Function(fname, loc)
|
148
|
153 self.Consume('(')
|
|
154 parameters = []
|
|
155 if not self.hasConsumed(')'):
|
150
|
156 def parseParameter():
|
213
|
157 typ = self.parseTypeSpec()
|
148
|
158 name = self.Consume('ID')
|
213
|
159 param = astnodes.Variable(name.val, typ)
|
|
160 param.loc = name.loc
|
|
161 parameters.append(param)
|
150
|
162 parseParameter()
|
|
163 while self.hasConsumed(','):
|
|
164 parseParameter()
|
148
|
165 self.Consume(')')
|
|
166 body = self.parseCompoundStatement()
|
|
167
|
213
|
168 # Statements:
|
|
169 def parseAssignment(self, lval):
|
|
170 lval = astnodes.VariableUse(lval, lval.loc)
|
164
|
171 loc = self.Consume('=').loc
|
148
|
172 rval = self.parseExpression()
|
157
|
173 self.Consume(';')
|
213
|
174 return astnodes.Assignment(lval, rval, loc)
|
148
|
175
|
213
|
176 def parseCall(self, func):
|
148
|
177 self.Consume('(')
|
|
178 args = []
|
|
179 if not self.hasConsumed(')'):
|
|
180 args.append(self.parseExpression())
|
|
181 while self.hasConsumed(','):
|
|
182 args.append(self.parseExpression())
|
|
183 self.Consume(')')
|
213
|
184 return astnodes.FunctionCall(func, args, func.loc)
|
148
|
185
|
213
|
186 def parseIfStatement(self):
|
165
|
187 loc = self.Consume('if').loc
|
148
|
188 self.Consume('(')
|
|
189 condition = self.parseExpression()
|
|
190 self.Consume(')')
|
149
|
191 yes = self.parseCompoundStatement()
|
148
|
192 if self.hasConsumed('else'):
|
149
|
193 no = self.parseCompoundStatement()
|
165
|
194 else:
|
|
195 no = astnodes.EmptyStatement()
|
213
|
196 return astnodes.IfStatement(condition, yes, no, loc)
|
148
|
197
|
213
|
198 def parseWhileStatement(self):
|
|
199 loc = self.Consume('while').loc
|
148
|
200 self.Consume('(')
|
|
201 condition = self.parseExpression()
|
|
202 self.Consume(')')
|
149
|
203 statements = self.parseCompoundStatement()
|
213
|
204 return astnodes.WhileStatement(condition, statements, loc)
|
149
|
205
|
213
|
206 def parseReturnStatement(self):
|
148
|
207 self.Consume('return')
|
|
208 expr = self.parseExpression()
|
157
|
209 self.Consume(';')
|
149
|
210 return astnodes.ReturnStatement(expr)
|
148
|
211
|
213
|
212 def parseCompoundStatement(self):
|
149
|
213 self.Consume('{')
|
157
|
214 statements = []
|
|
215 while not self.hasConsumed('}'):
|
166
|
216 s = self.parseStatement()
|
|
217 if not type(s) is astnodes.EmptyStatement:
|
|
218 statements.append(s)
|
149
|
219 return astnodes.CompoundStatement(statements)
|
148
|
220
|
213
|
221 def parseStatement(self):
|
148
|
222 # Determine statement type based on the pending token:
|
|
223 if self.Peak == 'if':
|
|
224 return self.parseIfStatement()
|
|
225 elif self.Peak == 'while':
|
|
226 return self.parseWhileStatement()
|
|
227 elif self.Peak == '{':
|
|
228 return self.parseCompoundStatement()
|
158
|
229 elif self.hasConsumed(';'):
|
155
|
230 return astnodes.EmptyStatement()
|
148
|
231 elif self.Peak == 'var':
|
158
|
232 self.parseVarDef()
|
|
233 return astnodes.EmptyStatement()
|
148
|
234 elif self.Peak == 'return':
|
|
235 return self.parseReturnStatement()
|
213
|
236 else:
|
148
|
237 designator = self.parseDesignator()
|
|
238 if self.Peak == '(':
|
213
|
239 return self.parseCall(designator)
|
148
|
240 elif self.Peak == '=':
|
|
241 return self.parseAssignment(designator)
|
213
|
242 else:
|
|
243 self.Error('Unable to determine statement')
|
148
|
244
|
213
|
245 # Parsing expressions:
|
|
246 def parseExpression(self):
|
148
|
247 return self.parseBinopRhs(self.parsePrimary(), 0)
|
213
|
248
|
|
249 def parsePrimary(self):
|
148
|
250 if self.hasConsumed('('):
|
|
251 e = self.parseExpression()
|
|
252 self.Consume(')')
|
|
253 return e
|
|
254 elif self.Peak == 'NUMBER':
|
|
255 val = self.Consume('NUMBER')
|
213
|
256 return astnodes.Literal(val.val, val.loc)
|
163
|
257 elif self.Peak == 'REAL':
|
|
258 val = self.Consume('REAL')
|
213
|
259 return astnodes.Literal(val.val, val.loc)
|
166
|
260 elif self.Peak == 'true':
|
|
261 val = self.Consume('true')
|
213
|
262 return astnodes.Literal(True, val.loc)
|
166
|
263 elif self.Peak == 'false':
|
|
264 val = self.Consume('false')
|
213
|
265 return astnodes.Literal(False, val.loc)
|
148
|
266 elif self.Peak == 'ID':
|
|
267 d = self.parseDesignator()
|
155
|
268 if self.Peak == '(':
|
213
|
269 return self.parseCall(d)
|
155
|
270 else:
|
213
|
271 return astnodes.VariableUse(d, d.loc)
|
148
|
272 self.Error('Expected NUM, ID or (expr), got {0}'.format(self.Peak))
|
|
273
|
213
|
274 def parseBinopRhs(self, lhs, min_prec):
|
148
|
275 while self.PeakPrec >= min_prec:
|
|
276 op_prec = self.PeakPrec
|
|
277 op = self.Consume(self.Peak)
|
|
278 rhs = self.parsePrimary()
|
|
279 while self.PeakPrec > op_prec:
|
|
280 rhs = self.parseBinopRhs(rhs, self.PeakPrec)
|
213
|
281 lhs = astnodes.Binop(lhs, op.typ, rhs, op.loc)
|
148
|
282 return lhs
|
|
283
|