code wiki / _hdl_build / nx_grep_test.nx
nx_grep_test.nx source
↩ module page · 40 lines · 2670 B
1// nx_grep_test.nx -- the sovereign grep, proven end to end in NishiLang (write a file, then grep it --
2// no shell grep). Exit 0 on 6/6. license_tier: ORIGINAL
3
4import "nx_grep.nx"
5import "nx_syscalls.nx"
6
7func gt_puts(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } sys_write(1, s, n); return 0 }
8func gt_num(v: i64) -> i64 { let bb: *u8 = sys_mmap(28); var m: i64=v; if m<0 {m=0-m;sys_write(1,"-" as *u8,1)}; let t: *u8 = sys_mmap(28); var k: i64=0; if m==0 {t[0]=48;k=1}; while m>0 {t[k]=48+(m%10); m=m/10; k=k+1}; var i: i64=0; while i<k {bb[i]=t[k-1-i]; i=i+1}; sys_write(1, bb, k); return 0 }
9
10func main() -> i64 {
11 gt_puts("=== SOVEREIGN GREP in NishiLang (no shell grep) ===\n" as *u8)
12 // write a known file
13 let path: *u8 = "/tmp/nxgrep_test.txt" as *u8
14 let content: *u8 = "apple pie\nbanana split\napple core\ncherry tart\n" as *u8
15 var clen: i64 = 0; while content[clen] != (0 as u8) { clen = clen + 1 }
16 let fd: i64 = sys_openat_wr(path, 0x1a4)
17 if fd >= 0 { sys_write(fd, content, clen); sys_close(fd) }
18
19 let apples: i64 = grep_count(path, "apple" as *u8)
20 let has_banana: i64 = grep_has(path, "banana" as *u8)
21 let has_zzz: i64 = grep_has(path, "zzz" as *u8)
22 let cherries: i64 = grep_count(path, "cherry" as *u8)
23 let nofile: i64 = grep_count("/tmp/does-not-exist-xyz" as *u8, "x" as *u8)
24
25 gt_puts(" grep -c 'apple' = " as *u8); gt_num(apples); gt_puts(" grep -q 'banana' = " as *u8); gt_num(has_banana); gt_puts(" grep -q 'zzz' = " as *u8); gt_num(has_zzz); gt_puts("\n --- grep 'apple' (printing matches) ---\n" as *u8)
26 grep_file(path, "apple" as *u8, 1)
27
28 let r: *i64 = sys_mmap(8*8) as *i64
29 r[0] = 0; if apples == 2 { r[0] = 1 } // two 'apple' lines
30 r[1] = 0; if has_banana == 1 { r[1] = 1 } // matches present
31 r[2] = 0; if has_zzz == 0 { r[2] = 1 } // absent -> no match
32 r[3] = 0; if cherries == 1 { r[3] = 1 } // one 'cherry' line
33 r[4] = 0; if nofile == 0 - 1 { r[4] = 1 } // missing file -> -1 (honest)
34 r[5] = 0; if grep_line_matches("hello apple world" as *u8, 17, "apple" as *u8) == 1 { if grep_line_matches("hello world" as *u8, 11, "apple" as *u8) == 0 { r[5] = 1 } }
35 var pass: i64 = 0; var i: i64 = 0
36 while i < 6 { pass = pass + r[i]; i = i + 1 }
37 gt_puts("----\n passed " as *u8); gt_num(pass); gt_puts("/6\n" as *u8)
38 if pass == 6 { gt_puts(" SOVEREIGN GREP: the team searches files itself in NishiLang -- no shell grep. One of the 'cheats' replaced; the stack gets more sovereign.\n" as *u8); sys_exit(0); return 0 }
39 gt_puts(" FAIL\n" as *u8); sys_exit(1); return 1
40}