code wiki / (root) / ir_test.nx

ir_test.nx source

↩ module page · 39 lines · 1378 B

1// ir_test.nx -- self-test for ir.nx library. 2// 3// Previously lived inside ir.nx, but module lib/_test split: a module 4// with its own main() can't be imported (main collides). Self-tests 5// move here; import the library and exercise its public API. 6 7import "types.nx" 8import "ir.nx" 9 10// Build an IR for `func main() -> i64 { return 10 + 20 }` and verify 11// structural invariants. We don't print the IR (no backend in this 12// file); just check node counts and that the last instr is a return 13// whose operand's const_int is the add result's id. 14 15func main() -> i64 { 16 let m_raw: *u8 = sys_mmap(256) 17 let m: *Module = m_raw as *Module 18 m.name = "test" as *u8 19 m.functions = 0 as *Function 20 m.n_functions = 0 21 22 let name: *u8 = "main" 23 let f: *Function = ir_function_new(m, name, 4, ir_type_i64()) 24 let b: *BasicBlock = ir_block_new(f) 25 26 let c10: i64 = ir_const_i64(f, 10) 27 let c20: i64 = ir_const_i64(f, 20) 28 let sum: i64 = ir_emit_binop(b, 1, c10, c20, ir_type_i64()) // OP_ADD = 1 29 ir_emit_return(b, sum) 30 31 if f.n_blocks != 1 { return 1 } 32 if b.head == (0 as *Instr) { return 2 } 33 if b.tail == (0 as *Instr) { return 3 } 34 if b.tail.op != OP_RETURN { return 4 } 35 if b.tail.op0 != sum { return 5 } 36 if f.n_values != 3 { return 6 } 37 if f.n_instrs != 2 { return 7 } 38 return 0 39}