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 / zig_selftest.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Zig lane (#740) author self-test: TESTED evidence only (translation-v1 section 10), never QUALIFIED. |
| 3 | |
| 4 | For every F2-zig fixture: Zig import, independent decode of the v2 unit, v2 codec acceptance (`sa` from a |
| 5 | build/L832 tree, else NOT_RUN), cross-importer identity against the C import of the F1 source, export of |
| 6 | the unit and of R(U, M) for all six family members (semantic-only, identical bytes), re-import identity |
| 7 | (translation-compose-v1 section 4.1), and Zig 0.17 DIFFERENTIAL in Debug and ReleaseSafe (original and |
| 8 | exported Zig) against a bigint evaluation of the records. Compositions C->Zig and Zig->C (R(U, C) by |
| 9 | tools/adapters/retarget when present, cross-checked against the test-code R; translation-compose-v2 section 2), each with the native |
| 10 | realization lower(N(U_A)) when the G1 lowering tools are present. |
| 11 | """ |
| 12 | from pathlib import Path |
| 13 | import argparse,hashlib,json,os,random,re,shutil,struct,subprocess,sys,tempfile |
| 14 | ROOT=Path(__file__).resolve().parents[3] |
| 15 | MASK=(1<<64)-1 |
| 16 | SEMDOM=b'omega.source.semantic.v1' |
| 17 | CONTRACT=hashlib.sha256((ROOT/'spec/universal/semantics.md').read_bytes()).digest() |
| 18 | # translation-compose-v2 section 1: OMSA version, language (= op dialect), profile, arithmetic obligations. |
| 19 | MEMBERS={'C':(1,1,1,1),'Rust':(1,2,2,1),'Python':(1,3,4,5),'Cpp':(2,5,7,1),'Zig':(2,6,8,1),'Go':(2,7,9,1)} |
| 20 | BOUNDARY=[0,1,2,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK] |
| 21 | IMPORT=ROOT/'tools/adapters/zig-import';EXPORT=ROOT/'tools/adapters/zig-export' |
| 22 | OMC_PIN='734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61' |
| 23 | BRIDGE_COMMIT='012860dbf26ee62a9838594b9dfd1e3e94a540a9' |
| 24 | NATIVE_OM_PIN='2c2c53f61d4ab302f1a2092c3c32189335dd53f6cf2b388f47a475f99f2c3940' |
| 25 | ZIG_MODES=('Debug','ReleaseSafe') |
| 26 | PLAIN=re.compile(rb'[+\-*](?!%)') |
| 27 | |
| 28 | class Fail(Exception):pass |
| 29 | def check(c,msg): |
| 30 | if not c:raise Fail(msg) |
| 31 | |
| 32 | def run(cmd,data,cwd=None,timeout=60,env=None): |
| 33 | return subprocess.run(cmd,input=data,capture_output=True,timeout=timeout,cwd=cwd,env=env) |
| 34 | |
| 35 | def py(tool,data,*args):return run([sys.executable,str(tool),*args],data) |
| 36 | |
| 37 | # ---- independent envelope model (not the #621 codec) ---- |
| 38 | def split(env): |
| 39 | check(len(env)>=13 and env[:5]==b'OMSB\x01','bad envelope magic') |
| 40 | ns,np_=struct.unpack_from('<II',env,5);check(len(env)==13+ns+np_,'bad envelope length') |
| 41 | return env[13:13+ns],env[13+ns:] |
| 42 | |
| 43 | def ops_of(sem): |
| 44 | count=struct.unpack_from('<H',sem,10)[0];check(len(sem)==44+20*count,'bad semantic length') |
| 45 | return [struct.unpack_from('<8BHHQ',sem,44+20*i) for i in range(count)] |
| 46 | |
| 47 | def records(sem):return [(o[2],o[8],o[9],o[10]) for o in ops_of(sem)] |
| 48 | |
| 49 | def decode(env,member): |
| 50 | ver,lang,prof,arob=MEMBERS[member] |
| 51 | sem,side=split(env) |
| 52 | check(sem[:4]==b'OMSA' and sem[4]==ver and sem[5]==lang and sem[6]==prof and sem[7:10]==b'\x01\x00\x01','wrong %s header'%member) |
| 53 | check(sem[12:44]==CONTRACT,'wrong parent semantics hash') |
| 54 | ops=[];slots=[] |
| 55 | for i,(d,v,op,t,attr,eff,alias,obl,a,b,imm) in enumerate(ops_of(sem)): |
| 56 | check(d==lang and v==1 and t==1 and eff==0 and alias==0,'op %d fields'%i) |
| 57 | if op==9:check(attr==0 and obl==1 and a==b==65535,'input op');slots.append(imm) |
| 58 | elif op==1:check(attr==1 and obl==0 and a==b==65535,'const op') |
| 59 | else:check(op in (2,3,4) and attr==1 and obl==arob and a<i and b<i and imm==0,'arith op %d'%i) |
| 60 | ops.append((op,a,b,imm)) |
| 61 | check(sorted(slots)==list(range(len(slots))),'input slots not a permutation') |
| 62 | return sem,side,ops |
| 63 | |
| 64 | def sidecar(sem,side,src,count): |
| 65 | check(side[:6]==b'OMSP\x01\x01','sidecar must be v1 encoding 1 (strict UTF-8)') |
| 66 | check(struct.unpack_from('<I',side,6)[0]==len(src) and side[10:42]==hashlib.sha256(sem).digest() and side[42:74]==hashlib.sha256(src).digest(),'bad sidecar binding') |
| 67 | check(len(side)==74+8*count+len(src) and side[74+8*count:]==src,'sidecar source mismatch') |
| 68 | return [struct.unpack_from('<II',side,74+8*i) for i in range(count)] |
| 69 | |
| 70 | def evaluate(ops,args): |
| 71 | vals=[] |
| 72 | for op,a,b,imm in ops: |
| 73 | v=args[imm] if op==9 else imm if op==1 else vals[a]+vals[b] if op==2 else vals[a]-vals[b] if op==3 else vals[a]*vals[b] |
| 74 | vals.append(v&MASK) |
| 75 | return vals[-1] |
| 76 | |
| 77 | def normalized(ops): |
| 78 | n=len(ops) |
| 79 | return n>=3 and ops[n-2][0]==1 and ops[n-2][3]==0 and ops[n-1][0]==2 and ops[n-1][2]==n-2 and ops[n-1][1]<n-2 |
| 80 | |
| 81 | def retarget(sem,member): |
| 82 | """R(U, M), translation-compose-v2 section 2 (test-code stand-in for tools/adapters/retarget): |
| 83 | OMSA version, header language/profile, op dialect and arithmetic obligations; sidecar dropped by the caller.""" |
| 84 | ver,lang,prof,arob=MEMBERS[member];b=bytearray(sem);b[4]=ver;b[5]=lang;b[6]=prof |
| 85 | for i,(_,_,op,*_) in enumerate(ops_of(sem)): |
| 86 | b[44+20*i]=lang |
| 87 | if op in (2,3,4):b[44+20*i+7]=arob |
| 88 | return bytes(b) |
| 89 | |
| 90 | def N(sem):return retarget(sem,'C') |
| 91 | |
| 92 | def strip(sem): |
| 93 | ops=ops_of(sem) |
| 94 | if not normalized([(o[2],o[8],o[9],o[10]) for o in ops]):return sem |
| 95 | n=len(ops)-2;b=bytearray(sem[:44+20*n]);struct.pack_into('<H',b,10,n);return bytes(b) |
| 96 | |
| 97 | def semonly(sem):return b'OMSB\x01'+struct.pack('<II',len(sem),0)+sem |
| 98 | def identity(sem):return hashlib.sha256(SEMDOM+sem).hexdigest() |
| 99 | |
| 100 | def vectors(nargs,rng): |
| 101 | if nargs==0:return [()] |
| 102 | if nargs<=2:base=[(x,) for x in BOUNDARY] if nargs==1 else [(x,y) for x in BOUNDARY for y in BOUNDARY] |
| 103 | else:base=[tuple(BOUNDARY[(j+k)%len(BOUNDARY)] for k in range(nargs)) for j in range(len(BOUNDARY))] |
| 104 | return base+[tuple(rng.getrandbits(64) for _ in range(nargs)) for _ in range(32)] |
| 105 | |
| 106 | # ---- Zig oracle: every requested program is one module of a single harness per build mode ---- |
| 107 | ZHEAD=('extern "c" fn scanf(fmt: [*:0]const u8, ...) c_int;\nextern "c" fn printf(fmt: [*:0]const u8, ...) c_int;\n' |
| 108 | 'pub fn main() void {\n var id: u64 = 0;\n var x: [6]u64 = .{ 0, 0, 0, 0, 0, 0 };\n' |
| 109 | ' while (scanf("%llu %llu %llu %llu %llu %llu %llu", &id, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5]) == 7) {\n' |
| 110 | ' const r: u64 = switch (id) {\n') |
| 111 | ZTAIL=' else => unreachable,\n };\n _ = printf("%llu\\n", r);\n }\n}\n' |
| 112 | class Zig: |
| 113 | def __init__(s,out,zig): |
| 114 | s.out=out/'zig';s.out.mkdir();s.zig=zig;s.items=[];s.compiles=0;s.observations=0 |
| 115 | s.env=dict(os.environ,ZIG_GLOBAL_CACHE_DIR=str(s.out/'cache'),ZIG_LOCAL_CACHE_DIR=str(s.out/'cache')) |
| 116 | def add(s,tag,text,name,vecs,ref):s.items.append((tag,text,name,vecs,ref)) |
| 117 | def build(s,d,mods,mode): |
| 118 | """mods: list of (text,name,nargs); returns (ok, stderr, exe).""" |
| 119 | d.mkdir(parents=True,exist_ok=True);main=[] |
| 120 | for j,(text,name,nargs) in enumerate(mods): |
| 121 | (d/('m%d.zig'%j)).write_bytes(text);main.append('const m%d = @import("m%d.zig");\n'%(j,j)) |
| 122 | body=''.join(' %d => m%d.%s(%s),\n'%(j,j,name,', '.join('x[%d]'%k for k in range(nargs))) for j,(_,name,nargs) in enumerate(mods)) |
| 123 | (d/'main.zig').write_text(''.join(main)+ZHEAD+body+ZTAIL) |
| 124 | r=run(['nice','-n','19',s.zig,'build-exe','-O',mode,'-lc','main.zig','-femit-bin=main'],None,cwd=d,timeout=900,env=s.env);s.compiles+=1 |
| 125 | return r.returncode==0,r.stderr.decode(errors='replace'),d/'main' |
| 126 | def execute(s,exe,lines): |
| 127 | r=run([str(exe)],''.join(lines).encode(),timeout=300) |
| 128 | return r.returncode,[int(x) for x in r.stdout.split()],r.stderr.decode(errors='replace') |
| 129 | def evaluate_all(s): |
| 130 | """Returns {tag: failure message} over every item and both modes.""" |
| 131 | failures={} |
| 132 | keys={};mods=[] |
| 133 | for tag,text,name,vecs,ref in s.items: |
| 134 | k=(text,name,len(vecs[0])) |
| 135 | if k not in keys:keys[k]=len(mods);mods.append(k) |
| 136 | for mode in ZIG_MODES: |
| 137 | ok,err,exe=s.build(s.out/('batch-'+mode),mods,mode) |
| 138 | if not ok: |
| 139 | bad=set() |
| 140 | for j,m in enumerate(mods): |
| 141 | o,e,_=s.build(s.out/('single-%s-%d'%(mode,j)),[m],mode) |
| 142 | if not o:bad.add(j);failures.setdefault('module%d'%j,'zig %s compile: %s'%(mode,e[-600:])) |
| 143 | for tag,text,name,vecs,ref in s.items: |
| 144 | if keys[(text,name,len(vecs[0]))] in bad:failures.setdefault(tag,'zig %s compile failed: %s'%(mode,failures['module%d'%keys[(text,name,len(vecs[0]))]])) |
| 145 | keep=[m for j,m in enumerate(mods) if j not in bad] |
| 146 | if not keep:continue |
| 147 | ok,err,exe=s.build(s.out/('batch2-'+mode),keep,mode) |
| 148 | check(ok,'zig batch rebuild failed: '+err[-600:]);idx={m:j for j,m in enumerate(keep)} |
| 149 | else:idx={m:j for j,m in enumerate(mods)} |
| 150 | lines=[];spans=[] |
| 151 | for tag,text,name,vecs,ref in s.items: |
| 152 | m=(text,name,len(vecs[0])) |
| 153 | if m not in idx:continue |
| 154 | spans.append((tag,len(lines),len(vecs),ref,m)) |
| 155 | for v in vecs:lines.append(' '.join(map(str,(idx[m],*v,*([0]*(6-len(v))))))+'\n') |
| 156 | rc,got,err=s.execute(exe,lines) |
| 157 | if rc!=0 or len(got)!=len(lines): |
| 158 | # Attribute: run each item alone on the same binary. |
| 159 | for tag,start,count,ref,m in spans: |
| 160 | r2,g2,e2=s.execute(exe,lines[start:start+count]) |
| 161 | if r2!=0 or g2!=ref:failures.setdefault(tag,'zig %s run rc=%d %s'%(mode,r2,e2[-300:])) |
| 162 | continue |
| 163 | s.observations+=len(got) |
| 164 | for tag,start,count,ref,m in spans: |
| 165 | if got[start:start+count]!=ref:failures.setdefault(tag,'zig %s result != reference'%mode) |
| 166 | return failures |
| 167 | |
| 168 | class COracle: |
| 169 | def __init__(s,out,cc):s.out=out/'c';s.out.mkdir();s.cc=cc;s.cache={};s.compiles=0;s.observations=0 |
| 170 | def values(s,text,name,vecs): |
| 171 | nargs=len(vecs[0]);key=hashlib.sha256(name.encode()+b'\0'+text).hexdigest() |
| 172 | if key not in s.cache: |
| 173 | f=s.out/(key[:24]+'.c');exe=s.out/key[:24] |
| 174 | body=('uint64_t x[6]={0};while(scanf("'+' '.join(['%" SCNu64 "']*nargs)+'",'+','.join('&x[%d]'%j for j in range(nargs))+')==%d)'%nargs+ |
| 175 | 'printf("%" PRIu64 "\\n",'+name+'('+','.join('x[%d]'%j for j in range(nargs))+'));') if nargs else 'printf("%" PRIu64 "\\n",'+name+'());' |
| 176 | f.write_bytes(text+('\n#include <stdio.h>\n#include <inttypes.h>\nint main(void){'+body+'return 0;}\n').encode()) |
| 177 | r=run(['nice','-n','19',s.cc,'-std=c17','-O2','-Wall','-Wextra','-Werror','-Wno-unused-parameter',str(f),'-o',str(exe)],None,timeout=180);s.compiles+=1 |
| 178 | check(r.returncode==0,'cc compile failed: '+r.stderr.decode(errors='replace')[-600:]);s.cache[key]=exe |
| 179 | r=run([str(s.cache[key])],''.join(' '.join(map(str,v))+'\n' for v in vecs).encode()) |
| 180 | check(r.returncode==0,'cc program failed');s.observations+=len(vecs) |
| 181 | return [int(x) for x in r.stdout.split()] |
| 182 | |
| 183 | # ---- native realization (translation-v1 section 5): lower(N(U)) -> omc 734f0a39 -> bridge binding -> caller ---- |
| 184 | CALLER='''#include <inttypes.h> |
| 185 | #include <stdio.h> |
| 186 | #include <stdlib.h> |
| 187 | uint32_t omega_calc(uint64_t *result%s); |
| 188 | int main(void) |
| 189 | { |
| 190 | char line[512]; |
| 191 | while (fgets(line, sizeof line, stdin)) { |
| 192 | char *p = line; |
| 193 | uint64_t a[6] = {0}; |
| 194 | for (int i = 0; i < 6; i++) |
| 195 | a[i] = strtoull(p, &p, 10); |
| 196 | (void)a; |
| 197 | uint64_t r = UINT64_C(6148914691236517205); |
| 198 | uint32_t s = omega_calc(&r%s); |
| 199 | printf("%%" PRIu32 " %%" PRIu64 "\\n", s, r); |
| 200 | } |
| 201 | return 0; |
| 202 | } |
| 203 | ''' |
| 204 | class Native: |
| 205 | def __init__(s,out,lower,omc,bridge,cc): |
| 206 | s.state='NOT_RUN';s.reason='';s.cache={};s.calls=0;s.cc=cc;s.lower=Path(lower) |
| 207 | try: |
| 208 | check(s.lower.is_file(),'lowering tool missing: '+lower) |
| 209 | check(Path(omc).is_file() and hashlib.sha256(Path(omc).read_bytes()).hexdigest()==OMC_PIN,'native omc missing or not 734f0a39') |
| 210 | src=run(['git','-C',bridge,'show',BRIDGE_COMMIT+':src/native.om'],None).stdout |
| 211 | check(hashlib.sha256(src).hexdigest()==NATIVE_OM_PIN,'bridge native.om pin') |
| 212 | r=run([omc],src);check(r.returncode==0,'bridge generator compile') |
| 213 | s.dir=out/'native';s.dir.mkdir();s.gen=s.dir/'native';s.gen.write_bytes(r.stdout);s.gen.chmod(0o700);s.omc=omc;s.state='RUN' |
| 214 | except (Fail,OSError,subprocess.SubprocessError) as e:s.reason=str(e) |
| 215 | def values(s,nsem,nargs,vecs): |
| 216 | key=identity(nsem) |
| 217 | if key not in s.cache: |
| 218 | d=s.dir/key[:24];d.mkdir() |
| 219 | r=py(s.lower,semonly(nsem));check(r.returncode==0,'lower refused N(U) rc=%d %s'%(r.returncode,r.stderr)) |
| 220 | unit=r.stdout;c=run([s.omc],unit);check(c.returncode==0 and c.stdout,'omc function-mode compile failed') |
| 221 | b=run([str(s.gen)],unit+b'\0'+b'%08d'%len(c.stdout)+c.stdout);check(b.returncode==0 and b.stdout,'bridge binding failed') |
| 222 | (d/'omega_native.c').write_bytes(b.stdout) |
| 223 | (d/'caller.c').write_text(CALLER%(''.join(', uint64_t i%d'%i for i in range(nargs)),''.join(', a[%d]'%i for i in range(nargs)))) |
| 224 | k=run([s.cc,'-std=gnu11','-O2','-Wall','-Wextra','-Werror','-pthread',str(d/'caller.c'),str(d/'omega_native.c'),'-o',str(d/'caller')],None,timeout=180) |
| 225 | check(k.returncode==0,'native caller compile: '+k.stderr.decode(errors='replace')[-400:]);s.cache[key]=d/'caller' |
| 226 | r=run([str(s.cache[key])],''.join(' '.join(map(str,v))+'\n' for v in vecs).encode()) |
| 227 | lines=r.stdout.decode().split('\n')[:-1];check(r.returncode==0 and len(lines)==len(vecs),'native caller run') |
| 228 | out=[] |
| 229 | for line in lines: |
| 230 | st,val=line.split();check(st=='0','native status '+st);out.append(int(val)) |
| 231 | s.calls+=len(vecs);return out |
| 232 | |
| 233 | def main(): |
| 234 | ap=argparse.ArgumentParser() |
| 235 | ap.add_argument('--out',required=True) |
| 236 | ap.add_argument('--zig',default=os.environ.get('ZIG') or shutil.which('zig') or '',help='Zig 0.17.0 (default: $ZIG, else zig on PATH; missing = NOT_RUN, exit 3)') |
| 237 | ap.add_argument('--cc',default=os.environ.get('CC','cc')) |
| 238 | ap.add_argument('--c-import',default=str(ROOT/'build/L589/c-import'),help='native C importer (default: in-tree build of mk/c-u64-import.mk)') |
| 239 | ap.add_argument('--c-export',default=str(ROOT/'tools/adapters/c-export'),help='public C exporter (default: in-tree, built by mk/c-u64-export.mk)') |
| 240 | ap.add_argument('--lower',default=str(ROOT/'tools/adapters/lower'),help='public lowering (default: in-tree, built by mk/lower.mk)') |
| 241 | ap.add_argument('--omc',default=os.environ.get('OMEGA_NATIVE_OMC'),required='OMEGA_NATIVE_OMC' not in os.environ,help='native realization omc 734f0a39 (default: $OMEGA_NATIVE_OMC)') |
| 242 | ap.add_argument('--bridge',default=os.environ.get('OMEGA_BRIDGE_REPO'),required='OMEGA_BRIDGE_REPO' not in os.environ,help='omega-bridge repository holding 012860db (default: $OMEGA_BRIDGE_REPO)') |
| 243 | ap.add_argument('--sa-v2-root',default=str(ROOT),help='tree with build/L832/sa, the #621 v2 codec (default: this repo, built by mk/source-aware-v2.mk)') |
| 244 | ap.add_argument('--retarget',default=str(ROOT/'tools/adapters/retarget') if (ROOT/'tools/adapters/retarget').is_file() else '', |
| 245 | help='public tools/adapters/retarget (default: in-tree when present); every use is cross-checked against the test-code R') |
| 246 | a=ap.parse_args() |
| 247 | zig=shutil.which(a.zig) if a.zig else None |
| 248 | if not zig: |
| 249 | print('NOT_RUN zig oracle not found (set ZIG or put zig 0.17.0 on PATH): %r'%a.zig,file=sys.stderr);return 3 |
| 250 | a.zig=str(Path(zig).resolve()) |
| 251 | out=Path(a.out).resolve();out.mkdir(parents=True,exist_ok=False) |
| 252 | cimp=Path(a.c_import);cexp=Path(a.c_export);v2root=Path(a.sa_v2_root);rtool=Path(a.retarget) if a.retarget else None |
| 253 | Z=Zig(out,a.zig);C=COracle(out,a.cc);NAT=Native(out,a.lower,a.omc,a.bridge,a.cc) |
| 254 | rng=random.Random(740);failures=[];counts={};rows_by_tag={} |
| 255 | def bump(k,n=1):counts[k]=counts.get(k,0)+n |
| 256 | v2_state='RUN' if (v2root/'build/L832/sa').is_file() else 'NOT_RUN' |
| 257 | def sa1(cmd,env): |
| 258 | r=run(['sh','tools/source-aware/sa',cmd],env,cwd=ROOT);bump('sa_v1_requests');return r |
| 259 | def sa2(cmd,env): |
| 260 | r=run(['sh','tools/source-aware/sa',cmd],env,cwd=v2root,env=dict(os.environ,SA_BUILD='build/L832'));bump('sa_v2_requests');return r |
| 261 | def zimport(src): |
| 262 | r=py(IMPORT,src);bump('zig_import_runs');return r |
| 263 | def zexport(env): |
| 264 | r=py(EXPORT,env);bump('zig_export_runs');return r |
| 265 | TOOLM={'C':'c','Rust':'rust','Python':'python','Cpp':'cpp','Zig':'zig','Go':'go'} |
| 266 | def R(env,m): |
| 267 | """R(U, M) as a semantic-only envelope: the retarget tool when given (must equal the test-code R), else test code.""" |
| 268 | want=semonly(retarget(split(env)[0],m)) |
| 269 | if rtool is None:return want |
| 270 | r=py(rtool,env,TOOLM[m]);bump('retarget_runs') |
| 271 | check(r.returncode==0 and r.stdout==want,'retarget %s rc=%d differs from test-code R %s'%(TOOLM[m],r.returncode,r.stderr)) |
| 272 | return r.stdout |
| 273 | def native(sem,nargs,vecs,ref): |
| 274 | if NAT.state!='RUN':return 'NOT_RUN ('+NAT.reason+')' |
| 275 | check(NAT.values(N(sem),nargs,vecs)==ref,'native realization lower(N(U_A)) != reference');return 'PASS' |
| 276 | |
| 277 | f1=json.loads((ROOT/'tests/universal/translation/fixtures-f1.json').read_text()) |
| 278 | f2=json.loads((ROOT/'tests/universal/translation/fixtures-f2-zig.json').read_text()) |
| 279 | f1pos={p['id']:p for p in f1['positives']} |
| 280 | check(len(f2['positives'])+len(f2['not_in_profile'])==len(f1pos),'F2-zig does not cover every F1 positive') |
| 281 | check({p['f1_id'] for p in f2['positives']}|{p['f1_id'] for p in f2['not_in_profile']}==set(f1pos),'F2-zig F1 id set') |
| 282 | |
| 283 | # Oracle controls: a plain + must panic on overflow in Debug and ReleaseSafe (checked illegal behavior); |
| 284 | # the same harness with +% wraps. Proves the build modes keep the safety checks a plain operator would hit. |
| 285 | ctl_dir=out/'zig-control';oracle_control={} |
| 286 | for mode in ZIG_MODES: |
| 287 | okp,errp,exep=Z.build(ctl_dir/('plain-'+mode),[(b'pub fn calc(a: u64, b: u64) u64 {\n return a + b;\n}\n','calc',2)],mode) |
| 288 | okw,errw,exew=Z.build(ctl_dir/('wrap-'+mode),[(b'pub fn calc(a: u64, b: u64) u64 {\n return a +% b;\n}\n','calc',2)],mode) |
| 289 | rp=run([str(exep)],b'0 %d 1 0 0 0 0\n'%MASK) if okp else None |
| 290 | rw=run([str(exew)],b'0 %d 1 0 0 0 0\n'%MASK) if okw else None |
| 291 | good=okp and okw and rp.returncode!=0 and b'integer overflow' in rp.stderr and rw.returncode==0 and rw.stdout==b'0\n' |
| 292 | oracle_control[mode]='PASS' if good else 'FAIL' |
| 293 | if not good:failures.append({'name':'oracle-control-'+mode,'result':'FAIL'}) |
| 294 | |
| 295 | def export_checks(sem,env_with_sidecar,tag): |
| 296 | """Exporter: identical bytes for every family member, semantic-only; returns src_B.""" |
| 297 | r=zexport(env_with_sidecar);check(r.returncode==0 and r.stderr==b'',tag+' export refused rc=%d %s'%(r.returncode,r.stderr)) |
| 298 | text=r.stdout |
| 299 | for m in MEMBERS: |
| 300 | u=R(env_with_sidecar,m);rs=split(u)[0] |
| 301 | check(N(rs)==N(sem),tag+' N(R(U,%s)) != N(U)'%m) |
| 302 | if MEMBERS[m][0]==1:check(sa1('decode',u).returncode==0,tag+' R(U,%s) not a valid v1 unit'%m) |
| 303 | elif v2_state=='RUN':check(sa2('decode',u).stdout==u,tag+' R(U,%s) not a valid v2 unit'%m) |
| 304 | q=zexport(u);check(q.returncode==0 and q.stdout==text,tag+' export differs for member '+m+' (semantic-only)') |
| 305 | bump('member_exports',len(MEMBERS)) |
| 306 | lines=text.split(b'\n') |
| 307 | check(text.startswith(b'pub fn calc(') and text.endswith(b';\n}\n') and len(lines)==4 and lines[1].startswith(b' return '),tag+' export form') |
| 308 | check(not PLAIN.search(lines[1]),tag+' plain operator in export') |
| 309 | return text |
| 310 | |
| 311 | def reimport_identity(sem_a,src_b,tag): |
| 312 | r=zimport(src_b);check(r.returncode==0,tag+' re-import refused rc=%d %s'%(r.returncode,r.stderr)) |
| 313 | sem_b,side_b,ops_b=decode(r.stdout,'Zig');sidecar(sem_b,side_b,src_b,len(ops_b)) |
| 314 | check(N(strip(sem_b))==N(strip(sem_a)),tag+' identity N(strip(U_B)) != N(strip(U_A))') |
| 315 | return sem_b,ops_b |
| 316 | |
| 317 | def row(tag,fn): |
| 318 | item={'id':tag};rows_by_tag[tag]=item |
| 319 | try:fn(item);item.setdefault('result','PASS') |
| 320 | except (Fail,ValueError,KeyError,IndexError,struct.error,subprocess.TimeoutExpired) as e: |
| 321 | item.update(result='FAIL',failure=str(e));failures.append(item) |
| 322 | return item |
| 323 | |
| 324 | # ---- F2-zig positives ---- |
| 325 | def positive(fx): |
| 326 | def body(item): |
| 327 | src=fx['source'].encode();check(hashlib.sha256(src).hexdigest()==fx['sha256'],'fixture sha') |
| 328 | p1=f1pos[fx['f1_id']];check(p1['sha256']==fx['f1_sha256'] and p1['inputs']==fx['inputs'] and p1['name']==fx['name'],'F1 link') |
| 329 | r=zimport(src);check(r.returncode==0 and r.stderr==b'','import refused rc=%d %s'%(r.returncode,r.stderr)) |
| 330 | check(zimport(src).stdout==r.stdout,'import not byte-deterministic') |
| 331 | env=r.stdout;sem,side,ops=decode(env,'Zig');spans=sidecar(sem,side,src,len(ops)) |
| 332 | check(normalized(ops),'importer must append the normalization pair') |
| 333 | check(spans[-1]==spans[-2]==(0,0),'synthetic pair spans') |
| 334 | for (op,_,_,imm),(lo,hi) in zip(ops[:-2],spans[:-2]): |
| 335 | t=src[lo:hi] |
| 336 | if op==1:check(t==b'%d'%imm,'literal span') |
| 337 | elif op==9:check(len(t)>0 and (t==b'_' or t[:1].isalpha()) and t.isascii(),'input span') |
| 338 | else:check(t==b'+%-%*%'[2*(op-2):2*(op-1)],'operator span') |
| 339 | if v2_state=='RUN': |
| 340 | ident=sa2('identity',env);check(ident.returncode==0 and ident.stdout.hex()==identity(sem),'sa v2 identity refused or differs') |
| 341 | check(sa2('decode',env).stdout==env,'sa v2 decode changed unit');check(sa2('replay',env).stdout==src,'sa v2 replay differs from source') |
| 342 | c=run([str(cimp)],p1['source'].encode());bump('c_import_runs');check(c.returncode==0,'C import of F1 refused') |
| 343 | csem,_,cops=decode(c.stdout,'C');check(N(sem)==N(csem),'cross-importer identity: N(import_Zig(F2)) != N(import_C(F1))') |
| 344 | exported=export_checks(sem,env,fx['id']) |
| 345 | sem_b,ops_b=reimport_identity(sem,exported,fx['id']) |
| 346 | check(sem_b==sem,'same-language round trip changed the semantic bytes') |
| 347 | vec=vectors(fx['inputs'],rng);ref=[evaluate(ops,v) for v in vec] |
| 348 | Z.add(fx['id'],src,fx['name'],vec,ref);Z.add(fx['id'],exported,'calc',vec,ref) |
| 349 | check(C.values(p1['source'].encode(),p1['name'],vec)==ref,'cc(F1 C) != reference') |
| 350 | s2=strip(sem);q=zexport(semonly(s2));check(q.returncode==0,'export of stripped unit refused') |
| 351 | r2=zimport(q.stdout);check(r2.returncode==0,'re-import of stripped export refused') |
| 352 | sem2,_,ops2=decode(r2.stdout,'Zig') |
| 353 | check([evaluate(ops2,v) for v in vec]==[evaluate(records(s2),v) for v in vec],'stripped round trip evaluation differs') |
| 354 | item.update(ops=len(ops),vectors=len(vec),semantic_identity=identity(sem),N_identity=identity(N(sem)),exported=exported.decode(), |
| 355 | stripped_reimport_identity_equal=N(strip(sem2))==N(s2)) |
| 356 | return body |
| 357 | rows=[row(fx['id'],positive(fx)) for fx in f2['positives']] |
| 358 | |
| 359 | # ---- Zig import refusals ---- |
| 360 | refusals=[] |
| 361 | for fx in f2['refusals']: |
| 362 | src=bytes.fromhex(fx['source_hex']) if 'source_hex' in fx else fx['source'].encode() |
| 363 | r=zimport(src);ok=hashlib.sha256(src).hexdigest()==fx['sha256'] and r.returncode==fx['status'] and r.stdout==b'' and r.stderr.startswith(b'ZIG_IMPORT_') |
| 364 | it={'id':fx['id'],'name':fx['name'],'want':fx['status'],'exit':r.returncode,'stderr':r.stderr.decode(errors='replace').strip(),'result':'PASS' if ok else 'FAIL'} |
| 365 | if not ok:failures.append(it) |
| 366 | refusals.append(it) |
| 367 | |
| 368 | # ---- import boundary controls (exact and over capacity); accepted ones exported, re-imported, run ---- |
| 369 | head=b'pub fn calc(a: u64, b: u64) u64 {\n return ' |
| 370 | base=head+b'a +% b;\n}\n' |
| 371 | chain=lambda k:head+b'a'+b' +% a'*k+b' +% b;\n}\n' |
| 372 | parens=lambda k:head+b'('*k+b'a'+b')'*k+b' +% b;\n}\n' |
| 373 | asnest=lambda k:head+b'('*k+b'a +% @as(u64, 5)'+b')'*k+b' +% b;\n}\n' |
| 374 | controls=[('exact-source-capacity',base+b' '*(4096-len(base)),0,12),('comment-at-capacity',base+b'//'+b'x'*(4096-len(base)-2),0,12), |
| 375 | ('operation-capacity',chain(59),0,60*5+7),('nesting-limit',parens(16),0,12),('as-nesting-limit',asnest(15),0,17), |
| 376 | ('over-source-capacity',base+b' '*(4097-len(base)),67,None),('over-operation-capacity',chain(60),67,None), |
| 377 | ('over-nesting-limit',parens(17),67,None),('over-as-nesting-limit',asnest(16),67,None)] |
| 378 | # Accepted spelling variants: each must import, round-trip and build/run under the Zig oracle (accepted => valid Zig). |
| 379 | variants=[('no-whitespace',b'pub fn calc(a:u64,b:u64)u64{return a+%b*%a-%@as(u64,3);}',0,37), |
| 380 | ('tabs-and-bare-cr',b'pub\tfn\tcalc(a: u64,\tb: u64) u64 {\r\treturn a\t+%\tb;\r}\r',0,12), |
| 381 | ('comments-everywhere',b'pub // x\nfn calc(a: u64, // y\n b: u64) u64 { // z\n return a +% // w\n b; // v\n} // end',0,12), |
| 382 | ('return-paren',b'pub fn calc(a: u64, b: u64) u64 {\n return(a)+%(b);\n}\n',0,12), |
| 383 | ('as-spacing',b'pub fn calc(a: u64, b: u64) u64 {\n return a +% @as( u64 , 5 ) +% b;\n}\n',0,17), |
| 384 | ('four-slash-and-unicode-comment','//// \u00fc \U0001d11e \u2028 \u0085\npub fn calc(a: u64, b: u64) u64 {\n return a +% b;\n}\n'.encode(),0,12), |
| 385 | ('operator-line-start',b'pub fn calc(a: u64, b: u64) u64 {\n return a\n *% b\n -% 1;\n}\n',0,34), |
| 386 | ('discard-params',b'pub fn calc(_: u64, b: u64, _: u64) u64 {\n return b *% b;\n}\n',0,None)] |
| 387 | controls+=[('variant-'+n,s,w,v) for n,s,w,v in variants] |
| 388 | ctl=[] |
| 389 | for name,src,want,value in controls: |
| 390 | def body(it,name=name,src=src,want=want,value=value): |
| 391 | it['source_bytes']=len(src);r=zimport(src);it['exit']=r.returncode |
| 392 | if want:check(r.returncode==want and not r.stdout and r.stderr==b'ZIG_IMPORT_LIMIT\n','%s rc=%d'%(name,r.returncode));return |
| 393 | check(r.returncode==0,'%s refused rc=%d %s'%(name,r.returncode,r.stderr));sem,side,ops=decode(r.stdout,'Zig');sidecar(sem,side,src,len(ops)) |
| 394 | nargs=sum(1 for o in ops if o[0]==9) |
| 395 | if value is not None:check(evaluate(ops,[5,7])==value,name+' value %d'%evaluate(ops,[5,7])) |
| 396 | exported=export_checks(sem,r.stdout,name) |
| 397 | sem_b,_=reimport_identity(sem,exported,name);check(sem_b==sem,name+' round trip') |
| 398 | vec=vectors(nargs,rng);ref=[evaluate(ops,v) for v in vec] |
| 399 | Z.add('control '+name,src,'calc',vec,ref);Z.add('control '+name,exported,'calc',vec,ref) |
| 400 | it.update(ops=len(ops),exported_bytes=len(exported)) |
| 401 | ctl.append(row('control '+name,body)) |
| 402 | def closed(tool,msg): |
| 403 | r=subprocess.run([str(ROOT/'build/L740'/tool)],stdin=subprocess.DEVNULL,capture_output=True,preexec_fn=lambda:os.close(0),timeout=10) |
| 404 | return {'id':tool+'-closed-stdin','exit':r.returncode,'result':'PASS' if r.returncode==77 and not r.stdout and r.stderr==msg else 'FAIL'} |
| 405 | ctl+=[closed('zig-import',b'ZIG_IMPORT_IO\n'),closed('zig-export',b'ZIG_EXPORT_IO\n')] |
| 406 | for tool in (IMPORT,EXPORT): |
| 407 | r=py(tool,base,'unexpected');ctl.append({'id':tool.name+'-arguments-refused','exit':r.returncode,'result':'PASS' if r.returncode==64 and not r.stdout and b'BAD_COMMAND' in r.stderr else 'FAIL'}) |
| 408 | r=py(IMPORT,base);d=run([str(ROOT/'build/L740/zig-import')],base) |
| 409 | ctl.append({'id':'public-import-identical-to-native','result':'PASS' if r.returncode==0 and r.stdout==d.stdout else 'FAIL'}) |
| 410 | closure=['src/source-aware/vendor/sha256.om','src/source-aware/core-v2.om','src/adapters/zig-u64-import.om','src/adapters/zig-u64-export.om','build/L740/build.json','build/L740/zig-import','build/L740/zig-export'] |
| 411 | for tool,victims in ((IMPORT,['src/source-aware/vendor/sha256.om','src/adapters/zig-u64-import.om','build/L740/zig-import']), |
| 412 | (EXPORT,['src/source-aware/core-v2.om','src/adapters/zig-u64-export.om','build/L740/zig-export'])): |
| 413 | for victim in victims: |
| 414 | with tempfile.TemporaryDirectory(prefix='closed-build-',dir=out) as td: |
| 415 | t=Path(td) |
| 416 | for rel in ['tools/adapters/'+tool.name]+closure: |
| 417 | p=t/rel;p.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(ROOT/rel,p);p.chmod(0o700) |
| 418 | with (t/victim).open('ab') as f:f.write(b'changed') |
| 419 | r=run([sys.executable,str(t/'tools/adapters'/tool.name)],base) |
| 420 | ok=r.returncode==78 and not r.stdout and b'STALE_OR_MISSING_BUILD' in r.stderr |
| 421 | ctl.append({'id':tool.name+'-stale-'+victim,'exit':r.returncode,'result':'PASS' if ok else 'FAIL'}) |
| 422 | failures+=[c for c in ctl if c['result']=='FAIL' and c not in failures] |
| 423 | |
| 424 | # ---- exporter refusals ---- |
| 425 | good=zimport(base).stdout |
| 426 | U=65535 |
| 427 | def unit(member,ops,typ=1,ver=None,lang=None,prof=None,runtime=0): |
| 428 | v,l,p,_=MEMBERS[member] |
| 429 | v=v if ver is None else ver;l=l if lang is None else lang;p=p if prof is None else prof |
| 430 | sem=b'OMSA'+bytes([v,l,p,1,runtime,1])+struct.pack('<H',len(ops))+CONTRACT |
| 431 | for op,attr,eff,alias,obl,x,y,imm in ops:sem+=struct.pack('<8BHHQ',l,1,op,typ,attr,eff,alias,obl,x,y,imm) |
| 432 | return semonly(sem) |
| 433 | def shared(k): # t_j = add(t_{j-1}, t_{j-1}): tree size 2^k |
| 434 | return unit('Zig',[(9,0,0,0,1,U,U,0)]+[(2,1,0,0,1,j,j,0) for j in range(k)]) |
| 435 | def rnest(k): # x0 +% (x0 +% (...)): parenthesis depth k-1 |
| 436 | return [(9,0,0,0,1,U,U,0)]+[(2,1,0,0,1,0,j,0) for j in range(k)] |
| 437 | def asdeep(k): # x0 +% (x0 +% (... (@as(u64, 5) +% 6))): k parenthesised levels around the @as leaf |
| 438 | ops=[(9,0,0,0,1,U,U,0),(1,1,0,0,0,U,U,5),(1,1,0,0,0,U,U,6),(2,1,0,0,1,1,2,0)] |
| 439 | for _ in range(k-1):ops.append((2,1,0,0,1,0,len(ops)-1,0)) |
| 440 | return ops |
| 441 | flipped=bytearray(good);flipped[-3]^=1 |
| 442 | xr=[('truncated',good[:-1],65),('bad-magic',b'X'+good[1:],65),('sidecar-source-mismatch',bytes(flipped),65),('oversize',good+b'\0'*(8193-len(good)),65), |
| 443 | ('semantic-version-3',bytes(good[:17])+b'\x03'+good[18:],65),('version-1-profile-8',unit('Zig',[(9,0,0,0,1,U,U,0)],ver=1),68), |
| 444 | ('version-2-profile-1',unit('C',[(9,0,0,0,1,U,U,0)],ver=2),68), |
| 445 | ('profile3-bigint',unit('Python',[(9,0,0,0,1,U,U,0),(9,0,0,0,1,U,U,1),(2,2,20,255,8,0,1,0)],typ=2,prof=3,runtime=1),68), |
| 446 | ('zig-div-op5',unit('Zig',[(9,0,0,0,1,U,U,0),(9,0,0,0,1,U,U,1),(5,1,0,0,3,0,1,0)]),68), |
| 447 | ('c-div-op5',unit('C',[(9,0,0,0,1,U,U,0),(9,0,0,0,1,U,U,1),(5,1,0,0,3,0,1,0)]),68), |
| 448 | ('slot-gap',unit('Zig',[(9,0,0,0,1,U,U,1)]),68),('language-profile-mismatch',bytes(good[:18])+b'\x05'+good[19:],68), |
| 449 | ('shared-ops-over-capacity',shared(6),67),('depth-over-limit',unit('Zig',rnest(18)),67),('as-depth-over-limit',unit('Zig',asdeep(17)),67), |
| 450 | ('size-over-limit',shared(9),67)] |
| 451 | xrows=[] |
| 452 | for name,env,want in xr: |
| 453 | it={'id':'export '+name,'want':want} |
| 454 | if name in ('profile3-bigint','c-div-op5'):it['v1_codec_accepts']=sa1('decode',env).returncode==0 |
| 455 | if name=='zig-div-op5':it['v2_codec_accepts']=(sa2('decode',env).returncode==0) if v2_state=='RUN' else 'NOT_RUN' |
| 456 | r=zexport(env);ok=r.returncode==want and not r.stdout and r.stderr.startswith(b'ZIG_EXPORT_') and it.get('v1_codec_accepts',True) is not False and it.get('v2_codec_accepts',True) is not False |
| 457 | it.update(exit=r.returncode,stderr=r.stderr.decode(errors='replace').strip(),result='PASS' if ok else 'FAIL') |
| 458 | if not ok:failures.append(it) |
| 459 | xrows.append(it) |
| 460 | # Accepted exporter boundaries: shared SSA expanded to exactly 64 re-import operations; depth exactly 16. |
| 461 | exact=[(9,0,0,0,1,U,U,0)]+[(2,1,0,0,1,j,j,0) for j in range(5)]+[(2,1,0,0,1,5,4,0),(2,1,0,0,1,6,3,0),(2,1,0,0,1,7,2,0),(2,1,0,0,1,8,1,0)] |
| 462 | for name,env,count in (('shared-ops-at-capacity',unit('Zig',exact),64),('depth-at-limit',unit('Zig',rnest(17)),20),('as-depth-at-limit',unit('Zig',asdeep(16)),21)): |
| 463 | def body(it,name=name,env=env,count=count): |
| 464 | sem,_=split(env);ops=records(sem);r=zexport(env);check(r.returncode==0,name+' refused rc=%d'%r.returncode) |
| 465 | q=zimport(r.stdout);check(q.returncode==0,name+' re-import refused');_,_,ops2=decode(q.stdout,'Zig') |
| 466 | check(len(ops2)==count,name+' re-import operation count %d'%len(ops2)) |
| 467 | vec=vectors(1,rng);ref=[evaluate(ops,v) for v in vec] |
| 468 | check([evaluate(ops2,v) for v in vec]==ref,name+' evaluation');Z.add('export '+name,r.stdout,'calc',vec,ref) |
| 469 | it.update(reimport_ops=len(ops2),identity_equal=N(strip(split(q.stdout)[0]))==N(strip(sem))) |
| 470 | xrows.append(row('export '+name,body)) |
| 471 | |
| 472 | # ---- composition C -> Zig: F1 positives and the four accepted C import boundary controls ---- |
| 473 | ch=b'#include <stdint.h>\nuint64_t calc(uint64_t a,uint64_t b){return a+b;}' |
| 474 | cctl=[('C-exact-source-capacity',ch+b' '*(4096-len(ch)),'calc',2),('C-comment-at-capacity',ch+b'//'+b'x'*(4096-len(ch)-2),'calc',2), |
| 475 | ('C-operation-capacity',b'#include <stdint.h>\nuint64_t calc(uint64_t a,uint64_t b){return '+b'+'.join([b'a']*61)+b';}','calc',2), |
| 476 | ('C-nesting-limit',b'#include <stdint.h>\nuint64_t calc(uint64_t a,uint64_t b){return '+b'('*16+b'a'+b')'*16+b';}','calc',2)] |
| 477 | comp=[] |
| 478 | for tag,csrc,name,nargs in [(p['id'],p['source'].encode(),p['name'],p['inputs']) for p in f1['positives']]+cctl: |
| 479 | def body(it,tag=tag,csrc=csrc,name=name,nargs=nargs): |
| 480 | c=run([str(cimp)],csrc);bump('c_import_runs');check(c.returncode==0,'C import refused') |
| 481 | sem_a,_,ops_a=decode(c.stdout,'C') |
| 482 | src_b=export_checks(sem_a,c.stdout,tag) |
| 483 | sem_b,ops_b=reimport_identity(sem_a,src_b,tag) |
| 484 | vec=vectors(nargs,rng);ref=[evaluate(ops_a,v) for v in vec] |
| 485 | check(C.values(csrc,name,vec)==ref,'cc(original C) != reference(U_A)') |
| 486 | check([evaluate(ops_b,v) for v in vec]==ref,'reference(U_B) != reference(U_A)') |
| 487 | Z.add('C->Zig '+tag,src_b,'calc',vec,ref) |
| 488 | it.update(identity=identity(N(strip(sem_a))),vectors=len(vec),native_realization=native(sem_a,nargs,vec,ref)) |
| 489 | comp.append(row('C->Zig '+tag,body)) |
| 490 | |
| 491 | # ---- composition Zig -> C: export_C(R(U_A, C)), then C import ---- |
| 492 | zc=[];zig_to_c='RUN' if cexp.is_file() else 'NOT_RUN' |
| 493 | if zig_to_c=='RUN': |
| 494 | for fx in f2['positives']: |
| 495 | def body(it,fx=fx): |
| 496 | src=fx['source'].encode();r=zimport(src);sem_a,_,ops_a=decode(r.stdout,'Zig') |
| 497 | q=py(cexp,R(r.stdout,'C'));bump('c_export_runs');check(q.returncode==0,'c-export refused R(U,C) rc=%d %s'%(q.returncode,q.stderr)) |
| 498 | c=run([str(cimp)],q.stdout);bump('c_import_runs');check(c.returncode==0,'C import of exported C refused') |
| 499 | sem_b,_,ops_b=decode(c.stdout,'C');check(N(strip(sem_b))==N(strip(sem_a)),'identity N(strip(U_B)) != N(strip(U_A))') |
| 500 | vec=vectors(fx['inputs'],rng);ref=[evaluate(ops_a,v) for v in vec] |
| 501 | check(C.values(q.stdout,'calc',vec)==ref,'cc(src_B) != reference(U_A)') |
| 502 | check([evaluate(ops_b,v) for v in vec]==ref,'reference(U_B) != reference(U_A)') |
| 503 | Z.add('Zig->C '+fx['id'],src,fx['name'],vec,ref) |
| 504 | it.update(vectors=len(vec),exported_c=q.stdout.decode(),native_realization=native(sem_a,fx['inputs'],vec,ref)) |
| 505 | zc.append(row('Zig->C '+fx['id'],body)) |
| 506 | |
| 507 | # ---- deferred Zig oracle: one harness per build mode over every requested program ---- |
| 508 | zfail=Z.evaluate_all() |
| 509 | for tag,msg in zfail.items(): |
| 510 | item=rows_by_tag.get(tag) |
| 511 | if item is None:failures.append({'id':tag,'result':'FAIL','failure':msg});continue |
| 512 | if item['result']=='PASS':item.update(result='FAIL',failure=msg);failures.append(item) |
| 513 | for item in rows_by_tag.values(): |
| 514 | if item['result']=='PASS':item['zig_modes']=list(ZIG_MODES) |
| 515 | |
| 516 | zv=run([a.zig,'version'],None).stdout.decode().strip() |
| 517 | report={'schema':'omega.zig-u64.selftest.v1','result':'FAIL' if failures else 'PASS','status_flags':'TESTED (author self-test), not QUALIFIED', |
| 518 | 'evidence':'REFERENCE + DIFFERENTIAL (Zig/cc/native NATIVE AArch64); no PROOF','source_commit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip(), |
| 519 | 'build':json.loads((ROOT/'build/L740/build.json').read_text()),'zig':{'version':zv,'sha256':hashlib.sha256(Path(a.zig).read_bytes()).hexdigest(),'modes':list(ZIG_MODES)}, |
| 520 | 'cc':run([a.cc,'--version'],None).stdout.decode().split('\n')[0],'oracle_control':oracle_control, |
| 521 | 'c_import_sha256':hashlib.sha256(cimp.read_bytes()).hexdigest(),'sa_v1_binary_sha256':hashlib.sha256((ROOT/'build/L574/sa').read_bytes()).hexdigest(), |
| 522 | 'sa_v2':v2_state if v2_state=='NOT_RUN' else {'root':str(v2root),'binary_sha256':hashlib.sha256((v2root/'build/L832/sa').read_bytes()).hexdigest()}, |
| 523 | 'c_export':str(cexp) if zig_to_c=='RUN' else 'NOT_RUN','native_realization':NAT.state if NAT.state=='RUN' else 'NOT_RUN ('+NAT.reason+')', |
| 524 | 'retarget':{'tool':str(rtool),'sha256':hashlib.sha256((rtool.parent.parent.parent/'build/L833/retarget').read_bytes()).hexdigest(),'cross_check':'every tool output equals the test-code R'} if rtool else 'R applied in test code (tools/adapters/retarget not given)', |
| 525 | 'positives':len(rows),'positives_passed':sum(r['result']=='PASS' for r in rows),'not_in_profile':len(f2['not_in_profile']), |
| 526 | 'refusals':len(refusals),'refusals_passed':sum(r['result']=='PASS' for r in refusals), |
| 527 | 'controls':len(ctl),'controls_passed':sum(r['result']=='PASS' for r in ctl),'export_cases':len(xrows),'export_cases_passed':sum(r['result']=='PASS' for r in xrows), |
| 528 | 'c_to_zig':len(comp),'c_to_zig_passed':sum(r['result']=='PASS' for r in comp),'zig_to_c':zig_to_c,'zig_to_c_cases':len(zc),'zig_to_c_passed':sum(r['result']=='PASS' for r in zc), |
| 529 | 'zig_compiles':Z.compiles,'zig_observations':Z.observations,'cc_compiles':C.compiles,'cc_observations':C.observations,'native_calls':NAT.calls, |
| 530 | 'counts':counts,'cases':rows,'refusal_cases':refusals,'control_cases':ctl,'export_rows':xrows,'c_to_zig_cases':comp,'zig_to_c_rows':zc,'failures':failures} |
| 531 | (out/'result.json').write_text(json.dumps(report,indent=1,ensure_ascii=False)+'\n') |
| 532 | keys=['positives','positives_passed','not_in_profile','refusals','refusals_passed','controls','controls_passed','export_cases','export_cases_passed', |
| 533 | 'c_to_zig','c_to_zig_passed','zig_to_c','zig_to_c_cases','zig_to_c_passed','zig_compiles','zig_observations','cc_observations','native_calls'] |
| 534 | print(report['result'],' '.join('%s=%s'%(k,report[k]) for k in keys),'sa_v2=%s'%('RUN' if v2_state=='RUN' else 'NOT_RUN'), |
| 535 | 'retarget=%s'%('TOOL' if rtool else 'TEST_CODE'),'native=%s'%NAT.state,'oracle_control=%s'%json.dumps(oracle_control),' '.join('%s=%s'%kv for kv in counts.items())) |
| 536 | for f in failures[:20]:print('FAIL',json.dumps(f,ensure_ascii=False)[:600]) |
| 537 | return 1 if failures else 0 |
| 538 | |
| 539 | if __name__=='__main__':raise SystemExit(main()) |