omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / tests / universal / translation / c_export_selftest.py
| 1 | #!/usr/bin/env python3 |
| 2 | """C export lane self-test (translation-v1 section 6, translation-compose-v1, #622). Author TESTED, not QUALIFIED. |
| 3 | |
| 4 | For every F1 positive and the four accepted boundary controls of c_import_controls.py: |
| 5 | import (native importer) -> export (native exporter) -> re-import; the re-imported OMSA semantic bytes |
| 6 | must equal the first import's. The semantic-only envelope and its retargets R(U,Rust) and R(U,Python) |
| 7 | (compose section 2) must export byte-identically. Original and exported C are compiled with |
| 8 | cc -std=c17 -O2 -Wall -Werror and compared on boundary and seeded random vectors (DIFFERENTIAL), and |
| 9 | against the Python integer model of the imported graph (REFERENCE). Constructed units cover the |
| 10 | non-NORMALIZED, shared-SSA and permuted-slot paths and every refusal. |
| 11 | |
| 12 | Optional compose leg (--rust-root / --python-root: checkouts holding the #626 / #627 adapters, built): |
| 13 | Rust -> C and Python -> C on fixtures-f2-<lang>.json per compose section 4: identity |
| 14 | N(strip(U_B)) = N(strip(U_A)), rustc/python3 original vs cc generated C vs REFERENCE, semantic-only |
| 15 | export identical. Not given = NOT_RUN.""" |
| 16 | from pathlib import Path |
| 17 | import argparse,hashlib,importlib.util,itertools,json,os,random,shutil,struct,subprocess,sys,tempfile |
| 18 | ROOT=Path(__file__).resolve().parents[3];sys.dont_write_bytecode=True |
| 19 | spec=importlib.util.spec_from_file_location('cgate',ROOT/'tests/universal/c_import_gate.py');g=importlib.util.module_from_spec(spec);spec.loader.exec_module(g) |
| 20 | MASK=g.MASK |
| 21 | IMPORTER=ROOT/'build/L589/c-import';EXPORTER=ROOT/'build/L622/c-export';CLI=ROOT/'tools/adapters/c-export';SA=ROOT/'tools/source-aware/sa' |
| 22 | BOUNDARY=[0,1,2,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK] |
| 23 | CFLAGS=['-std=c17','-O2','-Wall','-Werror'] |
| 24 | SEMHASH=hashlib.sha256((ROOT/'spec/universal/semantics.md').read_bytes()).digest() |
| 25 | |
| 26 | def controls(): |
| 27 | # Exactly the four accepted boundary controls of tests/universal/c_import_controls.py. |
| 28 | header=g.HEADER;base=(header+'uint64_t calc(uint64_t a,uint64_t b){return a+b;}').encode() |
| 29 | pad=base+b' '*(4096-len(base));comment=base+b'//'+b'x'*(4096-len(base)-2) |
| 30 | maximum=(header+'uint64_t calc(uint64_t a,uint64_t b){return '+'+'.join(['a']*61)+';}').encode() |
| 31 | deep=(header+'uint64_t calc(uint64_t a,uint64_t b){return '+'('*16+'a'+')'*16+';}').encode() |
| 32 | return [('exact-source-capacity',pad,'calc',2),('comment-at-capacity',comment,'calc',2),('operation-capacity',maximum,'calc',2),('nesting-limit',deep,'calc',2)] |
| 33 | |
| 34 | def run(cmd,data): |
| 35 | return subprocess.run(cmd,input=data,capture_output=True,timeout=30) |
| 36 | |
| 37 | def export(unit,name=None): |
| 38 | return run([sys.executable,str(CLI)]+([name] if name else []),unit) |
| 39 | |
| 40 | def semantic(env): |
| 41 | assert env[:5]==b'OMSB\x01';ns,np=struct.unpack_from('<II',env,5);assert len(env)==13+ns+np |
| 42 | return env[13:13+ns] |
| 43 | |
| 44 | def semonly(sem): |
| 45 | return b'OMSB\x01'+struct.pack('<II',len(sem),0)+sem |
| 46 | |
| 47 | def unit(records,ninputs=None,lang=1,profile=1): |
| 48 | """Semantic-only S1-shaped envelope from (op,a,b,imm) records; obligations/attributes per registry.""" |
| 49 | body=b'' |
| 50 | for op,a,b,imm in records: |
| 51 | attr=0 if op==9 else 1;obl=0 if op==1 else (3 if op==5 else 1) |
| 52 | body+=struct.pack('<8BHHQ',lang,1,op,1,attr,0,0,obl,a,b,imm) |
| 53 | sem=b'OMSA\x01'+bytes([lang,profile,1,0,1])+struct.pack('<H',len(records))+SEMHASH+body |
| 54 | return semonly(sem) |
| 55 | |
| 56 | def ops_of(sem): |
| 57 | count=struct.unpack_from('<H',sem,10)[0] |
| 58 | return [(op,a,b,imm) for (d,v,op,t,attr,e,al,ob,a,b,imm) in (struct.unpack_from('<8BHHQ',sem,44+20*i) for i in range(count))] |
| 59 | |
| 60 | # translation-compose-v1 section 1: member -> (language, profile, op dialect, arithmetic obligations). |
| 61 | FAMILY={'C':(1,1,1,1),'Rust':(2,2,2,1),'Python':(3,4,3,5)} |
| 62 | |
| 63 | def retarget(sem,member): |
| 64 | """R(U, M), compose section 2: header language/profile, every op's dialect byte, arithmetic obligations.""" |
| 65 | lang,prof,dial,obl=FAMILY[member];b=bytearray(sem);b[5]=lang;b[6]=prof |
| 66 | for i in range(struct.unpack_from('<H',sem,10)[0]): |
| 67 | o=44+20*i;b[o]=dial |
| 68 | if b[o+2] in (2,3,4):b[o+7]=obl |
| 69 | return bytes(b) |
| 70 | |
| 71 | def strip(sem): |
| 72 | """Remove one trailing NORMALIZED pair (translation-v1 section 4); C, Rust and Python importers declare one.""" |
| 73 | ops=ops_of(sem);n=len(ops) |
| 74 | assert n>=3 and ops[-2]==(1,65535,65535,0) and ops[-1][0]==2 and ops[-1][2]==n-2 and ops[-1][1]<n-2,'unit not NORMALIZED' |
| 75 | return sem[:10]+struct.pack('<H',n-2)+sem[12:44+20*(n-2)] |
| 76 | |
| 77 | def raw_unit(header,records): |
| 78 | """header=(language,profile,runtime,abi); records=(dialect,op,type,attr,effects,alias,obligations,a,b,imm).""" |
| 79 | lang,prof,rt,abi=header |
| 80 | body=b''.join(struct.pack('<8BHHQ',d,1,op,t,at,ef,al,ob,a,b,imm) for d,op,t,at,ef,al,ob,a,b,imm in records) |
| 81 | return semonly(b'OMSA\x01'+bytes([lang,prof,1,rt,abi])+struct.pack('<H',len(records))+SEMHASH+body) |
| 82 | |
| 83 | def vectors(nargs,rng): |
| 84 | if nargs==0:return [()] |
| 85 | if nargs<=2:vs=list(itertools.product(BOUNDARY,repeat=nargs)) |
| 86 | else:vs=[tuple(BOUNDARY[(j+k)%len(BOUNDARY)] for k in range(nargs)) for j in range(len(BOUNDARY))]+[tuple(x if k==s else 1 for k in range(nargs)) for s in range(nargs) for x in BOUNDARY] |
| 87 | return vs+[tuple(rng.getrandbits(64) for _ in range(nargs)) for _ in range(64)] |
| 88 | |
| 89 | def harness(name,nargs): |
| 90 | if not nargs:return '\n#include <stdio.h>\n#include <inttypes.h>\nint main(void){printf("%" PRIu64 "\\n",'+name+'());return 0;}\n' |
| 91 | scan=' '.join(['%" SCNu64 "']*nargs);ptrs=','.join('&x['+str(j)+']' for j in range(nargs));args=','.join('x['+str(j)+']' for j in range(nargs)) |
| 92 | return '\n#include <stdio.h>\n#include <inttypes.h>\nint main(void){uint64_t x[6]={0};while(scanf("'+scan+'",'+ptrs+')=='+str(nargs)+')printf("%" PRIu64 "\\n",'+name+'('+args+'));return 0;}\n' |
| 93 | |
| 94 | def native(out,tag,src,name,nargs,payload): |
| 95 | c=out/(tag+'.c');exe=out/tag;c.write_bytes(src+harness(name,nargs).encode()) |
| 96 | r=subprocess.run([os.environ.get('CC','cc')]+CFLAGS+[str(c),'-o',str(exe)],capture_output=True,timeout=60) |
| 97 | assert r.returncode==0,tag+' compile failed: '+r.stderr.decode(errors='replace') |
| 98 | r=run([str(exe)],payload);assert r.returncode==0,tag+' run failed' |
| 99 | return [int(x) for x in r.stdout.split()] |
| 100 | |
| 101 | def main(): |
| 102 | ap=argparse.ArgumentParser();ap.add_argument('--out',required=True) |
| 103 | ap.add_argument('--rust-root',default='',help='checkout with built #626 adapters (tools/adapters/rust-import, fixtures-f2-rust.json)') |
| 104 | ap.add_argument('--python-root',default='',help='checkout with built #627 adapters (tools/adapters/python-import, fixtures-f2-python.json)') |
| 105 | a=ap.parse_args() |
| 106 | out=Path(a.out).resolve();out.mkdir(parents=True,exist_ok=False) |
| 107 | for p in [IMPORTER,EXPORTER]:assert p.read_bytes()[:4]==b'\x7fELF',p |
| 108 | rng=random.Random(622624);rows=[];failures=[];observations=0 |
| 109 | fixtures=json.loads((ROOT/'tests/universal/translation/fixtures-f1.json').read_text()) |
| 110 | cases=[] |
| 111 | for f in fixtures['positives']: |
| 112 | src=f['source'].encode();assert hashlib.sha256(src).hexdigest()==f['sha256'],f['id'] |
| 113 | cases.append((f['id'],src,f['name'],f['inputs'])) |
| 114 | for name,src,fn,nargs in controls():cases.append(('control-'+name,src,fn,nargs)) |
| 115 | # 1. Required boundaries: import -> export -> re-import identity; semantic-only; native differential. |
| 116 | for cid,src,name,nargs in cases: |
| 117 | item={'id':cid,'source_sha256':hashlib.sha256(src).hexdigest()} |
| 118 | try: |
| 119 | r=run([str(IMPORTER)],src);assert r.returncode==0,'import refused rc=%d'%r.returncode |
| 120 | u1=r.stdout;s1=semantic(u1);ops=g.decode(u1,src,nargs) |
| 121 | assert len(ops)>=3 and ops[-2]==(1,65535,65535,0) and ops[-1][0]==2 and ops[-1][2]==len(ops)-2 and ops[-1][1]<len(ops)-2,'importer unit not NORMALIZED' |
| 122 | fname=None if name=='calc' else name |
| 123 | e=export(u1,fname);assert e.returncode==0 and e.stderr==b'','export refused rc=%d %s'%(e.returncode,e.stderr) |
| 124 | c=e.stdout |
| 125 | assert c.startswith(b'#include <stdint.h>\nuint64_t '+name.encode()+b'(') and c.endswith(b'; }\n') and c.count(b'\n')==2,'output form' |
| 126 | assert len(c)<=4096,'over 4096 bytes' |
| 127 | d=run([str(EXPORTER)],bytes([len(fname or '')])+(fname or '').encode()+u1);assert d.returncode==0 and d.stdout==c,'native direct differs from public command' |
| 128 | so=semonly(s1);v=run([str(SA),'decode'],so);assert v.returncode==0 and v.stdout==so,'semantic-only envelope not accepted by sa decode' |
| 129 | e2=export(so,fname);assert e2.returncode==0 and e2.stdout==c,'semantic-only envelope exported differently' |
| 130 | for m in ('Rust','Python'): |
| 131 | rm=semonly(retarget(s1,m));v=run([str(SA),'decode'],rm);assert v.returncode==0 and v.stdout==rm,'R(U,%s) not a valid v1 unit'%m |
| 132 | em=export(rm,fname);assert em.returncode==0 and em.stdout==c,'R(U,%s) exported differently'%m |
| 133 | assert retarget(retarget(s1,'Python'),'C')==s1 and retarget(retarget(s1,'Rust'),'C')==s1,'N(R(U,M)) != N(U)' |
| 134 | r2=run([str(IMPORTER)],c);assert r2.returncode==0,'re-import refused rc=%d %s'%(r2.returncode,r2.stderr) |
| 135 | s2=semantic(r2.stdout);assert s2==s1,'re-imported semantic bytes differ' |
| 136 | i1=run([str(SA),'identity'],u1).stdout;i2=run([str(SA),'identity'],r2.stdout).stdout;i3=run([str(SA),'identity'],so).stdout |
| 137 | assert len(i1)==32 and i1==i2==i3,'semantic identity differs' |
| 138 | vs=vectors(nargs,rng);payload=''.join(' '.join(map(str,x))+'\n' for x in vs).encode() |
| 139 | orig=native(out,cid+'-orig',src,name,nargs,payload);expo=native(out,cid+'-export',c,name,nargs,payload) |
| 140 | ref=[g.evaluate(ops,list(x)) for x in vs] |
| 141 | assert len(orig)==len(vs) and orig==expo,'native original C vs exported C mismatch' |
| 142 | assert expo==ref,'exported C vs REFERENCE model mismatch' |
| 143 | observations+=len(vs) |
| 144 | (out/(cid+'.export.c')).write_bytes(c) |
| 145 | item.update({'result':'PASS','ops':len(ops),'export_bytes':len(c),'export_sha256':hashlib.sha256(c).hexdigest(),'semantic_identity':i1.hex(),'vectors':len(vs),'export_head':c.split(b'\n')[1][:80].decode()}) |
| 146 | except (AssertionError,ValueError,struct.error,IndexError) as exc: |
| 147 | item.update({'result':'FAIL','failure':str(exc)});failures.append(item) |
| 148 | rows.append(item) |
| 149 | # 2. Constructed accepted units: non-NORMALIZED (+2 on re-import), shared SSA, permuted slots, zero inputs. |
| 150 | A,B=(9,65535,65535,0),(9,65535,65535,1) |
| 151 | built=[('non-normalized',[A,B,(2,0,1,0)],2,'i0 + i1'), |
| 152 | ('shared-ssa',[A,B,(2,0,1,0),(4,2,2,0)],2,'(i0 + i1) * (i0 + i1)'), |
| 153 | ('permuted-slots',[(9,65535,65535,1),(9,65535,65535,0),(3,0,1,0)],2,'i1 - i0'), |
| 154 | ('right-assoc-depth-16',[A]+[(2,0,0,0)]+[(2,0,k,0) for k in range(1,17)],1,None), |
| 155 | ('max-constant',[(1,65535,65535,MASK),(1,65535,65535,0),(3,1,0,0)],0,'0ULL - 18446744073709551615ULL')] |
| 156 | constructed=[] |
| 157 | for cid,recs,nargs,expr in built: |
| 158 | item={'id':'built-'+cid} |
| 159 | try: |
| 160 | env=unit(recs);v=run([str(SA),'decode'],env);assert v.returncode==0,'constructed unit not valid v1' |
| 161 | e=export(env);assert e.returncode==0,'export refused rc=%d %s'%(e.returncode,e.stderr) |
| 162 | c=e.stdout;body=c.split(b'{ return ')[1][:-4].decode() |
| 163 | if expr:assert body==expr,'expression '+body |
| 164 | else:assert body.count('(')==16 and body.endswith(')'*16),'depth 16 chain parentheses' |
| 165 | r2=run([str(IMPORTER)],c);assert r2.returncode==0,'re-import refused' |
| 166 | s2=semantic(r2.stdout);ops2=ops_of(s2);ops=[tuple(x) for x in recs] |
| 167 | vs=vectors(nargs,rng);payload=''.join(' '.join(map(str,x))+'\n' for x in vs).encode() |
| 168 | expo=native(out,'built-'+cid,c,'calc',nargs,payload);ref=[g.evaluate(ops,list(x)) for x in vs] |
| 169 | assert expo==ref,'exported C vs REFERENCE model mismatch' |
| 170 | assert [g.evaluate(ops2,list(x)) for x in vs]==ref,'re-import evaluation differs' |
| 171 | same=s2==semantic(env) |
| 172 | if cid=='non-normalized': |
| 173 | assert ops2==ops+[(1,65535,65535,0),(2,2,3,0)],'non-NORMALIZED unit must gain exactly one +0 pair' |
| 174 | item.update({'result':'PASS','export':body[:80],'reimport_identity_equal':same,'reimport_ops':len(ops2),'vectors':len(vs)});observations+=len(vs) |
| 175 | except (AssertionError,ValueError,struct.error,IndexError) as exc: |
| 176 | item.update({'result':'FAIL','failure':str(exc)});failures.append(item) |
| 177 | constructed.append(item) |
| 178 | # 3. Refusals: status, empty stdout, named stderr. |
| 179 | good=run([str(IMPORTER)],cases[2][1]).stdout |
| 180 | sem=semantic(good) |
| 181 | def patch(buf,off,val):b=bytearray(buf);b[off]=val;return bytes(b) |
| 182 | doubling=[A]+[(2,0,0,0)]+[(2,k,k,0) for k in range(1,62)] |
| 183 | def reob(s,obl): |
| 184 | b=bytearray(s) |
| 185 | for i in range(struct.unpack_from('<H',s,10)[0]): |
| 186 | if b[44+20*i+2] in (2,3,4):b[44+20*i+7]=obl |
| 187 | return bytes(b) |
| 188 | mixed=bytearray(sem);mixed[44]=2 |
| 189 | # Valid v1 units outside the S1 family (compose section 1): CPython bigint 3, OSC 5, dynamic retained 6. |
| 190 | bigint=raw_unit((3,3,1,1),[(3,9,2,0,0,0,1,65535,65535,0),(3,9,2,0,0,0,1,65535,65535,1),(3,2,2,2,20,255,8,0,1,0)]) |
| 191 | osc=raw_unit((4,5,0,1),[(4,9,1,0,0,0,1,65535,65535,0),(4,9,1,0,0,0,1,65535,65535,1),(4,2,1,1,0,0,1,0,1,0)]) |
| 192 | dynamic=raw_unit((3,6,1,2),[(3,9,1,0,0,0,1,65535,65535,0),(3,9,1,0,0,0,1,65535,65535,1),(3,2,1,1,0,0,5,0,1,0)]) |
| 193 | div=bytearray(sem);n=struct.unpack_from('<H',sem,10)[0];off=44+20*(n-3);assert div[off+2]==2;div[off+2]=5;div[off+7]=3 |
| 194 | # Last field: the envelope must (True) / must not (False) decode under source-aware v1 (sa decode), None unchecked. |
| 195 | refusals=[('two-arguments',['calc','x'],good,64,None),('name-main',['main'],good,64,None),('name-not-profile',['foo'],good,64,None), |
| 196 | ('name-bare-omega_',['omega_'],good,64,None),('name-bad-char',['omega_a-b'],good,64,None),('name-33-bytes',['omega_'+'a'*27],good,64,None), |
| 197 | ('empty-name',[''],good,64,None), |
| 198 | ('empty-input',[],b'',65,False),('truncated',[],good[:-1],65,False),('trailing-byte',[],good+b'\x00',65,False), |
| 199 | ('bad-magic',[],patch(good,0,0x58),65,False),('over-8192',[],good+b'\x00'*(8193-len(good)),65,False), |
| 200 | ('sidecar-source-tamper',[],patch(good,len(good)-2,0x5a),65,False),('wrong-contract-hash',[],semonly(patch(sem,12,sem[12]^1)),65,False), |
| 201 | ('profile-language-mismatch',[],semonly(patch(sem,6,2)),68,False),('c-header-rust-dialect-op',[],semonly(bytes(mixed)),68,False), |
| 202 | ('rust-obligation-5',[],semonly(reob(retarget(sem,'Rust'),5)),65,False),('python-obligation-1',[],semonly(reob(retarget(sem,'Python'),1)),65,False), |
| 203 | ('cpython-bigint-profile-3',[],bigint,68,True),('osc-profile-5',[],osc,68,True),('python-dynamic-profile-6',[],dynamic,68,True), |
| 204 | ('division-op-5',[],semonly(bytes(div)),68,True),('python-division-op-5',[],semonly(patch(retarget(bytes(div),'Python'),off+7,7)),68,True), |
| 205 | ('slot-gap',[],unit([A,(9,65535,65535,2),(2,0,1,0)]),68,True), |
| 206 | ('op-capacity-65',[],unit([A,B]+[(2,0,0,0)]+[(2,k,0,0) for k in range(2,62)]),67,True), |
| 207 | ('nesting-17',[],unit([A]+[(2,0,0,0)]+[(2,0,k,0) for k in range(1,18)]),67,True), |
| 208 | ('shared-blowup-2^61',[],unit(doubling),67,True)] |
| 209 | negatives=[] |
| 210 | for cid,args,data,want,v1 in refusals: |
| 211 | r=run([sys.executable,str(CLI)]+args,data) |
| 212 | valid=None if v1 is None else run([str(SA),'decode'],data).returncode==0 |
| 213 | ok=r.returncode==want and r.stdout==b'' and b'C_EXPORT_' in r.stderr and valid==v1 |
| 214 | item={'id':cid,'want':want,'exit':r.returncode,'stdout_bytes':len(r.stdout),'stderr':r.stderr.decode(errors='replace').strip(),'valid_v1':valid,'result':'PASS' if ok else 'FAIL'} |
| 215 | if not ok:failures.append(item) |
| 216 | negatives.append(item) |
| 217 | r=run([str(EXPORTER)],b'');ok=r.returncode==64 and not r.stdout |
| 218 | negatives.append({'id':'native-no-frame','want':64,'exit':r.returncode,'result':'PASS' if ok else 'FAIL'}) |
| 219 | if not ok:failures.append(negatives[-1]) |
| 220 | # 4. Public command refuses changed source or artifact identities (78). |
| 221 | for fault in ['source','binary']: |
| 222 | with tempfile.TemporaryDirectory(prefix='closed-build-',dir=out) as td: |
| 223 | t=Path(td) |
| 224 | for rel in ['tools/adapters/c-export','src/source-aware/vendor/sha256.om','src/source-aware/core.om','src/adapters/c-u64-export.om','build/L622/build.json','build/L622/c-export']: |
| 225 | p=t/rel;p.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(ROOT/rel,p);p.chmod(0o700 if rel.endswith('c-export') else 0o600) |
| 226 | with (t/('src/adapters/c-u64-export.om' if fault=='source' else 'build/L622/c-export')).open('ab') as f:f.write(b'changed') |
| 227 | r=run([sys.executable,str(t/'tools/adapters/c-export')],good);ok=r.returncode==78 and not r.stdout and b'C_EXPORT_STALE_OR_MISSING_BUILD' in r.stderr |
| 228 | negatives.append({'id':'public-'+fault+'-identity-change','want':78,'exit':r.returncode,'result':'PASS' if ok else 'FAIL'}) |
| 229 | if not ok:failures.append(negatives[-1]) |
| 230 | # 5. Compose section 4: Rust -> C and Python -> C on the lanes' F2 fixtures (scratch checkouts; NOT_RUN if absent). |
| 231 | compose={};pyoracle=out/'pyoracle.py' |
| 232 | pyoracle.write_text("import sys\npath,name,n=sys.argv[1],sys.argv[2],int(sys.argv[3])\nns={}\nexec(compile(open(path,'rb').read().decode('ascii'),path,'exec'),ns)\nf=ns[name]\nfor line in sys.stdin:\n xs=[int(t) for t in line.split()]\n assert len(xs)==n\n v=f(*xs)\n assert type(v) is int and 0<=v<2**64,(xs,v)\n print(v)\n") |
| 233 | def rust_oracle(tag,src,name,nargs,payload): |
| 234 | call=name+'('+', '.join('v[%d]'%j for j in range(nargs))+')' |
| 235 | harness=('\nfn main() {\n use std::io::BufRead;\n for line in std::io::stdin().lock().lines() {\n let line = line.unwrap();\n' |
| 236 | ' let v: Vec<u64> = line.split_whitespace().map(|x| x.parse().unwrap()).collect();\n assert_eq!(v.len(), %d);\n println!("{}", %s);\n }\n}\n'%(nargs,call)) |
| 237 | f=out/(tag+'.rs');exe=out/tag;f.write_bytes(src+harness.encode()) |
| 238 | rustc=shutil.which('rustc') or str(Path.home()/'.cargo/bin/rustc') |
| 239 | r=subprocess.run(['nice','-n','19',rustc,'--edition','2021','-O','-C','overflow-checks=on','-o',str(exe),str(f)],capture_output=True,timeout=300) |
| 240 | assert r.returncode==0,tag+' rustc failed: '+r.stderr.decode(errors='replace')[-600:] |
| 241 | r=run([str(exe)],payload);assert r.returncode==0,tag+' rust run failed' |
| 242 | return [int(x) for x in r.stdout.split()] |
| 243 | def python_oracle(tag,src,name,nargs,payload): |
| 244 | f=out/(tag+'.py');f.write_bytes(src) |
| 245 | r=run([sys.executable,'-I','-B',str(pyoracle),str(f),name,str(nargs)],payload);assert r.returncode==0,tag+' python3 failed: '+r.stderr.decode(errors='replace')[-400:] |
| 246 | return [int(x) for x in r.stdout.split()] |
| 247 | for lang,member,root,oracle in [('rust','Rust',a.rust_root,rust_oracle),('python','Python',a.python_root,python_oracle)]: |
| 248 | if not root:compose[member+'->C']={'result':'NOT_RUN'};continue |
| 249 | root=Path(root).resolve();fx=json.loads((root/('tests/universal/translation/fixtures-f2-%s.json'%lang)).read_text()) |
| 250 | imp=root/('tools/adapters/%s-import'%lang);lrows=[] |
| 251 | for f in fx['positives']+fx.get('controls',[]): |
| 252 | src=f['source'].encode();name=f['name'];nargs=f['inputs'];item={'id':f['id']} |
| 253 | try: |
| 254 | assert hashlib.sha256(src).hexdigest()==f['sha256'],'fixture hash' |
| 255 | r=run([sys.executable,str(imp)],src);assert r.returncode==0,'%s import refused rc=%d %s'%(lang,r.returncode,r.stderr) |
| 256 | ua=r.stdout;sa_=semantic(ua);l,p_=FAMILY[member][:2];assert sa_[5]==l and sa_[6]==p_,'importer member' |
| 257 | cname=name if name.startswith('omega_') and len(name)<=32 else None |
| 258 | e=export(ua,cname);assert e.returncode==0,'C export refused rc=%d %s'%(e.returncode,e.stderr) |
| 259 | srcb=e.stdout |
| 260 | assert export(semonly(sa_),cname).stdout==srcb,'semantic-only export differs' |
| 261 | assert export(semonly(retarget(sa_,'C')),cname).stdout==srcb,'export of R(U_A,C) differs' |
| 262 | r2=run([str(IMPORTER)],srcb);assert r2.returncode==0,'C import of generated C refused rc=%d'%r2.returncode |
| 263 | sb=semantic(r2.stdout) |
| 264 | assert retarget(strip(sb),'C')==retarget(strip(sa_),'C'),'N(strip(U_B)) != N(strip(U_A))' |
| 265 | vs=vectors(nargs,rng);payload=''.join(' '.join(map(str,x))+'\n' for x in vs).encode() |
| 266 | ref=[g.evaluate(ops_of(sa_),list(x)) for x in vs] |
| 267 | orig=oracle(f['id']+'-orig',src,name,nargs,payload);gen=native(out,f['id']+'-genC',srcb,cname or 'calc',nargs,payload) |
| 268 | assert orig==ref,'%s oracle(original) != REFERENCE(U_A)'%lang |
| 269 | assert gen==ref,'cc(generated C) != REFERENCE(U_A)' |
| 270 | observations+=len(vs) |
| 271 | item.update({'result':'PASS','vectors':len(vs),'n_identity':hashlib.sha256(retarget(strip(sa_),'C')).hexdigest(),'export_head':srcb.split(b'\n')[1][:80].decode()}) |
| 272 | except (AssertionError,ValueError,struct.error,IndexError,KeyError) as exc: |
| 273 | item.update({'result':'FAIL','failure':str(exc)});failures.append(item) |
| 274 | lrows.append(item) |
| 275 | compose[member+'->C']={'result':'FAIL' if any(x['result']!='PASS' for x in lrows) else 'PASS','root':str(root), |
| 276 | 'root_commit':subprocess.check_output(['git','-C',str(root),'rev-parse','HEAD'],text=True).strip(), |
| 277 | 'fixtures':len(lrows),'passed':sum(x['result']=='PASS' for x in lrows),'not_in_profile':[x['id'] for x in fx.get('not_in_profile',[])],'cases':lrows} |
| 278 | report={'schema':'omega.c-u64-export.selftest.v2','contract_sha256':hashlib.sha256((ROOT/'spec/universal/translation-v1.md').read_bytes()).hexdigest(), |
| 279 | 'compose_contract_sha256':hashlib.sha256((ROOT/'spec/universal/translation-compose-v1.md').read_bytes()).hexdigest(), |
| 280 | 'result':'FAIL' if failures else 'PASS','status':'TESTED (author self-test; not QUALIFIED)','evidence':['DIFFERENTIAL','REFERENCE'],'proof':False, |
| 281 | 'source_commit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip(), |
| 282 | 'exporter_sha256':hashlib.sha256(EXPORTER.read_bytes()).hexdigest(),'importer_sha256':hashlib.sha256(IMPORTER.read_bytes()).hexdigest(), |
| 283 | 'cc':subprocess.check_output([os.environ.get('CC','cc'),'--version'],text=True).splitlines()[0],'cflags':CFLAGS, |
| 284 | 'boundaries':len(rows),'boundaries_passed':sum(x['result']=='PASS' for x in rows), |
| 285 | 'constructed':len(constructed),'constructed_passed':sum(x['result']=='PASS' for x in constructed), |
| 286 | 'refusals':len(negatives),'refusals_passed':sum(x['result']=='PASS' for x in negatives),'native_C_observations':observations, |
| 287 | 'compose':compose,'cases':rows,'constructed_cases':constructed,'refusal_cases':negatives,'failures':failures} |
| 288 | (out/'result.json').write_text(json.dumps(report,indent=2)+'\n') |
| 289 | for x in rows: |
| 290 | if x['id'] in ('F1-P05','F1-P13','control-operation-capacity'):print(x['id'],x.get('export_head',x.get('failure'))) |
| 291 | for x in failures:print('FAIL',json.dumps(x)[:400]) |
| 292 | print('%s boundaries=%d/%d identical_reimport=%d retarget_identical_exports=%d constructed=%d/%d refusals=%d/%d native_C_observations=%d'%(report['result'],report['boundaries_passed'],len(rows),report['boundaries_passed'],2*report['boundaries_passed'],report['constructed_passed'],len(constructed),report['refusals_passed'],len(negatives),observations)) |
| 293 | for k,v in compose.items():print('compose',k,v['result'],'%d/%d'%(v['passed'],v['fixtures']) if 'fixtures' in v else '','not_in_profile=%s'%v.get('not_in_profile','')) |
| 294 | return 1 if failures else 0 |
| 295 | if __name__=='__main__':raise SystemExit(main()) |