Mercurial > lcfOS
view python/c3/codegenerator.py @ 157:8f3924b6076e
Added some code generator things
author | Windel Bouwman |
---|---|
date | Sun, 03 Mar 2013 18:14:35 +0100 |
parents | 1b4a85bdd99c |
children | 9683a4cd848f |
line wrap: on
line source
import ir from . import astnodes def genModule(pkg): m = ir.Module(pkg.name) for s in pkg.scope: if type(s) is astnodes.Variable: genGlobal(m, s) elif type(s) is astnodes.Function: genFunction(m, s) else: print(s) return m def genGlobal(m, var): v = ir.Value() v.name = var.name m.Globals.append(v) def genFunction(m, fnc): ft = genType(fnc.typ) f = ir.Function(fnc.name, ft) m.Globals.append(f) bb = ir.BasicBlock() f.BasicBlocks.append(bb) genCode(bb, fnc.body) def genCode(bb, code): if type(code) is astnodes.CompoundStatement: for s in code.statements: genCode(bb, s) elif type(code) is astnodes.Assignment: genCode(bb, code.rval) print('assign') elif type(code) is astnodes.IfStatement: genCode(bb, code.condition) genCode(bb, code.truestatement) print('If!') elif type(code) is astnodes.Binop: genCode(bb, code.a) genCode(bb, code.b) a = 1 b = 2 if code.op == '+': bb.Instructions.append(ir.AddInstruction(a, b)) else: bb.Instructions.append(ir.BinaryOperator(code.op, a, b)) elif type(code) is astnodes.Constant: print('CST') bb.Instructions.append(ir.ImmLoadInstruction(code.value)) else: print('Unknown:', code) def genType(t): return ir.Type() class CodeGenerator: """ Generates intermediate code """ def gencode(self, ast): assert type(ast) is astnodes.Package return genModule(ast)