1
|
1 """
|
|
2 This module parses source code into an abstract syntax tree (AST)
|
|
3 """
|
|
4
|
|
5 from .symboltable import SymbolTable
|
|
6 from .nodes import *
|
|
7 from .errors import CompilerException, Error
|
|
8 from .modules import loadModule
|
|
9 from .display import printNode
|
|
10 from .builtin import *
|
|
11 from . import assembler
|
|
12
|
|
13 class Parser:
|
|
14 def __init__(self, tokens):
|
|
15 """ provide the parser with the tokens iterator from the lexer. """
|
|
16 self.tokens = tokens
|
|
17 self.NextToken()
|
5
|
18 self.errorlist = []
|
1
|
19
|
|
20 def Error(self, msg):
|
|
21 raise CompilerException(msg, self.token.row, self.token.col)
|
|
22
|
|
23 # Lexer helpers:
|
|
24 def Consume(self, typ=''):
|
|
25 if self.token.typ == typ or typ == '':
|
|
26 v = self.token.val
|
|
27 self.NextToken()
|
|
28 return v
|
|
29 else:
|
|
30 self.Error('Excected: "{0}", got "{1}"'.format(typ, self.token))
|
|
31
|
|
32 def hasConsumed(self, typ):
|
|
33 if self.token.typ == typ:
|
|
34 self.Consume(typ)
|
|
35 return True
|
|
36 return False
|
|
37
|
|
38 def NextToken(self):
|
|
39 self.token = self.tokens.__next__()
|
4
|
40 self.location = (self.token.row, self.token.col)
|
1
|
41
|
4
|
42 # Helpers to find location of the error in the code:
|
|
43 def setLocation(self, obj, location):
|
|
44 obj.location = location
|
|
45 return obj
|
|
46 def getLocation(self):
|
|
47 return self.location
|
|
48
|
1
|
49 """
|
|
50 Recursive descent parser functions:
|
|
51 A set of mutual recursive functions.
|
|
52 Starting symbol is the Module.
|
|
53 """
|
|
54 def parseModule(self):
|
|
55 self.imports = []
|
4
|
56 loc = self.getLocation()
|
1
|
57 self.Consume('module')
|
|
58 modname = self.Consume('ID')
|
|
59 self.Consume(';')
|
|
60 mod = Module(modname)
|
|
61
|
|
62 # Construct a symbol table for this program
|
|
63 mod.symtable = SymbolTable()
|
|
64 # Add built in types and functions:
|
|
65 for x in [real, integer, boolean, char, chr_func]:
|
|
66 mod.symtable.addSymbol(x)
|
|
67
|
|
68 self.cst = mod.symtable
|
|
69 self.parseImportList()
|
|
70
|
|
71 self.parseDeclarationSequence()
|
|
72 # Procedures only allowed in this scope
|
|
73 self.parseProcedureDeclarations()
|
|
74
|
|
75 if self.hasConsumed('begin'):
|
|
76 mod.initcode = self.parseStatementSequence()
|
|
77 else:
|
|
78 mod.initcode = EmptyStatement()
|
|
79
|
|
80 self.Consume('end')
|
|
81 endname = self.Consume('ID')
|
|
82 if endname != modname:
|
|
83 self.Error('end denoter must be module name')
|
|
84 self.Consume('.')
|
|
85
|
|
86 mod.imports = self.imports
|
4
|
87 return self.setLocation(mod, loc)
|
1
|
88
|
|
89 # Import part
|
|
90 def parseImportList(self):
|
|
91 if self.hasConsumed('import'):
|
|
92 self.parseImport()
|
|
93 while self.hasConsumed(','):
|
|
94 self.parseImport()
|
|
95 self.Consume(';')
|
|
96
|
|
97 def parseImport(self):
|
4
|
98 loc = self.getLocation()
|
1
|
99 modname = self.Consume('ID')
|
|
100 mod = loadModule(modname)
|
4
|
101 self.setLocation(mod, loc)
|
1
|
102 self.cst.addSymbol(mod)
|
|
103
|
|
104 # Helper to parse an identifier defenitions
|
|
105 def parseIdentDef(self):
|
4
|
106 loc = self.getLocation()
|
1
|
107 name = self.Consume('ID')
|
|
108 ispublic = self.hasConsumed('*')
|
4
|
109 # Make a node of this thing:
|
|
110 i = Id(name)
|
|
111 i.ispublic = ispublic
|
|
112 return self.setLocation(i, loc)
|
1
|
113
|
|
114 def parseIdentList(self):
|
|
115 ids = [ self.parseIdentDef() ]
|
|
116 while self.hasConsumed(','):
|
|
117 ids.append( self.parseIdentDef() )
|
|
118 return ids
|
|
119
|
|
120 def parseQualIdent(self):
|
|
121 """ Parse a qualified identifier """
|
|
122 name = self.Consume('ID')
|
|
123 if self.cst.has(Module, name):
|
|
124 modname = name
|
|
125 mod = self.cst.get(Module, modname)
|
|
126 self.Consume('.')
|
|
127 name = self.Consume('ID')
|
|
128 # Try to find existing imported symbol:
|
|
129 for imp in self.imports:
|
|
130 if imp.modname == modname and imp.name == name:
|
|
131 return imp
|
|
132 # Try to find the symbol in the modules exports:
|
|
133 for sym in mod.exports:
|
|
134 if sym.name == name:
|
|
135 impsym = ImportedSymbol(modname, name)
|
|
136 impsym.typ = sym.typ
|
|
137 impsym.signature = mod.signature
|
|
138 self.imports.append(impsym)
|
|
139 return impsym
|
|
140 self.Error("Cannot find symbol {0}".format(name))
|
|
141 else:
|
|
142 return self.cst.getSymbol(name)
|
|
143
|
|
144 # Helper to parse a designator
|
|
145 def parseDesignator(self):
|
|
146 """ A designator designates an object.
|
|
147 The base location in memory is denoted by the qualified identifier
|
|
148 The actual address depends on the selector.
|
|
149 """
|
4
|
150 loc = self.getLocation()
|
1
|
151 obj = self.parseQualIdent()
|
|
152 typ = obj.typ
|
|
153 selectors = []
|
|
154 while self.token.typ in ['.', '[', '^']:
|
|
155 if self.hasConsumed('.'):
|
|
156 field = self.Consume('ID')
|
|
157 if typ is PointerType:
|
|
158 selectors.append(Deref())
|
|
159 typ = typ.pointedType
|
|
160 if not type(typ) is RecordType:
|
|
161 self.Error("field reference, type not record but {0}".format(typ))
|
|
162 typ = typ.fields[field]
|
|
163 selectors.append(Field(field))
|
|
164 elif self.hasConsumed('['):
|
|
165 indexes = self.parseExpressionList()
|
|
166 self.Consume(']')
|
|
167 for idx in indexes:
|
|
168 if not type(typ) is ArrayType:
|
|
169 self.Error('Cannot index non array type')
|
|
170 if not isType(idx.typ, integer):
|
|
171 self.Error('Only integer expressions can be used as an index')
|
|
172 selectors.append(Index(idx, typ))
|
|
173 typ = typ.elementType
|
|
174 elif self.hasConsumed('^'):
|
|
175 selectors.append(Deref())
|
|
176 typ = typ.pointedType
|
4
|
177 return self.setLocation(Designator(obj, selectors, typ), loc)
|
1
|
178
|
|
179 # Declaration sequence
|
|
180 def parseDeclarationSequence(self):
|
|
181 """ 1. constants, 2. types, 3. variables """
|
|
182 self.parseConstantDeclarations()
|
|
183 self.parseTypeDeclarations()
|
|
184 self.parseVariableDeclarations()
|
|
185
|
|
186 # Constants
|
|
187 def evalExpression(self, expr):
|
|
188 if type(expr) is Binop:
|
|
189 a = self.evalExpression(expr.a)
|
|
190 b = self.evalExpression(expr.b)
|
|
191 if expr.op == '+':
|
|
192 return a + b
|
|
193 elif expr.op == '-':
|
|
194 return a - b
|
|
195 elif expr.op == '*':
|
|
196 return a * b
|
|
197 elif expr.op == '/':
|
|
198 return float(a) / float(b)
|
|
199 elif expr.op == 'mod':
|
|
200 return int(a % b)
|
|
201 elif expr.op == 'div':
|
|
202 return int(a / b)
|
|
203 elif expr.op == 'or':
|
|
204 return a or b
|
|
205 elif expr.op == 'and':
|
|
206 return a and b
|
|
207 else:
|
|
208 self.Error('Cannot evaluate expression with {0}'.format(expr.op))
|
|
209 elif type(expr) is Constant:
|
|
210 return expr.value
|
|
211 elif type(expr) is Designator:
|
|
212 if type(expr.obj) is Constant:
|
|
213 return self.evalExpression(expr.obj)
|
|
214 else:
|
|
215 self.Error('Cannot evaluate designated object {0}'.format(expr.obj))
|
|
216 elif type(expr) is Unop:
|
|
217 a = self.evalExpression(expr.a)
|
|
218 if expr.op == 'not':
|
|
219 return not a
|
|
220 elif expr.op == '-':
|
|
221 return -a
|
|
222 else:
|
|
223 self.Error('Unimplemented unary operation {0}'.format(expr.op))
|
|
224 else:
|
|
225 self.Error('Cannot evaluate expression {0}'.format(expr))
|
|
226
|
|
227 def parseConstExpression(self):
|
|
228 e = self.parseExpression()
|
|
229 return self.evalExpression(e), e.typ
|
|
230
|
|
231 def parseConstantDeclarations(self):
|
|
232 """ Parse const part of a module """
|
|
233 if self.hasConsumed('const'):
|
|
234 while self.token.typ == 'ID':
|
4
|
235 i = self.parseIdentDef()
|
1
|
236 self.Consume('=')
|
|
237 constvalue, typ = self.parseConstExpression()
|
|
238 self.Consume(';')
|
4
|
239 c = Constant(constvalue, typ, name=i.name, public=i.ispublic)
|
|
240 self.setLocation(c, i.location)
|
1
|
241 self.cst.addSymbol(c)
|
|
242
|
|
243 # Type system
|
|
244 def parseTypeDeclarations(self):
|
|
245 if self.hasConsumed('type'):
|
|
246 while self.token.typ == 'ID':
|
|
247 typename, export = self.parseIdentDef()
|
|
248 self.Consume('=')
|
|
249 typ = self.parseStructuredType()
|
|
250 self.Consume(';')
|
|
251 t = DefinedType(typename, typ)
|
|
252 self.cst.addSymbol(t)
|
|
253
|
|
254 def parseType(self):
|
|
255 if self.token.typ == 'ID':
|
|
256 typename = self.Consume('ID')
|
|
257 if self.cst.has(Type, typename):
|
|
258 typ = self.cst.get(Type, typename)
|
|
259 while type(typ) is DefinedType:
|
|
260 typ = typ.typ
|
|
261 return typ
|
|
262 else:
|
|
263 self.Error('Cannot find type {0}'.format(typename))
|
|
264 else:
|
|
265 return self.parseStructuredType()
|
|
266
|
|
267 def parseStructuredType(self):
|
|
268 if self.hasConsumed('array'):
|
|
269 dimensions = []
|
|
270 dimensions.append( self.parseConstExpression() )
|
|
271 while self.hasConsumed(','):
|
|
272 dimensions.append( self.parseConstExpression() )
|
|
273 self.Consume('of')
|
|
274 arr = self.parseType()
|
|
275 for dimension, consttyp in reversed(dimensions):
|
|
276 if not isType(consttyp, integer):
|
|
277 self.Error('array dimension must be an integer type (not {0})'.format(consttyp))
|
|
278 if dimension < 2:
|
|
279 self.Error('array dimension must be bigger than 1 (not {0})'.format(dimension))
|
|
280 arr = ArrayType(dimension, arr)
|
|
281 return arr
|
|
282 elif self.hasConsumed('record'):
|
|
283 fields = {}
|
|
284 while self.token.typ == 'ID':
|
|
285 # parse a fieldlist:
|
|
286 identifiers = self.parseIdentList()
|
|
287 self.Consume(':')
|
|
288 typ = self.parseType()
|
|
289 self.Consume(';')
|
4
|
290 for i in identifiers:
|
|
291 if i.name in fields.keys():
|
|
292 self.Error('record field "{0}" multiple defined.'.format(i.name))
|
|
293 fields[i.name] = typ
|
1
|
294 # TODO store this in another way, symbol table?
|
|
295 self.Consume('end')
|
|
296 return RecordType(fields)
|
|
297 elif self.hasConsumed('pointer'):
|
|
298 self.Consume('to')
|
|
299 typ = self.parseType()
|
|
300 return PointerType(typ)
|
|
301 elif self.hasConsumed('procedure'):
|
|
302 parameters, returntype = self.parseFormalParameters()
|
|
303 return ProcedureType(parameters, returntype)
|
|
304 else:
|
|
305 self.Error('Unknown structured type "{0}"'.format(self.token.val))
|
|
306
|
|
307 # Variable declarations:
|
|
308 def parseVariableDeclarations(self):
|
|
309 if self.hasConsumed('var'):
|
|
310 if self.token.typ == 'ID':
|
|
311 while self.token.typ == 'ID':
|
|
312 ids = self.parseIdentList()
|
|
313 self.Consume(':')
|
|
314 typename = self.parseType()
|
|
315 self.Consume(';')
|
4
|
316 for i in ids:
|
|
317 v = Variable(i.name, typename, public=i.ispublic)
|
|
318 self.setLocation(v, i.location)
|
1
|
319 self.cst.addSymbol(v)
|
|
320 else:
|
|
321 self.Error('Expected ID, got'+str(self.token))
|
|
322
|
|
323 # Procedures
|
|
324 def parseFPsection(self):
|
|
325 if self.hasConsumed('const'):
|
|
326 kind = 'const'
|
|
327 elif self.hasConsumed('var'):
|
|
328 kind = 'var'
|
|
329 else:
|
|
330 kind = 'value'
|
|
331 names = [ self.Consume('ID') ]
|
|
332 while self.hasConsumed(','):
|
|
333 names.append( self.Consume('ID') )
|
|
334 self.Consume(':')
|
|
335 typ = self.parseType()
|
|
336 parameters = [Parameter(kind, name, typ)
|
|
337 for name in names]
|
|
338 return parameters
|
|
339
|
|
340 def parseFormalParameters(self):
|
|
341 parameters = []
|
|
342 self.Consume('(')
|
|
343 if not self.hasConsumed(')'):
|
|
344 parameters += self.parseFPsection()
|
|
345 while self.hasConsumed(';'):
|
|
346 parameters += self.parseFPsection()
|
|
347 self.Consume(')')
|
|
348 if self.hasConsumed(':'):
|
|
349 returntype = self.parseQualIdent()
|
|
350 else:
|
|
351 returntype = void
|
|
352 return ProcedureType(parameters, returntype)
|
|
353
|
|
354 def parseProcedureDeclarations(self):
|
|
355 procedures = []
|
|
356 while self.token.typ == 'procedure':
|
|
357 p = self.parseProcedureDeclaration()
|
|
358 procedures.append(p)
|
|
359 self.Consume(';')
|
|
360 return procedures
|
|
361
|
|
362 def parseProcedureDeclaration(self):
|
6
|
363 loc = self.getLocation()
|
1
|
364 self.Consume('procedure')
|
4
|
365 i = self.parseIdentDef()
|
|
366 procname = i.name
|
1
|
367 proctyp = self.parseFormalParameters()
|
|
368 procsymtable = SymbolTable(parent = self.cst)
|
|
369 self.cst = procsymtable # Switch symbol table:
|
|
370 # Add parameters as variables to symbol table:
|
|
371 for parameter in proctyp.parameters:
|
|
372 vname = parameter.name
|
|
373 vtyp = parameter.typ
|
|
374 if parameter.kind == 'var':
|
|
375 vtyp = PointerType(vtyp)
|
|
376 variable = Variable(vname, vtyp, False)
|
|
377 if parameter.kind == 'const':
|
|
378 variable.isReadOnly = True
|
|
379 variable.isParameter = True
|
|
380 self.cst.addSymbol(variable)
|
|
381 self.Consume(';')
|
|
382 self.parseDeclarationSequence()
|
|
383 # Mark all variables as local:
|
|
384 for variable in self.cst.getAllLocal(Variable):
|
|
385 variable.isLocal = True
|
|
386
|
|
387 if self.hasConsumed('begin'):
|
|
388 block = self.parseStatementSequence()
|
|
389 if self.hasConsumed('return'):
|
|
390 returnexpression = self.parseExpression()
|
|
391 else:
|
|
392 returnexpression = None
|
|
393
|
|
394 if proctyp.returntype.isType(void):
|
|
395 if not returnexpression is None:
|
|
396 self.Error('Void procedure cannot return a value')
|
|
397 else:
|
|
398 if returnexpression is None:
|
|
399 self.Error('Procedure must return a value')
|
|
400 if not isType(returnexpression.typ, proctyp.returntype):
|
|
401 self.Error('Returned type {0} does not match function return type {1}'.format(returnexpression.typ, proctyp.returntype))
|
|
402
|
|
403 self.Consume('end')
|
|
404 endname = self.Consume('ID')
|
4
|
405 if endname != procname:
|
1
|
406 self.Error('endname should match {0}'.format(name))
|
|
407 self.cst = procsymtable.parent # Switch back to parent symbol table
|
4
|
408 proc = Procedure(procname, proctyp, block, procsymtable, returnexpression)
|
6
|
409 self.setLocation(proc, loc)
|
1
|
410 self.cst.addSymbol(proc)
|
4
|
411 proc.public = i.ispublic
|
1
|
412 return proc
|
|
413
|
|
414 # Statements:
|
|
415 def parseAssignment(self, lval):
|
4
|
416 loc = self.getLocation()
|
1
|
417 self.Consume(':=')
|
|
418 rval = self.parseExpression()
|
|
419 if isType(lval.typ, real) and isType(rval.typ, integer):
|
|
420 rval = Unop(rval, 'INTTOREAL', real)
|
|
421 if type(rval.typ) is NilType:
|
|
422 if not type(lval.typ) is ProcedureType and not type(lval.typ) is PointerType:
|
|
423 self.Error('Can assign nil only to pointers or procedure types, not {0}'.format(lval))
|
|
424 elif not isType(lval.typ, rval.typ):
|
|
425 self.Error('Type mismatch {0} != {1}'.format(lval.typ, rval.typ))
|
4
|
426 return self.setLocation(Assignment(lval, rval), loc)
|
1
|
427
|
|
428 def parseExpressionList(self):
|
|
429 expressions = [ self.parseExpression() ]
|
|
430 while self.hasConsumed(','):
|
|
431 expressions.append( self.parseExpression() )
|
|
432 return expressions
|
|
433
|
|
434 def parseProcedureCall(self, procedure):
|
|
435 self.Consume('(')
|
|
436 if self.token.typ != ')':
|
|
437 args = self.parseExpressionList()
|
|
438 else:
|
|
439 args = []
|
|
440 self.Consume(')')
|
|
441 parameters = procedure.typ.parameters
|
|
442 if len(args) != len(parameters):
|
|
443 self.Error("Procedure requires {0} arguments, {1} given".format(len(parameters), len(args)))
|
|
444 for arg, param in zip(args, parameters):
|
|
445 if not arg.typ.isType(param.typ):
|
|
446 print(arg.typ, param.typ)
|
|
447 self.Error('Mismatch in parameter')
|
|
448 return ProcedureCall(procedure, args)
|
|
449
|
|
450 def parseIfStatement(self):
|
4
|
451 loc = self.getLocation()
|
1
|
452 self.Consume('if')
|
|
453 ifs = []
|
|
454 condition = self.parseExpression()
|
|
455 if not isType(condition.typ, boolean):
|
|
456 self.Error('condition of if statement must be boolean')
|
|
457 self.Consume('then')
|
|
458 truestatement = self.parseStatementSequence()
|
|
459 ifs.append( (condition, truestatement) )
|
|
460 while self.hasConsumed('elsif'):
|
|
461 condition = self.parseExpression()
|
|
462 if not isType(condition.typ, boolean):
|
|
463 self.Error('condition of if statement must be boolean')
|
|
464 self.Consume('then')
|
|
465 truestatement = self.parseStatementSequence()
|
|
466 ifs.append( (condition, truestatement) )
|
|
467 if self.hasConsumed('else'):
|
|
468 statement = self.parseStatementSequence()
|
|
469 else:
|
|
470 statement = None
|
|
471 self.Consume('end')
|
|
472 for condition, truestatement in reversed(ifs):
|
|
473 statement = IfStatement(condition, truestatement, statement)
|
4
|
474 return self.setLocation(statement, loc)
|
1
|
475
|
|
476 def parseCase(self):
|
|
477 # TODO
|
|
478 pass
|
|
479
|
|
480 def parseCaseStatement(self):
|
|
481 self.Consume('case')
|
|
482 expr = self.parseExpression()
|
|
483 self.Consume('of')
|
|
484 self.parseCase()
|
|
485 while self.hasConsumed('|'):
|
|
486 self.parseCase()
|
|
487 self.Consume('end')
|
|
488
|
|
489 def parseWhileStatement(self):
|
4
|
490 loc = self.getLocation()
|
1
|
491 self.Consume('while')
|
|
492 condition = self.parseExpression()
|
|
493 self.Consume('do')
|
|
494 statements = self.parseStatementSequence()
|
|
495 if self.hasConsumed('elsif'):
|
|
496 self.Error('elsif in while not yet implemented')
|
|
497 self.Consume('end')
|
4
|
498 return self.setLocation(WhileStatement(condition, statements), loc)
|
1
|
499
|
|
500 def parseRepeatStatement(self):
|
|
501 self.Consume('repeat')
|
|
502 stmt = self.parseStatementSequence()
|
|
503 self.Consume('until')
|
|
504 cond = self.parseBoolExpression()
|
|
505
|
|
506 def parseForStatement(self):
|
4
|
507 loc = self.getLocation()
|
1
|
508 self.Consume('for')
|
|
509 variable = self.parseDesignator()
|
|
510 if not variable.typ.isType(integer):
|
|
511 self.Error('loop variable of for statement must have integer type')
|
|
512 assert(variable.typ.isType(integer))
|
|
513 self.Consume(':=')
|
|
514 begin = self.parseExpression()
|
|
515 if not begin.typ.isType(integer):
|
|
516 self.Error('begin expression of a for statement must have integer type')
|
|
517 self.Consume('to')
|
|
518 end = self.parseExpression()
|
|
519 if not end.typ.isType(integer):
|
|
520 self.Error('end expression of a for statement must have integer type')
|
|
521 if self.hasConsumed('by'):
|
|
522 increment, typ = self.parseConstExpression()
|
|
523 if not typ.isType(integer):
|
|
524 self.Error('Increment must be integer')
|
|
525 else:
|
|
526 increment = 1
|
|
527 assert(type(increment) is int)
|
|
528 self.Consume('do')
|
|
529 statements = self.parseStatementSequence()
|
|
530 self.Consume('end')
|
4
|
531 return self.setLocation(ForStatement(variable, begin, end, increment, statements), loc)
|
1
|
532
|
|
533 def parseAsmcode(self):
|
4
|
534 # TODO: move this to seperate file
|
1
|
535 def parseOpcode():
|
|
536 return self.Consume('ID')
|
|
537 def parseOperand():
|
|
538 if self.hasConsumed('['):
|
|
539 memref = []
|
|
540 memref.append(parseOperand())
|
|
541 self.Consume(']')
|
|
542 return memref
|
|
543 else:
|
|
544 if self.token.typ == 'NUMBER':
|
|
545 return self.Consume('NUMBER')
|
|
546 else:
|
|
547 ID = self.Consume('ID')
|
|
548 if self.cst.has(Variable, ID):
|
|
549 return self.cst.get(Variable, ID)
|
|
550 else:
|
|
551 return ID
|
|
552
|
|
553 def parseOperands(n):
|
|
554 operands = []
|
|
555 if n > 0:
|
|
556 operands.append( parseOperand() )
|
|
557 n = n - 1
|
|
558 while n > 0:
|
|
559 self.Consume(',')
|
|
560 operands.append(parseOperand())
|
|
561 n = n - 1
|
|
562 return operands
|
|
563 self.Consume('asm')
|
|
564 asmcode = []
|
|
565 while self.token.typ != 'end':
|
|
566 opcode = parseOpcode()
|
|
567 func, numargs = assembler.opcodes[opcode]
|
|
568 operands = parseOperands(numargs)
|
|
569 asmcode.append( (opcode, operands) )
|
|
570 #print('opcode', opcode, operands)
|
|
571 self.Consume('end')
|
|
572 return AsmCode(asmcode)
|
|
573
|
|
574 def parseStatement(self):
|
5
|
575 try:
|
|
576 # Determine statement type based on the pending token:
|
|
577 if self.token.typ == 'if':
|
|
578 return self.parseIfStatement()
|
|
579 elif self.token.typ == 'case':
|
|
580 return self.parseCaseStatement()
|
|
581 elif self.token.typ == 'while':
|
|
582 return self.parseWhileStatement()
|
|
583 elif self.token.typ == 'repeat':
|
|
584 return self.parseRepeatStatement()
|
|
585 elif self.token.typ == 'for':
|
|
586 return self.parseForStatement()
|
|
587 elif self.token.typ == 'asm':
|
|
588 return self.parseAsmcode()
|
|
589 elif self.token.typ == 'ID':
|
|
590 # Assignment or procedure call
|
|
591 designator = self.parseDesignator()
|
|
592 if self.token.typ == '(' and type(designator.typ) is ProcedureType:
|
|
593 return self.parseProcedureCall(designator)
|
|
594 elif self.token.typ == ':=':
|
|
595 return self.parseAssignment(designator)
|
|
596 else:
|
|
597 self.Error('Unknown statement following designator: {0}'.format(self.token))
|
1
|
598 else:
|
5
|
599 # TODO: return empty statement??:
|
|
600 return EmptyStatement()
|
|
601 self.Error('Unknown statement {0}'.format(self.token))
|
|
602 except CompilerException as e:
|
|
603 print(e)
|
|
604 self.errorlist.append( (e.row, e.col, e.msg))
|
|
605 return EmptyStatement()
|
1
|
606
|
|
607 def parseStatementSequence(self):
|
|
608 """ Sequence of statements seperated by ';' """
|
|
609 statements = [ self.parseStatement() ]
|
|
610 while self.hasConsumed(';'):
|
|
611 statements.append( self.parseStatement() )
|
|
612 return StatementSequence( statements )
|
|
613
|
|
614 # Parsing expressions:
|
|
615 """
|
|
616 grammar of expressions:
|
|
617 expression = SimpleExpression [ reloperator SimpleExpression ]
|
|
618 reloperator = '=' | '<=' | '>=' | '<>'
|
|
619 Simpleexpression = [ '+' | '-' ] term { addoperator term }
|
|
620 addoperator = '+' | '-' | 'or'
|
|
621 term = factor { muloperator factor }
|
|
622 muloperator = '*' | '/' | 'div' | 'mod' | 'and'
|
|
623 factor = number | nil | true | false | "(" expression ")" |
|
|
624 designator [ actualparameters ] | 'not' factor
|
|
625 """
|
|
626 def parseExpression(self):
|
|
627 """ The connector between the boolean and expression domain """
|
|
628 expr = self.parseSimpleExpression()
|
|
629 if self.token.typ in ['>=','<=','<','>','<>','=']:
|
|
630 relop = self.Consume()
|
|
631 expr2 = self.parseSimpleExpression()
|
|
632 # Automatic type convert to reals:
|
|
633 if isType(expr.typ, real) and isType(expr2.typ, integer):
|
|
634 expr2 = Unop(expr2, 'INTTOREAL', real)
|
|
635 if isType(expr2.typ, real) and isType(expr.typ, integer):
|
|
636 expr = Unop(expr, 'INTTOREAL', real)
|
|
637 # Type check:
|
|
638 if not isType(expr.typ, expr2.typ):
|
|
639 self.Error('Type mismatch in relop')
|
|
640 if isType(expr.typ, real) and relop in ['<>', '=']:
|
|
641 self.Error('Cannot check real values for equality')
|
|
642
|
|
643 expr = Relop(expr, relop, expr2, boolean)
|
|
644 return expr
|
|
645
|
|
646 # Parsing arithmatic expressions:
|
|
647 def parseTerm(self):
|
|
648 a = self.parseFactor()
|
|
649 while self.token.typ in ['*', '/', 'mod', 'div', 'and']:
|
4
|
650 loc = self.getLocation()
|
1
|
651 op = self.Consume()
|
|
652 b = self.parseTerm()
|
|
653 # Type determination and checking:
|
|
654 if op in ['mod', 'div']:
|
|
655 if not isType(a.typ, integer):
|
|
656 self.Error('First operand should be integer, not {0}'.format(a.typ))
|
|
657 if not isType(b.typ, integer):
|
|
658 self.Error('Second operand should be integer, not {0}'.format(b.typ))
|
|
659 typ = integer
|
|
660 elif op == '*':
|
|
661 if isType(a.typ, integer) and isType(b.typ, integer):
|
|
662 typ = integer
|
|
663 elif isType(a.typ, real) or isType(b.typ, real):
|
|
664 if isType(a.typ, integer):
|
|
665 # Automatic type cast
|
|
666 a = Unop(a, 'INTTOREAL', real)
|
|
667 if isType(b.typ, integer):
|
|
668 b = Unop(b, 'INTTOREAL', real)
|
|
669 if not isType(a.typ, real):
|
|
670 self.Error('first operand must be a real!')
|
|
671 if not isType(b.typ, real):
|
|
672 self.Error('second operand must be a real!')
|
|
673 typ = real
|
|
674 else:
|
|
675 self.Error('Unknown operands for multiply: {0}, {1}'.format(a, b))
|
|
676 elif op == '/':
|
|
677 # Division always yields a real result, for integer division use div
|
|
678 if isType(a.typ, integer):
|
|
679 # Automatic type cast
|
|
680 a = Unop(a, 'INTTOREAL', real)
|
|
681 if isType(b.typ, integer):
|
|
682 b = Unop(b, 'INTTOREAL', real)
|
|
683 if not isType(a.typ, real):
|
|
684 self.Error('first operand must be a real!')
|
|
685 if not isType(b.typ, real):
|
|
686 self.Error('second operand must be a real!')
|
|
687 typ = real
|
|
688 elif op == 'and':
|
|
689 if not isType(a.typ, boolean):
|
|
690 self.Error('First operand of and must be boolean')
|
|
691 if not isType(b.typ, boolean):
|
|
692 self.Error('Second operand of and must be boolean')
|
|
693 typ = boolean
|
|
694 else:
|
|
695 self.Error('Unknown operand {0}'.format(op))
|
|
696
|
4
|
697 a = self.setLocation(Binop(a, op, b, typ), loc)
|
1
|
698 return a
|
|
699
|
|
700 def parseFactor(self):
|
|
701 if self.hasConsumed('('):
|
|
702 e = self.parseExpression()
|
|
703 self.Consume(')')
|
|
704 return e
|
|
705 elif self.token.typ == 'NUMBER':
|
4
|
706 loc = self.getLocation()
|
|
707 val = self.Consume('NUMBER')
|
|
708 return self.setLocation(Constant(val, integer), loc)
|
1
|
709 elif self.token.typ == 'REAL':
|
4
|
710 loc = self.getLocation()
|
|
711 val = self.Consume('REAL')
|
|
712 return self.setLocation(Constant(val, real), loc)
|
1
|
713 elif self.token.typ == 'CHAR':
|
|
714 val = self.Consume('CHAR')
|
|
715 return Constant(val, char)
|
|
716 elif self.token.typ == 'STRING':
|
|
717 txt = self.Consume('STRING')
|
|
718 return StringConstant(txt)
|
|
719 elif self.token.typ in ['true', 'false']:
|
|
720 val = self.Consume()
|
|
721 val = True if val == 'true' else False
|
|
722 return Constant(val, boolean)
|
|
723 elif self.hasConsumed('nil'):
|
|
724 return Constant(0, NilType())
|
|
725 elif self.hasConsumed('not'):
|
|
726 f = self.parseFactor()
|
|
727 if not isType(f.typ, boolean):
|
|
728 self.Error('argument of boolean negation must be boolean type')
|
|
729 return Unop(f, 'not', boolean)
|
|
730 elif self.token.typ == 'ID':
|
|
731 designator = self.parseDesignator()
|
|
732 # TODO: handle functions different here?
|
|
733 if self.token.typ == '(' and type(designator.typ) is ProcedureType:
|
|
734 return self.parseProcedureCall(designator)
|
|
735 else:
|
|
736 return designator
|
|
737 else:
|
|
738 self.Error('Expected NUMBER, ID or ( expr ), got'+str(self.token))
|
|
739
|
|
740 def parseSimpleExpression(self):
|
|
741 """ Arithmatic expression """
|
|
742 if self.token.typ in ['+', '-']:
|
|
743 # Handle the unary minus
|
|
744 op = self.Consume()
|
|
745 a = self.parseTerm()
|
|
746 typ = a.typ
|
|
747 if not isType(typ,real) and not isType(typ, integer):
|
|
748 self.Error('Unary minus or plus can be only applied to real or integers')
|
|
749 if op == '-':
|
|
750 a = Unop(a, op, typ)
|
|
751 else:
|
|
752 a = self.parseTerm()
|
|
753 while self.token.typ in ['+', '-', 'or']:
|
4
|
754 loc = self.getLocation()
|
1
|
755 op = self.Consume()
|
|
756 b = self.parseTerm()
|
|
757 if op in ['+', '-']:
|
|
758 if isType(a.typ, real) or isType(b.typ, real):
|
|
759 typ = real
|
|
760 if isType(a.typ, integer):
|
|
761 # Automatic type cast
|
|
762 a = Unop(a, 'INTTOREAL', real)
|
|
763 if not isType(a.typ, real):
|
|
764 self.Error('first operand must be a real!')
|
|
765 if isType(b.typ, integer):
|
|
766 b = Unop(b, 'INTTOREAL', real)
|
|
767 if not isType(b.typ, real):
|
|
768 self.Error('second operand must be a real!')
|
|
769 elif isType(a.typ, integer) and isType(b.typ, integer):
|
|
770 typ = integer
|
|
771 else:
|
|
772 self.Error('Invalid types {0} and {1}'.format(a.typ, b.typ))
|
|
773 elif op == 'or':
|
|
774 if not isType(a.typ, boolean):
|
|
775 self.Error('first operand must be boolean for or operation')
|
|
776 if not isType(b.typ, boolean):
|
|
777 self.Error('second operand must be boolean for or operation')
|
|
778 typ = boolean
|
|
779 else:
|
|
780 self.Error('Unknown operand {0}'.format(op))
|
4
|
781 a = self.setLocation(Binop(a, op, b, typ), loc)
|
1
|
782 return a
|
|
783
|