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