Mercurial > lcfOS
annotate python/ppci/c3/codegenerator.py @ 313:04cf4d26a3bc
Added constant function
author | Windel Bouwman |
---|---|
date | Wed, 18 Dec 2013 18:02:26 +0100 |
parents | 2c9768114877 |
children | 084cccaa5deb |
rev | line source |
---|---|
255 | 1 import logging |
301 | 2 from .. import ir |
307 | 3 from .. import irutils |
308 | 4 from . import astnodes as ast |
230 | 5 |
228 | 6 |
307 | 7 class SemanticError(Exception): |
308 | 8 """ Error thrown when a semantic issue is observed """ |
307 | 9 def __init__(self, msg, loc): |
308 | 10 super().__init__() |
307 | 11 self.msg = msg |
12 self.loc = loc | |
13 | |
14 | |
15 class CodeGenerator(irutils.Builder): | |
288 | 16 """ |
274 | 17 Generates intermediate (IR) code from a package. The entry function is |
18 'genModule'. The main task of this part is to rewrite complex control | |
19 structures, such as while and for loops into simple conditional | |
20 jump statements. Also complex conditional statements are simplified. | |
21 Such as 'and' and 'or' statements are rewritten in conditional jumps. | |
22 And structured datatypes are rewritten. | |
307 | 23 |
24 Type checking is done in one run with code generation. | |
274 | 25 """ |
307 | 26 def __init__(self, diag): |
261 | 27 self.logger = logging.getLogger('c3cgen') |
307 | 28 self.diag = diag |
261 | 29 |
217 | 30 def gencode(self, pkg): |
308 | 31 """ Generate code for a single module """ |
268 | 32 self.prepare() |
308 | 33 assert type(pkg) is ast.Package |
307 | 34 self.pkg = pkg |
35 self.intType = pkg.scope['int'] | |
36 self.boolType = pkg.scope['bool'] | |
313 | 37 self.logger.info('Generating ir-code for {}'.format(pkg.name), extra={'c3_ast':pkg}) |
288 | 38 self.varMap = {} # Maps variables to storage locations. |
217 | 39 self.funcMap = {} |
268 | 40 self.m = ir.Module(pkg.name) |
307 | 41 try: |
42 for s in pkg.innerScope.Functions: | |
43 f = self.newFunction(s.name) | |
44 self.funcMap[s] = f | |
45 for v in pkg.innerScope.Variables: | |
46 self.varMap[v] = self.newTemp() | |
47 for s in pkg.innerScope.Functions: | |
308 | 48 self.gen_function(s) |
307 | 49 except SemanticError as e: |
50 self.error(e.msg, e.loc) | |
313 | 51 if self.pkg.ok: |
52 return self.m | |
308 | 53 |
54 def error(self, msg, loc=None): | |
55 self.pkg.ok = False | |
56 self.diag.error(msg, loc) | |
307 | 57 |
58 def checkType(self, t): | |
59 """ Verify the type is correct """ | |
60 t = self.theType(t) | |
174 | 61 |
308 | 62 def gen_function(self, fn): |
268 | 63 # TODO: handle arguments |
64 f = self.funcMap[fn] | |
272 | 65 f.return_value = self.newTemp() |
268 | 66 self.setFunction(f) |
269 | 67 l2 = self.newBlock() |
68 self.emit(ir.Jump(l2)) | |
69 self.setBlock(l2) | |
268 | 70 # generate room for locals: |
174 | 71 |
268 | 72 for sym in fn.innerScope: |
73 # TODO: handle parameters different | |
313 | 74 self.checkType(sym.typ) |
272 | 75 if sym.isParameter: |
308 | 76 variable = ir.Parameter(sym.name) |
77 f.addParameter(variable) | |
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): | |
113 msg = 'Cannot assign {} to {}'.format(code.lval.typ, code.rval.typ) | |
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) | |
222 | 149 else: |
268 | 150 raise NotImplementedError('Unknown stmt {}'.format(code)) |
230 | 151 |
308 | 152 def gen_cond_code(self, expr, bbtrue, bbfalse): |
153 """ Generate conditional logic. | |
154 Implement sequential logical operators. """ | |
155 if type(expr) is ast.Binop: | |
268 | 156 if expr.op == 'or': |
157 l2 = self.newBlock() | |
308 | 158 self.gen_cond_code(expr.a, bbtrue, l2) |
159 if not self.equalTypes(expr.a.typ, self.boolType): | |
307 | 160 raise SemanticError('Must be boolean', expr.a.loc) |
268 | 161 self.setBlock(l2) |
308 | 162 self.gen_cond_code(expr.b, bbtrue, bbfalse) |
163 if not self.equalTypes(expr.b.typ, self.boolType): | |
307 | 164 raise SemanticError('Must be boolean', expr.b.loc) |
268 | 165 elif expr.op == 'and': |
166 l2 = self.newBlock() | |
308 | 167 self.gen_cond_code(expr.a, l2, bbfalse) |
168 if not self.equalTypes(expr.a.typ, self.boolType): | |
307 | 169 self.error('Must be boolean', expr.a.loc) |
268 | 170 self.setBlock(l2) |
308 | 171 self.gen_cond_code(expr.b, bbtrue, bbfalse) |
172 if not self.equalTypes(expr.b.typ, self.boolType): | |
307 | 173 raise SemanticError('Must be boolean', expr.b.loc) |
305 | 174 elif expr.op in ['==', '>', '<', '!=', '<=', '>=']: |
228 | 175 ta = self.genExprCode(expr.a) |
176 tb = self.genExprCode(expr.b) | |
307 | 177 if not self.equalTypes(expr.a.typ, expr.b.typ): |
178 raise SemanticError('Types unequal {} != {}' | |
179 .format(expr.a.typ, expr.b.typ), expr.loc) | |
268 | 180 self.emit(ir.CJump(ta, expr.op, tb, bbtrue, bbfalse)) |
181 else: | |
311 | 182 raise SemanticError('non-bool: {}'.format(expr.op), expr.loc) |
307 | 183 expr.typ = self.boolType |
308 | 184 elif type(expr) is ast.Literal: |
185 self.genExprCode(expr) | |
288 | 186 if expr.val: |
268 | 187 self.emit(ir.Jump(bbtrue)) |
288 | 188 else: |
268 | 189 self.emit(ir.Jump(bbfalse)) |
228 | 190 else: |
288 | 191 raise NotImplementedError('Unknown cond {}'.format(expr)) |
307 | 192 if not self.equalTypes(expr.typ, self.boolType): |
193 self.error('Condition must be boolean', expr.loc) | |
230 | 194 |
217 | 195 def genExprCode(self, expr): |
308 | 196 """ Generate code for an expression. Return the generated ir-value """ |
197 assert isinstance(expr, ast.Expression) | |
198 if type(expr) is ast.Binop: | |
307 | 199 expr.lvalue = False |
200 if expr.op in ['+', '-', '*', '/', '<<', '>>', '|', '&']: | |
201 ra = self.genExprCode(expr.a) | |
202 rb = self.genExprCode(expr.b) | |
203 if self.equalTypes(expr.a.typ, self.intType) and \ | |
204 self.equalTypes(expr.b.typ, self.intType): | |
205 expr.typ = expr.a.typ | |
206 else: | |
207 raise SemanticError('Can only add integers', expr.loc) | |
208 else: | |
209 raise NotImplementedError("Cannot use equality as expressions") | |
268 | 210 return ir.Binop(ra, expr.op, rb) |
308 | 211 elif type(expr) is ast.Unop: |
307 | 212 if expr.op == '&': |
213 ra = self.genExprCode(expr.a) | |
308 | 214 expr.typ = ast.PointerType(expr.a.typ) |
307 | 215 if not expr.a.lvalue: |
216 raise SemanticError('No valid lvalue', expr.a.loc) | |
217 expr.lvalue = False | |
218 assert type(ra) is ir.Mem | |
219 return ra.e | |
220 else: | |
221 raise NotImplementedError('Unknown unop {0}'.format(expr.op)) | |
308 | 222 elif type(expr) is ast.Identifier: |
307 | 223 # Generate code for this identifier. |
224 tg = self.resolveSymbol(expr) | |
225 expr.kind = type(tg) | |
226 expr.typ = tg.typ | |
279 | 227 # This returns the dereferenced variable. |
308 | 228 if isinstance(tg, ast.Variable): |
313 | 229 expr.lvalue = True |
307 | 230 return ir.Mem(self.varMap[tg]) |
313 | 231 elif isinstance(tg, ast.Constant): |
232 c_val = self.genExprCode(tg.value) | |
233 return self.evalConst(c_val) | |
280
02385f62f250
Rework from str interface to Instruction interface
Windel Bouwman
parents:
279
diff
changeset
|
234 else: |
308 | 235 raise NotImplementedError(str(tg)) |
236 elif type(expr) is ast.Deref: | |
222 | 237 # dereference pointer type: |
225 | 238 addr = self.genExprCode(expr.ptr) |
307 | 239 ptr_typ = self.theType(expr.ptr.typ) |
240 expr.lvalue = True | |
308 | 241 if type(ptr_typ) is ast.PointerType: |
307 | 242 expr.typ = ptr_typ.ptype |
243 return ir.Mem(addr) | |
244 else: | |
245 raise SemanticError('Cannot deref non-pointer', expr.loc) | |
308 | 246 elif type(expr) is ast.Member: |
279 | 247 base = self.genExprCode(expr.base) |
307 | 248 expr.lvalue = expr.base.lvalue |
249 basetype = self.theType(expr.base.typ) | |
308 | 250 if type(basetype) is ast.StructureType: |
307 | 251 if basetype.hasField(expr.field): |
252 expr.typ = basetype.fieldType(expr.field) | |
253 else: | |
254 raise SemanticError('{} does not contain field {}' | |
308 | 255 .format(basetype, expr.field), expr.loc) |
307 | 256 else: |
308 | 257 raise SemanticError('Cannot select {} of non-structure type {}' |
258 .format(expr.field, basetype), expr.loc) | |
307 | 259 |
279 | 260 assert type(base) is ir.Mem, type(base) |
307 | 261 bt = self.theType(expr.base.typ) |
268 | 262 offset = ir.Const(bt.fieldOffset(expr.field)) |
308 | 263 return ir.Mem(ir.Add(base.e, offset)) |
264 elif type(expr) is ast.Literal: | |
307 | 265 expr.lvalue = False |
313 | 266 typemap = {int: 'int', float: 'double', bool: 'bool', str:'string'} |
307 | 267 if type(expr.val) in typemap: |
268 expr.typ = self.pkg.scope[typemap[type(expr.val)]] | |
269 else: | |
312 | 270 raise SemanticError('Unknown literal type {}'.format(expr.val), expr.loc) |
268 | 271 return ir.Const(expr.val) |
308 | 272 elif type(expr) is ast.TypeCast: |
273 return self.gen_type_cast(expr) | |
274 elif type(expr) is ast.FunctionCall: | |
275 return self.gen_function_call(expr) | |
225 | 276 else: |
259 | 277 raise NotImplementedError('Unknown expr {}'.format(expr)) |
307 | 278 |
308 | 279 def gen_type_cast(self, expr): |
280 """ Generate code for type casting """ | |
281 ar = self.genExprCode(expr.a) | |
282 from_type = self.theType(expr.a.typ) | |
283 to_type = self.theType(expr.to_type) | |
284 if isinstance(from_type, ast.PointerType) and isinstance(to_type, ast.PointerType): | |
285 expr.typ = expr.to_type | |
286 return ar | |
287 elif type(from_type) is ast.BaseType and from_type.name == 'int' and \ | |
288 isinstance(to_type, ast.PointerType): | |
289 expr.typ = expr.to_type | |
290 return ar | |
291 else: | |
292 raise SemanticError('Cannot cast {} to {}' | |
293 .format(from_type, to_type), expr.loc) | |
294 | |
295 def gen_function_call(self, expr): | |
296 """ Generate code for a function call """ | |
297 # Evaluate the arguments: | |
298 args = [self.genExprCode(e) for e in expr.args] | |
299 # Check arguments: | |
300 tg = self.resolveSymbol(expr.proc) | |
301 if type(tg) is not ast.Function: | |
302 raise SemanticError('cannot call {}'.format(tg)) | |
303 ftyp = tg.typ | |
304 fname = tg.name | |
305 ptypes = ftyp.parametertypes | |
306 if len(expr.args) != len(ptypes): | |
307 raise SemanticError('{} requires {} arguments, {} given' | |
308 .format(fname, len(ptypes), len(expr.args)), expr.loc) | |
309 for arg, at in zip(expr.args, ptypes): | |
310 if not self.equalTypes(arg.typ, at): | |
311 raise SemanticError('Got {}, expected {}' | |
312 .format(arg.typ, at), arg.loc) | |
313 # determine return type: | |
314 expr.typ = ftyp.returntype | |
315 return ir.Call(fname, args) | |
316 | |
313 | 317 def evalConst(self, c): |
318 if isinstance(c, ir.Const): | |
319 return c | |
320 else: | |
321 raise SemanticError('Cannot evaluate constant {}'.format(c)) | |
322 | |
307 | 323 def resolveSymbol(self, sym): |
308 | 324 if type(sym) is ast.Member: |
307 | 325 base = self.resolveSymbol(sym.base) |
308 | 326 if type(base) is not ast.Package: |
327 raise SemanticError('Base is not a package', sym.loc) | |
307 | 328 scope = base.innerScope |
329 name = sym.field | |
308 | 330 elif type(sym) is ast.Identifier: |
307 | 331 scope = sym.scope |
332 name = sym.target | |
333 else: | |
334 raise NotImplementedError(str(sym)) | |
335 if name in scope: | |
336 s = scope[name] | |
337 else: | |
338 raise SemanticError('{} undefined'.format(name), sym.loc) | |
308 | 339 assert isinstance(s, ast.Symbol) |
307 | 340 return s |
341 | |
342 def theType(self, t): | |
343 """ Recurse until a 'real' type is found """ | |
308 | 344 if type(t) is ast.DefinedType: |
307 | 345 t = self.theType(t.typ) |
308 | 346 elif type(t) in [ast.Identifier, ast.Member]: |
307 | 347 t = self.theType(self.resolveSymbol(t)) |
308 | 348 elif isinstance(t, ast.Type): |
307 | 349 pass |
350 else: | |
351 raise NotImplementedError(str(t)) | |
308 | 352 assert isinstance(t, ast.Type) |
307 | 353 return t |
354 | |
355 def equalTypes(self, a, b): | |
356 """ Compare types a and b for structural equavalence. """ | |
357 # Recurse into named types: | |
358 a = self.theType(a) | |
359 b = self.theType(b) | |
308 | 360 assert isinstance(a, ast.Type) |
361 assert isinstance(b, ast.Type) | |
307 | 362 |
363 if type(a) is type(b): | |
308 | 364 if type(a) is ast.BaseType: |
307 | 365 return a.name == b.name |
308 | 366 elif type(a) is ast.PointerType: |
307 | 367 return self.equalTypes(a.ptype, b.ptype) |
308 | 368 elif type(a) is ast.StructureType: |
307 | 369 if len(a.mems) != len(b.mems): |
370 return False | |
371 return all(self.equalTypes(am.typ, bm.typ) for am, bm in | |
372 zip(a.mems, b.mems)) | |
373 else: | |
374 raise NotImplementedError('{} not implemented'.format(type(a))) | |
375 return False |