def __init__(self): ModulePass.__init__(self) IRBaseVisitor.__init__(self) self.function_block_mapping = [] self.current_bb = None self.function_code = {} self.fn_stack = [] self.emit = EmitJS()
class JSCodeGen(ModulePass, IRBaseVisitor): def __init__(self): ModulePass.__init__(self) IRBaseVisitor.__init__(self) self.function_block_mapping = [] self.current_bb = None self.function_code = {} self.fn_stack = [] self.emit = EmitJS() def current_fn(self): return self.fn_stack[-1] def get_code(self): js_code = "" for name, fn in self.function_code.items(): js_code += str(fn) # Run the main function() js_code += "\nconsole.log(main());" return js_code @verify(node=Module) def run_on_module(self, node): draw_header("Javascript Code Generation") # Generate code for "main" if "main" not in node.functions: raise Exception("No main function in the IR") self.visit(node.functions["main"], []) def visit_function(self, node, arglist): self.emit.indent() fn = JSFunction(node.name) self.function_code[node.name] = fn self.fn_stack.append(fn) for bb in node.basic_blocks: self.visit(bb) def visit_basicblock(self, node): # Create a new assembly block for inst in node.instructions: self.visit(inst) def visit_returninstruction(self, node): inst = self.emit.ret(node.value.name) self.current_fn().append(inst) def visit_addinstruction(self, node): pass def visit_subinstruction(self, node): pass def visit_mulinstruction(self, node): inst = self.emit.binary_inst(node.lhs, '*', node.rhs, node.name) self.current_fn().append(inst) def visit_divinstruction(self, node): pass