generic_types_test.nx source
↩ module page · 64 lines · 2207 B
1// generic_types_test.nx -- exercises the monomorphization port.
2//
3// Declares a generic struct and uses it with two distinct type
4// arguments in the same module. If monomorphization is working,
5// the two instantiations produce separate Type objects keyed
6// under mangled names (Pair$i64 and Pair$p). If broken, they
7// collapse into one shared struct and the payloads would type-
8// confuse.
9//
10// Today this file is compiled ONLY through nxc2.exe (the C-based
11// compiler using parse.c). That establishes the reference
12// behaviour. When nxc.nx (using parse.nx's ported
13// monomorphization) is bootstrapped through QEMU, compiling
14// this file with it should produce byte-identical output to the
15// nxc2.exe version -- which will confirm parse.nx's
16// instantiate_generic_n logic matches parse.c's for real.
17//
18// For now, the file serves as:
19// 1. A live test-case for parse.c + code-gen of the feature
20// 2. A future regression guard when parse.nx becomes the
21// actual compiler frontend
22// 3. Concrete documentation of what generic struct usage looks
23// like in NishiLang
24
25import "syscalls.nx"
26
27// Template: a two-field record parameterised on one type T.
28struct Pair<T> {
29 first: T,
30 second: T,
31}
32
33// Use with i64 -- concrete monomorph Pair$i64.
34func make_pair_i64(a: i64, b: i64) -> *Pair<i64> {
35 let raw: *u8 = sys_mmap(32)
36 let p: *Pair<i64> = raw as *Pair<i64>
37 p.first = a
38 p.second = b
39 return p
40}
41
42// Use with *u8 -- concrete monomorph Pair$p (different struct).
43func make_pair_str(a: *u8, b: *u8) -> *Pair<*u8> {
44 let raw: *u8 = sys_mmap(32)
45 let p: *Pair<*u8> = raw as *Pair<*u8>
46 p.first = a
47 p.second = b
48 return p
49}
50
51// Compile-only smoke.
52func main() -> i64 {
53 let p1: *Pair<i64> = make_pair_i64(42, 99)
54 if p1.first != 42 { return 1 }
55 if p1.second != 99 { return 2 }
56
57 let p2: *Pair<*u8> = make_pair_str("hello", "world")
58 if p2.first[0] != 0x68 { return 3 } // 'h'
59 if p2.second[0] != 0x77 { return 4 } // 'w'
60
61 // Both instantiations visible in same scope -- demonstrates
62 // distinct-Type-per-instantiation.
63 return 0
64}