Mercurial > lcfOS
annotate python/ppci/c3/codegenerator.py @ 360:42343d189e14
Bugfix in for loop
author | Windel Bouwman |
---|---|
date | Fri, 14 Mar 2014 16:11:32 +0100 |
parents | 5477e499b039 |
children | c05ab629976a |
rev | line source |
---|---|
255 | 1 import logging |
354 | 2 import struct |
301 | 3 from .. import ir |
307 | 4 from .. import irutils |
308 | 5 from . import astnodes as ast |
230 | 6 |
228 | 7 |
307 | 8 class SemanticError(Exception): |
308 | 9 """ Error thrown when a semantic issue is observed """ |
307 | 10 def __init__(self, msg, loc): |
308 | 11 super().__init__() |
307 | 12 self.msg = msg |
13 self.loc = loc | |
14 | |
15 | |
16 class CodeGenerator(irutils.Builder): | |
288 | 17 """ |
274 | 18 Generates intermediate (IR) code from a package. The entry function is |
19 'genModule'. The main task of this part is to rewrite complex control | |
20 structures, such as while and for loops into simple conditional | |
21 jump statements. Also complex conditional statements are simplified. | |
22 Such as 'and' and 'or' statements are rewritten in conditional jumps. | |
23 And structured datatypes are rewritten. | |
307 | 24 |
25 Type checking is done in one run with code generation. | |
274 | 26 """ |
307 | 27 def __init__(self, diag): |
261 | 28 self.logger = logging.getLogger('c3cgen') |
307 | 29 self.diag = diag |
261 | 30 |
217 | 31 def gencode(self, pkg): |
308 | 32 """ Generate code for a single module """ |
268 | 33 self.prepare() |
308 | 34 assert type(pkg) is ast.Package |
307 | 35 self.pkg = pkg |
36 self.intType = pkg.scope['int'] | |
37 self.boolType = pkg.scope['bool'] | |
334 | 38 self.logger.debug('Generating ir-code for {}'.format(pkg.name), extra={'c3_ast':pkg}) |
288 | 39 self.varMap = {} # Maps variables to storage locations. |
217 | 40 self.funcMap = {} |
268 | 41 self.m = ir.Module(pkg.name) |
307 | 42 try: |
43 for s in pkg.innerScope.Functions: | |
44 f = self.newFunction(s.name) | |
45 self.funcMap[s] = f | |
46 for v in pkg.innerScope.Variables: | |
47 self.varMap[v] = self.newTemp() | |
48 for s in pkg.innerScope.Functions: | |
308 | 49 self.gen_function(s) |
307 | 50 except SemanticError as e: |
51 self.error(e.msg, e.loc) | |
313 | 52 if self.pkg.ok: |
53 return self.m | |
308 | 54 |
55 def error(self, msg, loc=None): | |
56 self.pkg.ok = False | |
57 self.diag.error(msg, loc) | |
307 | 58 |
308 | 59 def gen_function(self, fn): |
268 | 60 # TODO: handle arguments |
61 f = self.funcMap[fn] | |
272 | 62 f.return_value = self.newTemp() |
268 | 63 self.setFunction(f) |
269 | 64 l2 = self.newBlock() |
65 self.emit(ir.Jump(l2)) | |
66 self.setBlock(l2) | |
268 | 67 # generate room for locals: |
174 | 68 |
268 | 69 for sym in fn.innerScope: |
316 | 70 self.the_type(sym.typ) |
272 | 71 if sym.isParameter: |
316 | 72 p = ir.Parameter(sym.name) |
73 variable = ir.LocalVariable(sym.name + '_copy') | |
74 f.addParameter(p) | |
75 f.addLocal(variable) | |
76 # Move parameter into local copy: | |
77 self.emit(ir.Move(ir.Mem(variable), p)) | |
274 | 78 elif sym.isLocal: |
308 | 79 variable = ir.LocalVariable(sym.name) |
80 f.addLocal(variable) | |
81 elif isinstance(sym, ast.Variable): | |
82 variable = ir.LocalVariable(sym.name) | |
83 f.addLocal(variable) | |
274 | 84 else: |
275 | 85 raise NotImplementedError('{}'.format(sym)) |
308 | 86 self.varMap[sym] = variable |
268 | 87 |
88 self.genCode(fn.body) | |
272 | 89 self.emit(ir.Move(f.return_value, ir.Const(0))) |
269 | 90 self.emit(ir.Jump(f.epiloog)) |
268 | 91 self.setFunction(None) |
158 | 92 |
217 | 93 def genCode(self, code): |
308 | 94 """ Wrapper around gen_stmt to catch errors """ |
307 | 95 try: |
308 | 96 self.gen_stmt(code) |
307 | 97 except SemanticError as e: |
98 self.error(e.msg, e.loc) | |
99 | |
308 | 100 def gen_stmt(self, code): |
101 """ Generate code for a statement """ | |
102 assert isinstance(code, ast.Statement) | |
268 | 103 self.setLoc(code.loc) |
308 | 104 if type(code) is ast.Compound: |
221 | 105 for s in code.statements: |
106 self.genCode(s) | |
308 | 107 elif type(code) is ast.Empty: |
306 | 108 pass |
308 | 109 elif type(code) is ast.Assignment: |
268 | 110 lval = self.genExprCode(code.lval) |
307 | 111 rval = self.genExprCode(code.rval) |
112 if not self.equalTypes(code.lval.typ, code.rval.typ): | |
315 | 113 msg = 'Cannot assign {} to {}'.format(code.rval.typ, code.lval.typ) |
307 | 114 raise SemanticError(msg, code.loc) |
115 if not code.lval.lvalue: | |
116 raise SemanticError('No valid lvalue {}'.format(code.lval), code.lval.loc) | |
268 | 117 self.emit(ir.Move(lval, rval)) |
308 | 118 elif type(code) is ast.ExpressionStatement: |
275 | 119 self.emit(ir.Exp(self.genExprCode(code.ex))) |
308 | 120 elif type(code) is ast.If: |
268 | 121 bbtrue = self.newBlock() |
122 bbfalse = self.newBlock() | |
123 te = self.newBlock() | |
308 | 124 self.gen_cond_code(code.condition, bbtrue, bbfalse) |
268 | 125 self.setBlock(bbtrue) |
126 self.genCode(code.truestatement) | |
127 self.emit(ir.Jump(te)) | |
128 self.setBlock(bbfalse) | |
306 | 129 self.genCode(code.falsestatement) |
268 | 130 self.emit(ir.Jump(te)) |
131 self.setBlock(te) | |
308 | 132 elif type(code) is ast.Return: |
303 | 133 re = self.genExprCode(code.expr) |
134 self.emit(ir.Move(self.fn.return_value, re)) | |
135 self.emit(ir.Jump(self.fn.epiloog)) | |
136 b = self.newBlock() | |
137 self.setBlock(b) | |
308 | 138 elif type(code) is ast.While: |
268 | 139 bbdo = self.newBlock() |
140 bbtest = self.newBlock() | |
141 te = self.newBlock() | |
142 self.emit(ir.Jump(bbtest)) | |
143 self.setBlock(bbtest) | |
308 | 144 self.gen_cond_code(code.condition, bbdo, te) |
268 | 145 self.setBlock(bbdo) |
228 | 146 self.genCode(code.statement) |
268 | 147 self.emit(ir.Jump(bbtest)) |
148 self.setBlock(te) | |
315 | 149 elif type(code) is ast.For: |
150 bbdo = self.newBlock() | |
151 bbtest = self.newBlock() | |
152 te = self.newBlock() | |
153 self.genCode(code.init) | |
154 self.emit(ir.Jump(bbtest)) | |
155 self.setBlock(bbtest) | |
156 self.gen_cond_code(code.condition, bbdo, te) | |
157 self.setBlock(bbdo) | |
158 self.genCode(code.statement) | |
360 | 159 self.genCode(code.final) |
315 | 160 self.emit(ir.Jump(bbtest)) |
161 self.setBlock(te) | |
222 | 162 else: |
268 | 163 raise NotImplementedError('Unknown stmt {}'.format(code)) |
230 | 164 |
308 | 165 def gen_cond_code(self, expr, bbtrue, bbfalse): |
166 """ Generate conditional logic. | |
167 Implement sequential logical operators. """ | |
168 if type(expr) is ast.Binop: | |
268 | 169 if expr.op == 'or': |
170 l2 = self.newBlock() | |
308 | 171 self.gen_cond_code(expr.a, bbtrue, l2) |
172 if not self.equalTypes(expr.a.typ, self.boolType): | |
307 | 173 raise SemanticError('Must be boolean', expr.a.loc) |
268 | 174 self.setBlock(l2) |
308 | 175 self.gen_cond_code(expr.b, bbtrue, bbfalse) |
176 if not self.equalTypes(expr.b.typ, self.boolType): | |
307 | 177 raise SemanticError('Must be boolean', expr.b.loc) |
268 | 178 elif expr.op == 'and': |
179 l2 = self.newBlock() | |
308 | 180 self.gen_cond_code(expr.a, l2, bbfalse) |
181 if not self.equalTypes(expr.a.typ, self.boolType): | |
307 | 182 self.error('Must be boolean', expr.a.loc) |
268 | 183 self.setBlock(l2) |
308 | 184 self.gen_cond_code(expr.b, bbtrue, bbfalse) |
185 if not self.equalTypes(expr.b.typ, self.boolType): | |
307 | 186 raise SemanticError('Must be boolean', expr.b.loc) |
305 | 187 elif expr.op in ['==', '>', '<', '!=', '<=', '>=']: |
228 | 188 ta = self.genExprCode(expr.a) |
189 tb = self.genExprCode(expr.b) | |
307 | 190 if not self.equalTypes(expr.a.typ, expr.b.typ): |
191 raise SemanticError('Types unequal {} != {}' | |
192 .format(expr.a.typ, expr.b.typ), expr.loc) | |
268 | 193 self.emit(ir.CJump(ta, expr.op, tb, bbtrue, bbfalse)) |
194 else: | |
311 | 195 raise SemanticError('non-bool: {}'.format(expr.op), expr.loc) |
307 | 196 expr.typ = self.boolType |
308 | 197 elif type(expr) is ast.Literal: |
198 self.genExprCode(expr) | |
288 | 199 if expr.val: |
268 | 200 self.emit(ir.Jump(bbtrue)) |
288 | 201 else: |
268 | 202 self.emit(ir.Jump(bbfalse)) |
228 | 203 else: |
288 | 204 raise NotImplementedError('Unknown cond {}'.format(expr)) |
354 | 205 |
206 # Check that the condition is a boolean value: | |
307 | 207 if not self.equalTypes(expr.typ, self.boolType): |
208 self.error('Condition must be boolean', expr.loc) | |
230 | 209 |
217 | 210 def genExprCode(self, expr): |
308 | 211 """ Generate code for an expression. Return the generated ir-value """ |
212 assert isinstance(expr, ast.Expression) | |
213 if type(expr) is ast.Binop: | |
307 | 214 expr.lvalue = False |
215 if expr.op in ['+', '-', '*', '/', '<<', '>>', '|', '&']: | |
216 ra = self.genExprCode(expr.a) | |
217 rb = self.genExprCode(expr.b) | |
218 if self.equalTypes(expr.a.typ, self.intType) and \ | |
219 self.equalTypes(expr.b.typ, self.intType): | |
220 expr.typ = expr.a.typ | |
221 else: | |
222 raise SemanticError('Can only add integers', expr.loc) | |
223 else: | |
224 raise NotImplementedError("Cannot use equality as expressions") | |
268 | 225 return ir.Binop(ra, expr.op, rb) |
308 | 226 elif type(expr) is ast.Unop: |
307 | 227 if expr.op == '&': |
228 ra = self.genExprCode(expr.a) | |
308 | 229 expr.typ = ast.PointerType(expr.a.typ) |
307 | 230 if not expr.a.lvalue: |
231 raise SemanticError('No valid lvalue', expr.a.loc) | |
232 expr.lvalue = False | |
233 assert type(ra) is ir.Mem | |
234 return ra.e | |
235 else: | |
236 raise NotImplementedError('Unknown unop {0}'.format(expr.op)) | |
308 | 237 elif type(expr) is ast.Identifier: |
307 | 238 # Generate code for this identifier. |
239 tg = self.resolveSymbol(expr) | |
240 expr.kind = type(tg) | |
241 expr.typ = tg.typ | |
279 | 242 # This returns the dereferenced variable. |
308 | 243 if isinstance(tg, ast.Variable): |
313 | 244 expr.lvalue = True |
307 | 245 return ir.Mem(self.varMap[tg]) |
313 | 246 elif isinstance(tg, ast.Constant): |
247 c_val = self.genExprCode(tg.value) | |
248 return self.evalConst(c_val) | |
280
02385f62f250
Rework from str interface to Instruction interface
Windel Bouwman
parents:
279
diff
changeset
|
249 else: |
308 | 250 raise NotImplementedError(str(tg)) |
251 elif type(expr) is ast.Deref: | |
222 | 252 # dereference pointer type: |
225 | 253 addr = self.genExprCode(expr.ptr) |
316 | 254 ptr_typ = self.the_type(expr.ptr.typ) |
307 | 255 expr.lvalue = True |
308 | 256 if type(ptr_typ) is ast.PointerType: |
307 | 257 expr.typ = ptr_typ.ptype |
258 return ir.Mem(addr) | |
259 else: | |
260 raise SemanticError('Cannot deref non-pointer', expr.loc) | |
308 | 261 elif type(expr) is ast.Member: |
279 | 262 base = self.genExprCode(expr.base) |
307 | 263 expr.lvalue = expr.base.lvalue |
316 | 264 basetype = self.the_type(expr.base.typ) |
308 | 265 if type(basetype) is ast.StructureType: |
307 | 266 if basetype.hasField(expr.field): |
267 expr.typ = basetype.fieldType(expr.field) | |
268 else: | |
269 raise SemanticError('{} does not contain field {}' | |
308 | 270 .format(basetype, expr.field), expr.loc) |
307 | 271 else: |
308 | 272 raise SemanticError('Cannot select {} of non-structure type {}' |
273 .format(expr.field, basetype), expr.loc) | |
307 | 274 |
279 | 275 assert type(base) is ir.Mem, type(base) |
316 | 276 bt = self.the_type(expr.base.typ) |
268 | 277 offset = ir.Const(bt.fieldOffset(expr.field)) |
308 | 278 return ir.Mem(ir.Add(base.e, offset)) |
354 | 279 elif type(expr) is ast.Index: |
280 """ Array indexing """ | |
281 base = self.genExprCode(expr.base) | |
282 idx = self.genExprCode(expr.i) | |
283 base_typ = self.the_type(expr.base.typ) | |
284 if not isinstance(base_typ, ast.ArrayType): | |
285 raise SemanticError('Cannot index non-array type {}'.format(base_typ), expr.base.loc) | |
286 idx_type = self.the_type(expr.i.typ) | |
287 if not self.equalTypes(idx_type, self.intType): | |
288 raise SemanticError('Index must be int not {}'.format(idx_type), expr.i.loc) | |
289 assert type(base) is ir.Mem | |
290 element_type = self.the_type(base_typ.element_type) | |
291 element_size = self.size_of(element_type) | |
292 expr.typ = base_typ.element_type | |
293 expr.lvalue = True | |
294 | |
295 return ir.Mem(ir.Add(base.e, ir.Mul(idx, ir.Const(element_size)))) | |
308 | 296 elif type(expr) is ast.Literal: |
307 | 297 expr.lvalue = False |
313 | 298 typemap = {int: 'int', float: 'double', bool: 'bool', str:'string'} |
307 | 299 if type(expr.val) in typemap: |
300 expr.typ = self.pkg.scope[typemap[type(expr.val)]] | |
301 else: | |
312 | 302 raise SemanticError('Unknown literal type {}'.format(expr.val), expr.loc) |
354 | 303 # Construct correct const value: |
304 if type(expr.val) is str: | |
305 cval = struct.pack('<I', len(expr.val)) + expr.val.encode('ascii') | |
306 return ir.Addr(ir.Const(cval)) | |
307 else: | |
308 return ir.Const(expr.val) | |
308 | 309 elif type(expr) is ast.TypeCast: |
310 return self.gen_type_cast(expr) | |
311 elif type(expr) is ast.FunctionCall: | |
312 return self.gen_function_call(expr) | |
225 | 313 else: |
259 | 314 raise NotImplementedError('Unknown expr {}'.format(expr)) |
307 | 315 |
308 | 316 def gen_type_cast(self, expr): |
317 """ Generate code for type casting """ | |
318 ar = self.genExprCode(expr.a) | |
316 | 319 from_type = self.the_type(expr.a.typ) |
320 to_type = self.the_type(expr.to_type) | |
308 | 321 if isinstance(from_type, ast.PointerType) and isinstance(to_type, ast.PointerType): |
322 expr.typ = expr.to_type | |
323 return ar | |
324 elif type(from_type) is ast.BaseType and from_type.name == 'int' and \ | |
325 isinstance(to_type, ast.PointerType): | |
326 expr.typ = expr.to_type | |
327 return ar | |
354 | 328 elif type(from_type) is ast.BaseType and from_type.name == 'byte' and \ |
329 type(to_type) is ast.BaseType and to_type.name == 'int': | |
330 expr.typ = expr.to_type | |
331 return ar | |
308 | 332 else: |
333 raise SemanticError('Cannot cast {} to {}' | |
334 .format(from_type, to_type), expr.loc) | |
353 | 335 |
308 | 336 def gen_function_call(self, expr): |
337 """ Generate code for a function call """ | |
338 # Evaluate the arguments: | |
339 args = [self.genExprCode(e) for e in expr.args] | |
340 # Check arguments: | |
341 tg = self.resolveSymbol(expr.proc) | |
342 if type(tg) is not ast.Function: | |
343 raise SemanticError('cannot call {}'.format(tg)) | |
344 ftyp = tg.typ | |
336
d1ecc493384e
Added spiffy armtoken class for bit fiddeling. Added cool test that checks for build repeatability
Windel Bouwman
parents:
334
diff
changeset
|
345 fname = tg.package.name + '_' + tg.name |
308 | 346 ptypes = ftyp.parametertypes |
347 if len(expr.args) != len(ptypes): | |
348 raise SemanticError('{} requires {} arguments, {} given' | |
349 .format(fname, len(ptypes), len(expr.args)), expr.loc) | |
350 for arg, at in zip(expr.args, ptypes): | |
351 if not self.equalTypes(arg.typ, at): | |
352 raise SemanticError('Got {}, expected {}' | |
353 .format(arg.typ, at), arg.loc) | |
354 # determine return type: | |
355 expr.typ = ftyp.returntype | |
356 return ir.Call(fname, args) | |
357 | |
313 | 358 def evalConst(self, c): |
359 if isinstance(c, ir.Const): | |
360 return c | |
361 else: | |
362 raise SemanticError('Cannot evaluate constant {}'.format(c)) | |
363 | |
307 | 364 def resolveSymbol(self, sym): |
308 | 365 if type(sym) is ast.Member: |
307 | 366 base = self.resolveSymbol(sym.base) |
308 | 367 if type(base) is not ast.Package: |
368 raise SemanticError('Base is not a package', sym.loc) | |
307 | 369 scope = base.innerScope |
370 name = sym.field | |
308 | 371 elif type(sym) is ast.Identifier: |
307 | 372 scope = sym.scope |
373 name = sym.target | |
374 else: | |
375 raise NotImplementedError(str(sym)) | |
376 if name in scope: | |
377 s = scope[name] | |
378 else: | |
379 raise SemanticError('{} undefined'.format(name), sym.loc) | |
308 | 380 assert isinstance(s, ast.Symbol) |
307 | 381 return s |
382 | |
316 | 383 def size_of(self, t): |
384 """ Determine the byte size of a type """ | |
385 t = self.the_type(t) | |
386 if type(t) is ast.BaseType: | |
387 return t.bytesize | |
388 elif type(t) is ast.StructureType: | |
389 return sum(self.size_of(mem.typ) for mem in t.mems) | |
354 | 390 elif type(t) is ast.ArrayType: |
391 return t.size * self.size_of(t.element_type) | |
316 | 392 else: |
393 raise NotImplementedError(str(t)) | |
394 | |
395 def the_type(self, t): | |
307 | 396 """ Recurse until a 'real' type is found """ |
308 | 397 if type(t) is ast.DefinedType: |
316 | 398 t = self.the_type(t.typ) |
308 | 399 elif type(t) in [ast.Identifier, ast.Member]: |
316 | 400 t = self.the_type(self.resolveSymbol(t)) |
401 elif type(t) is ast.StructureType: | |
402 # Setup offsets of fields. Is this the right place?: | |
403 offset = 0 | |
404 for mem in t.mems: | |
405 mem.offset = offset | |
406 offset = offset + self.size_of(mem.typ) | |
308 | 407 elif isinstance(t, ast.Type): |
307 | 408 pass |
409 else: | |
410 raise NotImplementedError(str(t)) | |
308 | 411 assert isinstance(t, ast.Type) |
307 | 412 return t |
413 | |
414 def equalTypes(self, a, b): | |
415 """ Compare types a and b for structural equavalence. """ | |
416 # Recurse into named types: | |
316 | 417 a = self.the_type(a) |
418 b = self.the_type(b) | |
307 | 419 |
420 if type(a) is type(b): | |
308 | 421 if type(a) is ast.BaseType: |
307 | 422 return a.name == b.name |
308 | 423 elif type(a) is ast.PointerType: |
307 | 424 return self.equalTypes(a.ptype, b.ptype) |
308 | 425 elif type(a) is ast.StructureType: |
307 | 426 if len(a.mems) != len(b.mems): |
427 return False | |
428 return all(self.equalTypes(am.typ, bm.typ) for am, bm in | |
429 zip(a.mems, b.mems)) | |
354 | 430 elif type(a) is ast.ArrayType: |
431 return self.equalTypes(a.element_type, b.element_type) | |
307 | 432 else: |
433 raise NotImplementedError('{} not implemented'.format(type(a))) | |
434 return False |