omega-bridge
Omega-first language interoperability: checked conversion backends and native language bindings
Brought by drakestapleton
omega-bridge / tests / text.py
| 1 | """Test infrastructure only: text fixtures, native/C/Python oracles, library callers and |
| 2 | valid compiled mutants. Text conversion itself lives in src/toc.om.""" |
| 3 | import concurrent.futures, errno, hashlib, json, os, pathlib, subprocess, sys, time |
| 4 | ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 5 | os.chdir(ROOT) |
| 6 | SEED = os.environ.get('OMEGA_SEED', 'build/bootstrap/omc') |
| 7 | B = ROOT / 'build/text' |
| 8 | B.mkdir(parents=True, exist_ok=True) |
| 9 | CFLAGS = ['-std=gnu11', '-O1', '-Werror=discarded-qualifiers', '-fsanitize=undefined', '-fno-sanitize-recover=all'] |
| 10 | def sha(b): return hashlib.sha256(b).hexdigest() |
| 11 | def run(cmd, data=b''): |
| 12 | # A freshly written executable can be briefly busy (ETXTBSY) while another worker thread's |
| 13 | # fork still holds its write descriptor until that child execs; retry for up to one second. |
| 14 | for attempt in range(50): |
| 15 | try: |
| 16 | r = subprocess.run([str(c) for c in cmd], input=data, capture_output=True, timeout=60) |
| 17 | break |
| 18 | except OSError as e: |
| 19 | if e.errno != errno.ETXTBSY or attempt == 49: raise |
| 20 | time.sleep(0.02) |
| 21 | assert r.returncode >= 0, ('signal', cmd, r.returncode) |
| 22 | return r |
| 23 | def obs(r): return dict(status=r.returncode, stdout_hex=r.stdout.hex(), stderr_hex=r.stderr.hex()) |
| 24 | def ok(r): |
| 25 | assert r.returncode == 0, r.stderr[:300] |
| 26 | return r |
| 27 | def elf(path, data): |
| 28 | assert len(data) >= 120 and data[:5] == b'\x7fELF\x02' and data[18:20] == b'\xb7\x00', 'not an AArch64 ELF' |
| 29 | path.write_bytes(data); path.chmod(0o755) |
| 30 | def execute(target, text, d, probe=None): |
| 31 | """Compile/run one emitted C or Python file; probe replaces the program's own main.""" |
| 32 | f = d / ('out.c' if target == 'c' else 'out.py') |
| 33 | f.write_bytes(text) |
| 34 | if target == 'c': |
| 35 | ok(run(['gcc', *CFLAGS, f, '-o', d / 'out'])) |
| 36 | return run([d / 'out']) |
| 37 | ok(run([sys.executable, '-m', 'py_compile', f])) |
| 38 | return run([sys.executable, '-c', probe, f]) if probe else run([sys.executable, f]) |
| 39 | |
| 40 | ESC = {10: b'\\n', 9: b'\\t', 34: b'\\"', 92: b'\\\\'} |
| 41 | def lit(data): return b'"' + b''.join(ESC.get(v, bytes([v])) for v in data) + b'"' |
| 42 | def prog(data, body=b'w = write 1 t 0 len t\nret 0', prefix=b''): |
| 43 | return prefix + b'text t ' + lit(data) + b'\nfn main to int\n' + body + b'\nend\n' |
| 44 | |
| 45 | cases = [] |
| 46 | def positive(name, src, out=b'', status=0, error=None, native_error=None, errout=b''): |
| 47 | cases.append(dict(name=name, src=src if isinstance(src, bytes) else src.encode(), out=out if isinstance(out, bytes) else out.encode(), |
| 48 | status=status, error=error, native_error=native_error, errout=errout)) |
| 49 | base = json.loads(pathlib.Path('evidence/text-parent-baseline/baseline.json').read_text()) |
| 50 | assert sha(pathlib.Path(SEED).read_bytes()) == base['seed_sha256'] |
| 51 | for r in base['cases']: |
| 52 | cases.append(dict(name='parent-' + r['name'], src=r['source'].encode(), out=bytes.fromhex(r.get('expected_stdout_hex', '')), status=0, |
| 53 | error=r['native_compile_rc'] or None, native_error=r['native_compile_rc'], errout=b'', parent=True)) |
| 54 | positive('all-256-bytes', prog(bytes(range(256))), bytes(range(256))) |
| 55 | for i in range(256): positive(f'byte-{i}', prog(bytes([i])), bytes([i])) |
| 56 | positive('raw-cr-tab', b'text t "A\r\tZ"\nfn main to int\nw = write 1 t 0 len t\nret int len t\nend\n', b'A\r\tZ', 4) |
| 57 | inject = b'"; _os._exit(99) # \\xFA0123\n*/ int main(){return 99;}' |
| 58 | positive('target-injection', prog(inject), inject) |
| 59 | positive('read-only-view', 'text t "A\\nB"\nfn pass a view uchar 3 to long\nret write 1 a 0 len a\nend\nfn main to int\nn = pass t\nret int n\nend\n', 'A\nB', 3) |
| 60 | positive('view-forward', 'text t "A\\tB"\nfn pass a view uchar 3 to uchar\nret get a 1\nend\nfn more a view uchar 3 to uchar\nret pass a\nend\nfn main to int\nret int more t\nend\n', '', 9) |
| 61 | positive('empty-view', 'text t ""\nfn size a view uchar 0 to ulong\nret len a\nend\nfn main to int\nret int size t\nend\n', error=8, native_error=8) |
| 62 | positive('view-length-mismatch', 'text t "AB"\nfn pass a view uchar 3 to uchar\nret get a 0\nend\nfn main to int\nret int pass t\nend\n', error=7, native_error=7) |
| 63 | positive('prefix-names', 'text abc "A"\ntext abcdefgh "B"\ntext ab "C"\nfn main to int\nw = write 1 abc 0 len abc\nw = write 1 abcdefgh 0 len abcdefgh\nw = write 1 ab 0 len ab\nret 0\nend\n', 'ABC') |
| 64 | positive('texts-after-function', 'text t "A"\nfn main to int\nw = write 1 t 0 len t\nret 0\nend\ntext last "B"\n', 'A') |
| 65 | positive('texts-and-globals', 'text t "A"\nglobal g uchar 1\ntext u "B"\nfn main to int\nput g 0 get u 0\nw = write 1 t 0 1\nw = write 1 g 0 1\nret 0\nend\n', 'AB') |
| 66 | for n in (8, 9): |
| 67 | positive(f'combined-table-{n}', ''.join(f'global g{i} uchar 1\n' if i % 2 else f'text t{i} "{i}"\n' for i in range(n)) + 'fn main to int\nret 0\nend\n', error=14 if n == 9 else None) |
| 68 | for n in (32768, 32769): positive(f'pool-{n}', prog(b'A' * n, b'ret int len t'), status=n % 256, error=14 if n == 32769 else None) |
| 69 | positive('shared-pool-limit', b'text a ' + lit(b'A' * 16384) + b'\ntext t ' + lit(b'B' * 16385) + b'\nfn main to int\nret 0\nend\n', error=14) |
| 70 | positive('dynamic-last', prog(bytes([0, 255]), b'i = ulong 1\nret int get t i'), status=255) |
| 71 | positive('dynamic-bounds', prog(b'AB', b'i = ulong 2\nret int get t i'), status=103) |
| 72 | positive('empty-bounds', prog(b'', b'i = ulong 0\nret int get t i'), status=103) |
| 73 | positive('write-slice', prog(bytes([1, 0, 255, 2]), b'w = write 1 t 1 2\nret int w'), bytes([0, 255]), 2) |
| 74 | positive('empty-write-at-end', prog(b'ABC', b'w = write 1 t len t 0\nret int w')) |
| 75 | positive('write-bounds', prog(b'AB', b'w = write 1 t 1 2\nret 0'), status=103) |
| 76 | positive('write-overflow', prog(b'AB', b'w = write 1 t ulong 18446744073709551615 2\nret 0'), status=103) |
| 77 | positive('stderr-bytes', prog(b'ABC', b'w = write 2 t 0 len t\nret 0'), errout=b'ABC') |
| 78 | positive('bad-fd', prog(b'ABC', b'w = write int -1 t 0 len t\nret int neg w'), status=9) |
| 79 | positive('text_target', 'text t "abc"\nfn main to int\nret 0\nend\n') |
| 80 | positive('NATIVE-developer-fixture', 'text msg "NATIVE\\n"\nfn main to int\nw = write 1 msg 0 len msg\nret 23\nend\n', 'NATIVE\n', 23) |
| 81 | positive('note-quote', prog(b'A', prefix=b'note unmatched " and \\q\n'), 'A') |
| 82 | positive('note-raw-zero', prog(b'A', b'ret 0', bytes([110, 111, 116, 101, 32, 0, 255, 10]))) |
| 83 | for name, prefix, code in [ |
| 84 | ('escape-zero', b'text t "\\0"\n', 22), ('escape-hex', b'text t "\\x41"\n', 22), ('escape-cr', b'text t "\\r"\n', 22), |
| 85 | ('quote-adjacent', b'text t "ab"x\n', 22), ('quote-backslash-eof', b'text t "ab\\', 22), ('quote-eof', b'text t "ab', 22), |
| 86 | ('duplicate', b'text t "a"\ntext t "b"\n', 10), ('global-collision', b'global t uchar 1\ntext t "b"\n', 10), |
| 87 | ('long-name', b'text abcdefghi "a"\n', 13), ('missing-literal', b'text t abc\n', 16), ('raw-lf', b'text t "a\nb"\n', 22), |
| 88 | ('outside-zero', b'\0', 16), ('outside-control', b'\1', 16), ('after-quote-control', b'text t "a"\1\n', 16)]: |
| 89 | positive(name, prefix + b'fn main to int\nret 0\nend\n', error=code, native_error=code) |
| 90 | for name, body, code in [('readonly-put', 'put t 0 1', 20), ('readonly-read', 'n = read 0 t 0 1', 20), ('readonly-edit', 'touch t', 20), |
| 91 | ('constant-bounds', 'x = get t 2', 21), ('inline-get', 'x = get "ab" 0', 16), ('inline-write', 'x = write 1 "ab" 0 2', 16)]: |
| 92 | positive(name, 'text t "ab"\nfn touch a edit uchar 2 to void\nend\nfn main to int\n' + body + '\nret 0\nend\n', error=code, native_error=code) |
| 93 | trunc = prog(bytes([65, 0, 34, 92, 10, 255])) |
| 94 | for i in range(len(trunc) + 1): cases.append(dict(name=f'prefix-{i}', src=trunc[:i], probe=True)) |
| 95 | |
| 96 | def check(c): |
| 97 | d = B / c['name']; d.mkdir(exist_ok=True) |
| 98 | native = run([SEED], c['src']) |
| 99 | if c.get('native_error') is not None: assert native.returncode == c['native_error'], ('native refusal code', native.returncode) |
| 100 | elif not c.get('probe'): assert native.returncode == 0, native.stderr |
| 101 | expected = None |
| 102 | if native.returncode == 0: |
| 103 | elf(d / 'native', native.stdout); expected = obs(run([d / 'native'])) |
| 104 | (d / 'input.om').write_bytes(c['src']) |
| 105 | rows = [] |
| 106 | for target in ('c', 'python'): |
| 107 | row = dict(case=c['name'], target=target, source_sha256=sha(c['src']), native_compile=native.returncode) |
| 108 | try: |
| 109 | p = run(['tools/bridge', target, d / 'input.om']) |
| 110 | refusal = native.returncode or c.get('error') |
| 111 | row['convert_status'] = p.returncode |
| 112 | if refusal: |
| 113 | assert p.returncode == refusal and not p.stdout and f'error {refusal}'.encode() in p.stderr, (refusal, p.returncode, p.stderr[:200]) |
| 114 | else: |
| 115 | assert p.returncode == 0 and p.stdout, p.stderr[:300] |
| 116 | row['output_sha256'] = sha(p.stdout) |
| 117 | got = obs(execute(target, p.stdout, d)) |
| 118 | row['native'], row['actual'] = expected, got |
| 119 | assert got == expected, ('target differs from native', got['status'], expected['status']) |
| 120 | if not c.get('probe'): |
| 121 | assert (expected['status'], expected['stdout_hex'], expected['stderr_hex']) == (c['status'], c['out'].hex(), c['errout'].hex()), ('native differs from independent expectation', expected) |
| 122 | row['ok'] = True |
| 123 | except Exception as e: |
| 124 | row['ok'] = False; row['error'] = repr(e)[:300] |
| 125 | print('FAIL', c['name'], target, row['error']) |
| 126 | rows.append(row) |
| 127 | return rows |
| 128 | |
| 129 | with concurrent.futures.ThreadPoolExecutor(max_workers=int(os.environ.get('TEXT_JOBS', '2'))) as pool: |
| 130 | rows = [r for rs in pool.map(check, cases) for r in rs] |
| 131 | |
| 132 | # Controls: valid compiled emitter mutants and real library callers. |
| 133 | controls = [] |
| 134 | def control(name, target, caught, **kw): |
| 135 | controls.append(dict(name=name, target=target, caught=bool(caught), **kw)) |
| 136 | if not caught: print('FAIL control', name, target, kw) |
| 137 | CTRL = B / 'controls'; CTRL.mkdir(exist_ok=True) |
| 138 | SRC = b'text t "A\\n\\"\\\\\\tB"\nfn main to int\nw = write 1 t 0 len t\nret int w\nend\n' |
| 139 | native = ok(run([SEED], SRC)); elf(CTRL / 'native', native.stdout) |
| 140 | EXPECT = obs(run([CTRL / 'native'])) |
| 141 | assert EXPECT == dict(status=6, stdout_hex='410a225c0942', stderr_hex=''), EXPECT |
| 142 | ORIGINAL = pathlib.Path('src/toc.om').read_text() |
| 143 | def mutant_emitter(name, old, new): |
| 144 | assert ORIGINAL.count(old) == 1, ('mutation anchor', name) |
| 145 | src = ORIGINAL.replace(old, new) |
| 146 | compiled = ok(run([SEED], src.encode())) |
| 147 | e = CTRL / f'{name}.emitter'; elf(e, compiled.stdout) |
| 148 | return e, sha(src.encode()), sha(compiled.stdout) |
| 149 | for name, old, new in [('decoded-byte', 'put textbuf u b', 'put textbuf u xor b uchar 1'), |
| 150 | ('decoded-length', 'put g_len i sub get textuse 0 get g_pos i', 'put g_len i sub sub get textuse 0 get g_pos i 1'), |
| 151 | ('escape-decoding', 'b = uchar 10', 'b = uchar 13')]: |
| 152 | e, ssha, esha = mutant_emitter(name, old, new) |
| 153 | for target in ('c', 'python'): |
| 154 | d = CTRL / f'{name}-{target}'; d.mkdir(exist_ok=True) |
| 155 | emitted = ok(run([e], (b'C' if target == 'c' else b'P') + SRC)).stdout |
| 156 | got = obs(execute(target, emitted, d)) |
| 157 | control(name, target, got != EXPECT and got['stderr_hex'] == '', mutant_source_sha256=ssha, mutant_emitter_sha256=esha, actual=got, expected=EXPECT) |
| 158 | |
| 159 | # Emitted storage is immutable: C const object, Python bytes; mutating the output is detected. |
| 160 | PYPROBE = "import runpy,sys\nm=runpy.run_path(sys.argv[1])\np=m['g0']\nif type(p) is not bytes: sys.exit(77)\ntry: p[0]=1\nexcept TypeError: sys.exit(0)\nsys.exit(78)\n" |
| 161 | # The C length is a const internal object too, so a linked caller cannot widen o_get's bound. |
| 162 | for target in ('c', 'python'): |
| 163 | (CTRL / 'ro.om').write_bytes(SRC) |
| 164 | text = ok(run(['tools/bridge', target, CTRL / 'ro.om'])).stdout |
| 165 | if target == 'c': |
| 166 | text = b'#define OMEGA_LIBRARY\n' + text + b'\nint main(void){return _Generic(&g0[0],const uint8_t*:0,default:77)+_Generic(&g0_n,const uint64_t*:0,default:1);}\n' |
| 167 | mutants = [('immutable-storage-mutant', b'static const uint8_t g0', b'static uint8_t g0', 77), |
| 168 | ('immutable-length-mutant', b'static const uint64_t g0_n', b'uint64_t g0_n', 1)] |
| 169 | else: |
| 170 | mutants = [('immutable-storage-mutant', b'g0=bytes((', b'g0=bytearray((', 77)] |
| 171 | variants = [('immutable-storage', text, 0)] |
| 172 | for label, old, new, want in mutants: |
| 173 | assert text.count(old) == 1, (label, target) |
| 174 | variants.append((label, text.replace(old, new), want)) |
| 175 | for label, body, want in variants: |
| 176 | d = CTRL / f'{label}-{target}'; d.mkdir(exist_ok=True) |
| 177 | got = execute(target, body, d, PYPROBE if target == 'python' else None) |
| 178 | control(label, target, got.returncode == want and not got.stderr, status=got.returncode) |
| 179 | |
| 180 | # The converter's own refusals, without the seed in front (tools/bridge runs the seed first). |
| 181 | # Each source differs from the accepted 'clean' program only in the text line or the body. |
| 182 | MAIN = b'fn main to int\nret 0\nend\n' |
| 183 | direct = [] |
| 184 | for name, src, want in [('clean', b'text t "ab"\n' + MAIN, 0), ('raw-lf', b'text t "a\nb"\n' + MAIN, 22), |
| 185 | ('unterminated', b'text t "ab', 22), ('unknown-escape', b'text t "a\\qb"\n' + MAIN, 22), |
| 186 | ('junk-after-quote', b'text t "ab"x\n' + MAIN, 22), ('trailing-token', b'text t "ab" junk\n' + MAIN, 16), |
| 187 | ('no-quote', b'text t ab\n' + MAIN, 16), |
| 188 | ('put-text', b'text t "ab"\nfn main to int\nput t 0 1\nret 0\nend\n', 20), |
| 189 | ('read-text', b'text t "ab"\nfn main to int\nn = read 0 t 0 1\nret 0\nend\n', 20), |
| 190 | ('edit-text', b'text t "ab"\nfn f a edit uchar 2 to void\nput a 0 1\nend\nfn main to int\nf t\nret 0\nend\n', 20), |
| 191 | # L555 whole-core review: names, trailing tokens and literal indices the seed refuses. |
| 192 | ('global-then-text', b'global a uchar 4\ntext a "x"\n' + MAIN, 10), ('text-then-global', b'text a "x"\nglobal a uchar 4\n' + MAIN, 10), |
| 193 | ('text-then-text', b'text a "x"\ntext a "y"\n' + MAIN, 10), ('global-then-global', b'global a uchar 4\nglobal a uchar 4\n' + MAIN, 10), |
| 194 | ('text-then-fn', b'text f "x"\nfn f to int\nret 0\nend\n' + MAIN, 10), ('fn-then-global', b'fn f to int\nret 0\nend\nglobal f uchar 4\n' + MAIN, 10), |
| 195 | ('long-text-name', b'text abcdefghi "x"\n' + MAIN, 13), ('long-global-name', b'global abcdefghi uchar 1\n' + MAIN, 13), |
| 196 | ('global-trailing-token', b'global g uchar 4 junk\n' + MAIN, 16), |
| 197 | ('empty-text-literal-index', b'text e ""\nfn main to int\nret int get e 0\nend\n', 21), |
| 198 | ('text-literal-index', b'text t "ab"\nfn main to int\nret int get t 2\nend\n', 21), |
| 199 | ('global-literal-put', b'global g uchar 4\nfn main to int\nput g 4 1\nret 0\nend\n', 21), |
| 200 | ('global-then-fn', b'global f uchar 4\nfn f to int\nret 0\nend\n' + MAIN, 10), |
| 201 | ('local-literal-put', b'fn main to int\na = new uchar 4 0\nput a 4 1\nret 0\nend\n', 21), |
| 202 | ('keyword-global', b'global own uchar 4\n' + MAIN, 16), ('keyword-text', b'text u8 "a"\n' + MAIN, 16), |
| 203 | ('keyword-fn', b'fn get to int\nret 0\nend\n' + MAIN, 16), |
| 204 | ('near-keyword-names', b'global ifx uchar 4\ntext owns "b"\nfn gets to int\nret 0\nend\n' + MAIN, 0), |
| 205 | ('keyword-param', b'fn f own ulong to ulong\nret own\nend\n' + MAIN, 16), |
| 206 | ('long-param', b'fn f abcdefghi ulong to ulong\nret abcdefghi\nend\n' + MAIN, 13), |
| 207 | ('param-then-param', b'fn f a ulong a ulong to ulong\nret a\nend\n' + MAIN, 10), |
| 208 | ('global-then-param', b'global g uchar 4\nfn f g ulong to ulong\nret g\nend\n' + MAIN, 10), |
| 209 | ('text-then-param', b'text t "a"\nfn f t ulong to ulong\nret t\nend\n' + MAIN, 10), |
| 210 | ('param-then-later-fn', b'fn f h ulong to ulong\nret h\nend\nfn h to int\nret 0\nend\n' + MAIN, 10), |
| 211 | ('param-then-later-global', b'fn f g ulong to ulong\nret g\nend\nglobal g uchar 4\n' + MAIN, 0), |
| 212 | ('keyword-local', b'fn main to int\nown = ulong 1\nret 0\nend\n', 16)]: |
| 213 | for mode in (b'C', b'P'): |
| 214 | r = run(['build/bridge'], mode + src) |
| 215 | direct.append(dict(name=name, mode=mode.decode(), want=want, status=r.returncode, ok=r.returncode == want and bool(r.stdout) == (want == 0))) |
| 216 | if not direct[-1]['ok']: print('FAIL direct', direct[-1]) |
| 217 | # Seeded modes refuse a text line (24) before reading its bytes, raw NUL included. |
| 218 | for mode in (b'D', b'Q'): |
| 219 | r = run(['build/bridge'], mode + b'text t "a\0b"\n' + MAIN) |
| 220 | direct.append(dict(name='seeded-text-nul', mode=mode.decode(), want=24, status=r.returncode, ok=r.returncode == 24 and not r.stdout)) |
| 221 | if not direct[-1]['ok']: print('FAIL direct', direct[-1]) |
| 222 | # Seeded modes also refuse the seeded frontend's further keywords (16); the baseline seed accepts them. |
| 223 | # The draft-1049 profile (E) adds its own words; the e5 profile (D) accepts those. |
| 224 | for name, src, mode, want in (('seeded-keyword-param', b'fn f const ulong to ulong\nret const\nend\n', b'C', 0), |
| 225 | ('seeded-keyword-param', b'fn f const ulong to ulong\nret const\nend\n', b'D', 16), |
| 226 | ('seeded-keyword-param', b'fn f const ulong to ulong\nret const\nend\n', b'Q', 16), |
| 227 | ('draft-keyword-param', b'fn f qty ulong to ulong\nret qty\nend\n', b'D', 0), |
| 228 | ('draft-keyword-param', b'fn f qty ulong to ulong\nret qty\nend\n', b'E', 16)): |
| 229 | r = run(['build/bridge'], mode + src + MAIN) |
| 230 | direct.append(dict(name=name, mode=mode.decode(), want=want, status=r.returncode, ok=r.returncode == want and bool(r.stdout) == (want == 0))) |
| 231 | if not direct[-1]['ok']: print('FAIL direct', direct[-1]) |
| 232 | # Cabi library modes (no body pass) still refuse a parameter named like a function declared below (10), |
| 233 | # reported at the parameter's function line as the seed does. |
| 234 | FIX = (ROOT / 'tests/cabi/fixture.om').read_bytes() |
| 235 | BADFIX = FIX.replace(b'fn fx_put64 b edit uchar 512 o ulong', b'fn fx_put64 b edit uchar 512 fx_gpu ulong') |
| 236 | assert BADFIX != FIX |
| 237 | BADLINE = b'line %d: error 10\n' % (FIX[:FIX.index(b'fn fx_put64 ')].count(b'\n') + 1) |
| 238 | TOC = (ROOT / 'src/toc.om').read_bytes() |
| 239 | for label, src, want in (('cabi-fixture', FIX, 0), ('cabi-param-then-later-fn', BADFIX, 10)): |
| 240 | for mode in (b'L', b'M', b'V'): |
| 241 | r = run(['sh', '-c', 'exec build/bridge 3< src/toc.om'], mode + src + f'\n{sha(TOC)} {sha(src)}\n'.encode()) |
| 242 | good = r.returncode == want and bool(r.stdout) == (want == 0) and (want == 0 or r.stderr.endswith(BADLINE)) |
| 243 | direct.append(dict(name=label, mode=mode.decode(), want=want, status=r.returncode, ok=good)) |
| 244 | if not direct[-1]['ok']: print('FAIL direct', direct[-1], r.stderr) |
| 245 | |
| 246 | # Readonly library views: C const callers compile cleanly; Python takes immutable bytes for |
| 247 | # readonly uchar views only. Edit views stay mutable-only; lengths and element types stay checked. |
| 248 | LIB = b'fn pick a view uchar 4 to uchar\nret get a 2\nend\nfn poke a edit uchar 2 to void\nput a 0 7\nend\nfn wsum a view ulong 2 to ulong\nret add get a 0 get a 1\nend\n' |
| 249 | CCALL = b'#include "library.c"\nint main(void){static const uint8_t a[]={1,0,255,4};uint8_t m[]={1,2};uint64_t out=99;\nif(omega_pick(&out,a,4)||out!=255)return 1;if(omega_pick(&out,a,3)!=8)return 2;\nif(omega_poke(&out,m,2)||m[0]!=7||m[1]!=2)return 3;return omega_pick(&out,a,4);}\n' |
| 250 | PYCALL = b'''from library import omega_pick, omega_poke, omega_wsum |
| 251 | ro = b"\\x01\\x00\\xff\\x04" |
| 252 | assert omega_pick(ro, 4) == (0, 255) |
| 253 | assert omega_pick(bytearray(ro), 4) == (0, 255) |
| 254 | assert omega_pick(ro, 3) == (8, None) and omega_pick(ro[:3], 3) == (8, None) |
| 255 | assert omega_pick(ro, 4) == (0, 255) and ro == b"\\x01\\x00\\xff\\x04" |
| 256 | assert omega_pick(list(ro), 4) == (8, None) and omega_pick(memoryview(ro), 4) == (8, None) |
| 257 | m = bytearray(b"\\x01\\x02") |
| 258 | assert omega_poke(m, 2) == (0, 0) and m == bytearray(b"\\x07\\x02") |
| 259 | frozen = b"\\x01\\x02" |
| 260 | assert omega_poke(frozen, 2) == (8, None) and frozen == b"\\x01\\x02" |
| 261 | assert omega_wsum([1, 2], 2) == (0, 3) and omega_wsum(b"\\x01\\x02", 2) == (8, None) |
| 262 | ''' |
| 263 | def library(emitter, label): |
| 264 | out = {} |
| 265 | (CTRL / 'library.om').write_bytes(LIB) |
| 266 | for target in ('c', 'python'): |
| 267 | d = CTRL / f'{label}-{target}'; d.mkdir(exist_ok=True) |
| 268 | if emitter is None: emitted = ok(run(['tools/bridge', target, CTRL / 'library.om'])).stdout |
| 269 | else: emitted = ok(run([emitter], (b'C' if target == 'c' else b'P') + LIB)).stdout |
| 270 | (d / ('library.c' if target == 'c' else 'library.py')).write_bytes(emitted) |
| 271 | if target == 'c': |
| 272 | (d / 'caller.c').write_bytes(CCALL) |
| 273 | cc = run(['gcc', *CFLAGS, d / 'caller.c', '-o', d / 'caller']) |
| 274 | r = run([d / 'caller']) if cc.returncode == 0 else cc |
| 275 | else: |
| 276 | (d / 'caller.py').write_bytes(PYCALL) |
| 277 | r = subprocess.run([sys.executable, 'caller.py'], cwd=d, capture_output=True, timeout=60) |
| 278 | out[target] = (r.returncode, r.stderr[:300].decode(errors='replace')) |
| 279 | return out |
| 280 | good = library(None, 'library') |
| 281 | for target in ('c', 'python'): control('readonly-library-caller', target, good[target][0] == 0, result=good[target]) |
| 282 | for name, old, new, target in [ |
| 283 | ('python-view-refuses-bytes', '(edit==2 and type(p) is bytes)', '(False and type(p) is bytes)', 'python'), |
| 284 | ('python-edit-accepts-bytes', '(edit==2 and type(p) is bytes)', '(type(p) is bytes)', 'python'), |
| 285 | ('c-view-drops-const', 'fn viewqual k ulong to void\nif eq k 2', 'fn viewqual k ulong to void\nif eq k 99', 'c')]: |
| 286 | e, ssha, esha = mutant_emitter(name, old, new) |
| 287 | got = library(e, name) |
| 288 | control(name, target, got[target][0] != 0, mutant_source_sha256=ssha, mutant_emitter_sha256=esha, result=got[target]) |
| 289 | |
| 290 | failed = sum(not r['ok'] for r in rows) + sum(not c['caught'] for c in controls) + sum(not x['ok'] for x in direct) |
| 291 | report = dict(seed_sha256=sha(pathlib.Path(SEED).read_bytes()), toc_sha256=sha(pathlib.Path('src/toc.om').read_bytes()), |
| 292 | source_cases=len(cases), target_checks=len(rows), target_passed=sum(r['ok'] for r in rows), |
| 293 | direct_refusals=len(direct), direct_passed=sum(x['ok'] for x in direct), |
| 294 | controls=len(controls), controls_caught=sum(c['caught'] for c in controls), failed=failed, |
| 295 | rows=rows, direct_rows=direct, control_rows=controls) |
| 296 | pathlib.Path('build/text-receipts.json').write_text(json.dumps(report, indent=2) + '\n') |
| 297 | print(f"text cases={len(cases)} target_checks={len(rows)} passed={report['target_passed']} direct={len(direct)} direct_passed={report['direct_passed']} controls={len(controls)} caught={report['controls_caught']} RC={int(bool(failed))}") |
| 298 | sys.exit(bool(failed)) |