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