1
|
1 """
|
|
2 This module parses source code into an abstract syntax tree (AST)
|
|
3 """
|
|
4
|
|
5 import shelve
|
|
6 from .symboltable import SymbolTable
|
|
7 from .nodes import *
|
|
8 from .errors import CompilerException, Error
|
|
9 from .modules import loadModule
|
|
10 from .display import printNode
|
|
11 from .builtin import *
|
|
12 from . import assembler
|
|
13
|
|
14 class Parser:
|
|
15 def __init__(self, tokens):
|
|
16 """ provide the parser with the tokens iterator from the lexer. """
|
|
17 self.tokens = tokens
|
|
18 self.NextToken()
|
|
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):
|
|
363 self.Consume('procedure')
|
4
|
364 i = self.parseIdentDef()
|
|
365 procname = i.name
|
1
|
366 proctyp = self.parseFormalParameters()
|
|
367 procsymtable = SymbolTable(parent = self.cst)
|
|
368 self.cst = procsymtable # Switch symbol table:
|
|
369 # Add parameters as variables to symbol table:
|
|
370 for parameter in proctyp.parameters:
|
|
371 vname = parameter.name
|
|
372 vtyp = parameter.typ
|
|
373 if parameter.kind == 'var':
|
|
374 vtyp = PointerType(vtyp)
|
|
375 variable = Variable(vname, vtyp, False)
|
|
376 if parameter.kind == 'const':
|
|
377 variable.isReadOnly = True
|
|
378 variable.isParameter = True
|
|
379 self.cst.addSymbol(variable)
|
|
380 self.Consume(';')
|
|
381 self.parseDeclarationSequence()
|
|
382 # Mark all variables as local:
|
|
383 for variable in self.cst.getAllLocal(Variable):
|
|
384 variable.isLocal = True
|
|
385
|
|
386 if self.hasConsumed('begin'):
|
|
387 block = self.parseStatementSequence()
|
|
388 if self.hasConsumed('return'):
|
|
389 returnexpression = self.parseExpression()
|
|
390 else:
|
|
391 returnexpression = None
|
|
392
|
|
393 if proctyp.returntype.isType(void):
|
|
394 if not returnexpression is None:
|
|
395 self.Error('Void procedure cannot return a value')
|
|
396 else:
|
|
397 if returnexpression is None:
|
|
398 self.Error('Procedure must return a value')
|
|
399 if not isType(returnexpression.typ, proctyp.returntype):
|
|
400 self.Error('Returned type {0} does not match function return type {1}'.format(returnexpression.typ, proctyp.returntype))
|
|
401
|
|
402 self.Consume('end')
|
|
403 endname = self.Consume('ID')
|
4
|
404 if endname != procname:
|
1
|
405 self.Error('endname should match {0}'.format(name))
|
|
406 self.cst = procsymtable.parent # Switch back to parent symbol table
|
4
|
407 proc = Procedure(procname, proctyp, block, procsymtable, returnexpression)
|
1
|
408 self.cst.addSymbol(proc)
|
4
|
409 proc.public = i.ispublic
|
1
|
410 return proc
|
|
411
|
|
412 # Statements:
|
|
413 def parseAssignment(self, lval):
|
4
|
414 loc = self.getLocation()
|
1
|
415 self.Consume(':=')
|
|
416 rval = self.parseExpression()
|
|
417 if isType(lval.typ, real) and isType(rval.typ, integer):
|
|
418 rval = Unop(rval, 'INTTOREAL', real)
|
|
419 if type(rval.typ) is NilType:
|
|
420 if not type(lval.typ) is ProcedureType and not type(lval.typ) is PointerType:
|
|
421 self.Error('Can assign nil only to pointers or procedure types, not {0}'.format(lval))
|
|
422 elif not isType(lval.typ, rval.typ):
|
|
423 self.Error('Type mismatch {0} != {1}'.format(lval.typ, rval.typ))
|
4
|
424 return self.setLocation(Assignment(lval, rval), loc)
|
1
|
425
|
|
426 def parseExpressionList(self):
|
|
427 expressions = [ self.parseExpression() ]
|
|
428 while self.hasConsumed(','):
|
|
429 expressions.append( self.parseExpression() )
|
|
430 return expressions
|
|
431
|
|
432 def parseProcedureCall(self, procedure):
|
|
433 self.Consume('(')
|
|
434 if self.token.typ != ')':
|
|
435 args = self.parseExpressionList()
|
|
436 else:
|
|
437 args = []
|
|
438 self.Consume(')')
|
|
439 parameters = procedure.typ.parameters
|
|
440 if len(args) != len(parameters):
|
|
441 self.Error("Procedure requires {0} arguments, {1} given".format(len(parameters), len(args)))
|
|
442 for arg, param in zip(args, parameters):
|
|
443 if not arg.typ.isType(param.typ):
|
|
444 print(arg.typ, param.typ)
|
|
445 self.Error('Mismatch in parameter')
|
|
446 return ProcedureCall(procedure, args)
|
|
447
|
|
448 def parseIfStatement(self):
|
4
|
449 loc = self.getLocation()
|
1
|
450 self.Consume('if')
|
|
451 ifs = []
|
|
452 condition = self.parseExpression()
|
|
453 if not isType(condition.typ, boolean):
|
|
454 self.Error('condition of if statement must be boolean')
|
|
455 self.Consume('then')
|
|
456 truestatement = self.parseStatementSequence()
|
|
457 ifs.append( (condition, truestatement) )
|
|
458 while self.hasConsumed('elsif'):
|
|
459 condition = self.parseExpression()
|
|
460 if not isType(condition.typ, boolean):
|
|
461 self.Error('condition of if statement must be boolean')
|
|
462 self.Consume('then')
|
|
463 truestatement = self.parseStatementSequence()
|
|
464 ifs.append( (condition, truestatement) )
|
|
465 if self.hasConsumed('else'):
|
|
466 statement = self.parseStatementSequence()
|
|
467 else:
|
|
468 statement = None
|
|
469 self.Consume('end')
|
|
470 for condition, truestatement in reversed(ifs):
|
|
471 statement = IfStatement(condition, truestatement, statement)
|
4
|
472 return self.setLocation(statement, loc)
|
1
|
473
|
|
474 def parseCase(self):
|
|
475 # TODO
|
|
476 pass
|
|
477
|
|
478 def parseCaseStatement(self):
|
|
479 self.Consume('case')
|
|
480 expr = self.parseExpression()
|
|
481 self.Consume('of')
|
|
482 self.parseCase()
|
|
483 while self.hasConsumed('|'):
|
|
484 self.parseCase()
|
|
485 self.Consume('end')
|
|
486
|
|
487 def parseWhileStatement(self):
|
4
|
488 loc = self.getLocation()
|
1
|
489 self.Consume('while')
|
|
490 condition = self.parseExpression()
|
|
491 self.Consume('do')
|
|
492 statements = self.parseStatementSequence()
|
|
493 if self.hasConsumed('elsif'):
|
|
494 self.Error('elsif in while not yet implemented')
|
|
495 self.Consume('end')
|
4
|
496 return self.setLocation(WhileStatement(condition, statements), loc)
|
1
|
497
|
|
498 def parseRepeatStatement(self):
|
|
499 self.Consume('repeat')
|
|
500 stmt = self.parseStatementSequence()
|
|
501 self.Consume('until')
|
|
502 cond = self.parseBoolExpression()
|
|
503
|
|
504 def parseForStatement(self):
|
4
|
505 loc = self.getLocation()
|
1
|
506 self.Consume('for')
|
|
507 variable = self.parseDesignator()
|
|
508 if not variable.typ.isType(integer):
|
|
509 self.Error('loop variable of for statement must have integer type')
|
|
510 assert(variable.typ.isType(integer))
|
|
511 self.Consume(':=')
|
|
512 begin = self.parseExpression()
|
|
513 if not begin.typ.isType(integer):
|
|
514 self.Error('begin expression of a for statement must have integer type')
|
|
515 self.Consume('to')
|
|
516 end = self.parseExpression()
|
|
517 if not end.typ.isType(integer):
|
|
518 self.Error('end expression of a for statement must have integer type')
|
|
519 if self.hasConsumed('by'):
|
|
520 increment, typ = self.parseConstExpression()
|
|
521 if not typ.isType(integer):
|
|
522 self.Error('Increment must be integer')
|
|
523 else:
|
|
524 increment = 1
|
|
525 assert(type(increment) is int)
|
|
526 self.Consume('do')
|
|
527 statements = self.parseStatementSequence()
|
|
528 self.Consume('end')
|
4
|
529 return self.setLocation(ForStatement(variable, begin, end, increment, statements), loc)
|
1
|
530
|
|
531 def parseAsmcode(self):
|
4
|
532 # TODO: move this to seperate file
|
1
|
533 def parseOpcode():
|
|
534 return self.Consume('ID')
|
|
535 def parseOperand():
|
|
536 if self.hasConsumed('['):
|
|
537 memref = []
|
|
538 memref.append(parseOperand())
|
|
539 self.Consume(']')
|
|
540 return memref
|
|
541 else:
|
|
542 if self.token.typ == 'NUMBER':
|
|
543 return self.Consume('NUMBER')
|
|
544 else:
|
|
545 ID = self.Consume('ID')
|
|
546 if self.cst.has(Variable, ID):
|
|
547 return self.cst.get(Variable, ID)
|
|
548 else:
|
|
549 return ID
|
|
550
|
|
551 def parseOperands(n):
|
|
552 operands = []
|
|
553 if n > 0:
|
|
554 operands.append( parseOperand() )
|
|
555 n = n - 1
|
|
556 while n > 0:
|
|
557 self.Consume(',')
|
|
558 operands.append(parseOperand())
|
|
559 n = n - 1
|
|
560 return operands
|
|
561 self.Consume('asm')
|
|
562 asmcode = []
|
|
563 while self.token.typ != 'end':
|
|
564 opcode = parseOpcode()
|
|
565 func, numargs = assembler.opcodes[opcode]
|
|
566 operands = parseOperands(numargs)
|
|
567 asmcode.append( (opcode, operands) )
|
|
568 #print('opcode', opcode, operands)
|
|
569 self.Consume('end')
|
|
570 return AsmCode(asmcode)
|
|
571
|
|
572 def parseStatement(self):
|
|
573 # Determine statement type based on the pending token:
|
|
574 if self.token.typ == 'if':
|
|
575 return self.parseIfStatement()
|
|
576 elif self.token.typ == 'case':
|
|
577 return self.parseCaseStatement()
|
|
578 elif self.token.typ == 'while':
|
|
579 return self.parseWhileStatement()
|
|
580 elif self.token.typ == 'repeat':
|
|
581 return self.parseRepeatStatement()
|
|
582 elif self.token.typ == 'for':
|
|
583 return self.parseForStatement()
|
|
584 elif self.token.typ == 'asm':
|
|
585 return self.parseAsmcode()
|
|
586 elif self.token.typ == 'ID':
|
|
587 # Assignment or procedure call
|
|
588 designator = self.parseDesignator()
|
|
589 if self.token.typ == '(' and type(designator.typ) is ProcedureType:
|
|
590 return self.parseProcedureCall(designator)
|
|
591 elif self.token.typ == ':=':
|
|
592 return self.parseAssignment(designator)
|
|
593 else:
|
|
594 self.Error('Unknown statement following designator: {0}'.format(self.token))
|
|
595 else:
|
|
596 # TODO: return empty statement??:
|
|
597 return EmptyStatement()
|
|
598 self.Error('Unknown statement {0}'.format(self.token))
|
|
599
|
|
600 def parseStatementSequence(self):
|
|
601 """ Sequence of statements seperated by ';' """
|
|
602 statements = [ self.parseStatement() ]
|
|
603 while self.hasConsumed(';'):
|
|
604 statements.append( self.parseStatement() )
|
|
605 return StatementSequence( statements )
|
|
606
|
|
607 # Parsing expressions:
|
|
608 """
|
|
609 grammar of expressions:
|
|
610 expression = SimpleExpression [ reloperator SimpleExpression ]
|
|
611 reloperator = '=' | '<=' | '>=' | '<>'
|
|
612 Simpleexpression = [ '+' | '-' ] term { addoperator term }
|
|
613 addoperator = '+' | '-' | 'or'
|
|
614 term = factor { muloperator factor }
|
|
615 muloperator = '*' | '/' | 'div' | 'mod' | 'and'
|
|
616 factor = number | nil | true | false | "(" expression ")" |
|
|
617 designator [ actualparameters ] | 'not' factor
|
|
618 """
|
|
619 def parseExpression(self):
|
|
620 """ The connector between the boolean and expression domain """
|
|
621 expr = self.parseSimpleExpression()
|
|
622 if self.token.typ in ['>=','<=','<','>','<>','=']:
|
|
623 relop = self.Consume()
|
|
624 expr2 = self.parseSimpleExpression()
|
|
625 # Automatic type convert to reals:
|
|
626 if isType(expr.typ, real) and isType(expr2.typ, integer):
|
|
627 expr2 = Unop(expr2, 'INTTOREAL', real)
|
|
628 if isType(expr2.typ, real) and isType(expr.typ, integer):
|
|
629 expr = Unop(expr, 'INTTOREAL', real)
|
|
630 # Type check:
|
|
631 if not isType(expr.typ, expr2.typ):
|
|
632 self.Error('Type mismatch in relop')
|
|
633 if isType(expr.typ, real) and relop in ['<>', '=']:
|
|
634 self.Error('Cannot check real values for equality')
|
|
635
|
|
636 expr = Relop(expr, relop, expr2, boolean)
|
|
637 return expr
|
|
638
|
|
639 # Parsing arithmatic expressions:
|
|
640 def parseTerm(self):
|
|
641 a = self.parseFactor()
|
|
642 while self.token.typ in ['*', '/', 'mod', 'div', 'and']:
|
4
|
643 loc = self.getLocation()
|
1
|
644 op = self.Consume()
|
|
645 b = self.parseTerm()
|
|
646 # Type determination and checking:
|
|
647 if op in ['mod', 'div']:
|
|
648 if not isType(a.typ, integer):
|
|
649 self.Error('First operand should be integer, not {0}'.format(a.typ))
|
|
650 if not isType(b.typ, integer):
|
|
651 self.Error('Second operand should be integer, not {0}'.format(b.typ))
|
|
652 typ = integer
|
|
653 elif op == '*':
|
|
654 if isType(a.typ, integer) and isType(b.typ, integer):
|
|
655 typ = integer
|
|
656 elif isType(a.typ, real) or isType(b.typ, real):
|
|
657 if isType(a.typ, integer):
|
|
658 # Automatic type cast
|
|
659 a = Unop(a, 'INTTOREAL', real)
|
|
660 if isType(b.typ, integer):
|
|
661 b = Unop(b, 'INTTOREAL', real)
|
|
662 if not isType(a.typ, real):
|
|
663 self.Error('first operand must be a real!')
|
|
664 if not isType(b.typ, real):
|
|
665 self.Error('second operand must be a real!')
|
|
666 typ = real
|
|
667 else:
|
|
668 self.Error('Unknown operands for multiply: {0}, {1}'.format(a, b))
|
|
669 elif op == '/':
|
|
670 # Division always yields a real result, for integer division use div
|
|
671 if isType(a.typ, integer):
|
|
672 # Automatic type cast
|
|
673 a = Unop(a, 'INTTOREAL', real)
|
|
674 if isType(b.typ, integer):
|
|
675 b = Unop(b, 'INTTOREAL', real)
|
|
676 if not isType(a.typ, real):
|
|
677 self.Error('first operand must be a real!')
|
|
678 if not isType(b.typ, real):
|
|
679 self.Error('second operand must be a real!')
|
|
680 typ = real
|
|
681 elif op == 'and':
|
|
682 if not isType(a.typ, boolean):
|
|
683 self.Error('First operand of and must be boolean')
|
|
684 if not isType(b.typ, boolean):
|
|
685 self.Error('Second operand of and must be boolean')
|
|
686 typ = boolean
|
|
687 else:
|
|
688 self.Error('Unknown operand {0}'.format(op))
|
|
689
|
4
|
690 a = self.setLocation(Binop(a, op, b, typ), loc)
|
1
|
691 return a
|
|
692
|
|
693 def parseFactor(self):
|
|
694 if self.hasConsumed('('):
|
|
695 e = self.parseExpression()
|
|
696 self.Consume(')')
|
|
697 return e
|
|
698 elif self.token.typ == 'NUMBER':
|
4
|
699 loc = self.getLocation()
|
|
700 val = self.Consume('NUMBER')
|
|
701 return self.setLocation(Constant(val, integer), loc)
|
1
|
702 elif self.token.typ == 'REAL':
|
4
|
703 loc = self.getLocation()
|
|
704 val = self.Consume('REAL')
|
|
705 return self.setLocation(Constant(val, real), loc)
|
1
|
706 elif self.token.typ == 'CHAR':
|
|
707 val = self.Consume('CHAR')
|
|
708 return Constant(val, char)
|
|
709 elif self.token.typ == 'STRING':
|
|
710 txt = self.Consume('STRING')
|
|
711 return StringConstant(txt)
|
|
712 elif self.token.typ in ['true', 'false']:
|
|
713 val = self.Consume()
|
|
714 val = True if val == 'true' else False
|
|
715 return Constant(val, boolean)
|
|
716 elif self.hasConsumed('nil'):
|
|
717 return Constant(0, NilType())
|
|
718 elif self.hasConsumed('not'):
|
|
719 f = self.parseFactor()
|
|
720 if not isType(f.typ, boolean):
|
|
721 self.Error('argument of boolean negation must be boolean type')
|
|
722 return Unop(f, 'not', boolean)
|
|
723 elif self.token.typ == 'ID':
|
|
724 designator = self.parseDesignator()
|
|
725 # TODO: handle functions different here?
|
|
726 if self.token.typ == '(' and type(designator.typ) is ProcedureType:
|
|
727 return self.parseProcedureCall(designator)
|
|
728 else:
|
|
729 return designator
|
|
730 else:
|
|
731 self.Error('Expected NUMBER, ID or ( expr ), got'+str(self.token))
|
|
732
|
|
733 def parseSimpleExpression(self):
|
|
734 """ Arithmatic expression """
|
|
735 if self.token.typ in ['+', '-']:
|
|
736 # Handle the unary minus
|
|
737 op = self.Consume()
|
|
738 a = self.parseTerm()
|
|
739 typ = a.typ
|
|
740 if not isType(typ,real) and not isType(typ, integer):
|
|
741 self.Error('Unary minus or plus can be only applied to real or integers')
|
|
742 if op == '-':
|
|
743 a = Unop(a, op, typ)
|
|
744 else:
|
|
745 a = self.parseTerm()
|
|
746 while self.token.typ in ['+', '-', 'or']:
|
4
|
747 loc = self.getLocation()
|
1
|
748 op = self.Consume()
|
|
749 b = self.parseTerm()
|
|
750 if op in ['+', '-']:
|
|
751 if isType(a.typ, real) or isType(b.typ, real):
|
|
752 typ = real
|
|
753 if isType(a.typ, integer):
|
|
754 # Automatic type cast
|
|
755 a = Unop(a, 'INTTOREAL', real)
|
|
756 if not isType(a.typ, real):
|
|
757 self.Error('first operand must be a real!')
|
|
758 if isType(b.typ, integer):
|
|
759 b = Unop(b, 'INTTOREAL', real)
|
|
760 if not isType(b.typ, real):
|
|
761 self.Error('second operand must be a real!')
|
|
762 elif isType(a.typ, integer) and isType(b.typ, integer):
|
|
763 typ = integer
|
|
764 else:
|
|
765 self.Error('Invalid types {0} and {1}'.format(a.typ, b.typ))
|
|
766 elif op == 'or':
|
|
767 if not isType(a.typ, boolean):
|
|
768 self.Error('first operand must be boolean for or operation')
|
|
769 if not isType(b.typ, boolean):
|
|
770 self.Error('second operand must be boolean for or operation')
|
|
771 typ = boolean
|
|
772 else:
|
|
773 self.Error('Unknown operand {0}'.format(op))
|
4
|
774 a = self.setLocation(Binop(a, op, b, typ), loc)
|
1
|
775 return a
|
|
776
|