def inst_function( name: SSym, params: List[Var], return_val: Optional[bytecode.Parameter], *insts: Inst, ) -> SFunction: """Create a function out of the instructions in insts.""" begin = BasicBlock('bb0') for inst in insts: begin.add_inst(inst) if return_val is not None: begin.add_inst(bytecode.ReturnInst(return_val)) code = Function(params, begin) param_syms = [SSym(p.name) for p in params] return SFunction(name, param_syms, Nil, code, False)
def _add_is_function_check( self, function_expr: bytecode.Parameter, add_to_block: bytecode.BasicBlock) -> None: typeof_var = bytecode.Var(next(self.var_names)) typeof_instr = bytecode.TypeofInst( typeof_var, function_expr) is_function_var = bytecode.Var(next(self.var_names)) is_function_instr = bytecode.BinopInst( is_function_var, bytecode.Binop.SYM_EQ, typeof_var, bytecode.SymLit(sexp.SSym('function')) ) branch_instr = bytecode.BrnInst(is_function_var, IS_FUNCTION_TRAP) for instr in [typeof_instr, is_function_instr, branch_instr]: add_to_block.add_inst(instr)
def make_func() -> Function: bb0 = BasicBlock("bb0") bb1 = BasicBlock("bb1") bb0.add_inst(bytecode.CopyInst(Var('v0'), NumLit(SNum(42)))) bb0.add_inst( bytecode.BinopInst(Var('v1'), Binop.ADD, Var('v0'), NumLit(SNum(69)))) bb0.add_inst(bytecode.JmpInst(bb1)) bb1.add_inst(bytecode.ReturnInst(Var('v1'))) return Function([], bb0)
def _add_arity_check( self, function_expr: bytecode.Parameter, add_to_block: bytecode.BasicBlock, arity: int) -> None: arity_var = bytecode.Var(next(self.var_names)) add_to_block.add_inst(bytecode.ArityInst(arity_var, function_expr)) correct_arity_var = bytecode.Var(next(self.var_names)) add_to_block.add_inst(bytecode.BinopInst( correct_arity_var, bytecode.Binop.NUM_EQ, arity_var, bytecode.NumLit(sexp.SNum(arity)) )) add_to_block.add_inst(bytecode.BrnInst(correct_arity_var, ARITY_TRAP))
def make_branch_func_object() -> Tuple[Function, Tuple[BasicBlock, ...]]: bb0 = BasicBlock("bb0") bb1 = BasicBlock("bb1") bb2 = BasicBlock("bb2") bb3 = BasicBlock("bb3") bb0.add_inst(bytecode.CopyInst(Var('v0'), NumLit(SNum(42)))) bb0.add_inst(bytecode.BrInst(Var('x'), bb1)) bb0.add_inst(bytecode.JmpInst(bb2)) bb1.add_inst( bytecode.BinopInst(Var('v0'), Binop.ADD, Var('v0'), NumLit(SNum(27)))) bb1.add_inst(bytecode.JmpInst(bb3)) bb2.add_inst(bytecode.CopyInst(Var('v0'), SymLit(SSym('hi')))) bb2.add_inst(bytecode.JmpInst(bb3)) bb3.add_inst(bytecode.ReturnInst(Var('v0'))) return Function([Var('x')], bb0), (bb0, bb1, bb2, bb3)