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 / go_selftest.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Go lane (#741) author self-test: TESTED evidence only (translation-v1 section 10), never QUALIFIED. |
| 3 | |
| 4 | For every F2-go fixture: Go import, independent decode, #621 v2 codec `sa identity|decode|replay` |
| 5 | (build/L832, or NOT_RUN), cross-importer identity against the C import of the F1 source, export of the |
| 6 | unit and of R(U, M) for all six family members (identical bytes, gofmt-clean), re-import identity |
| 7 | (translation-compose-v1 section 4.1), and Go 1.27.3 DIFFERENTIAL (original and exported Go) against a |
| 8 | bigint evaluation of the records. The untyped-constant rule of go-u64-v1.md section 1.1 is checked |
| 9 | against `go build` on the refusal fixtures and on seeded random constant/variable trees. Compositions |
| 10 | C->Go and Go->C (R(U, M) in test code, or tools/adapters/retarget via --retarget, cross-checked byte for |
| 11 | byte; the G1 C exporter accepts v1 C units only), with the native realization lower(N(U_A)) when the lowering, omc 734f0a39 and the |
| 12 | bridge are present (otherwise NOT_RUN). |
| 13 | """ |
| 14 | from pathlib import Path |
| 15 | import argparse,hashlib,json,os,random,shutil,struct,subprocess,sys,tempfile |
| 16 | ROOT=Path(__file__).resolve().parents[3] |
| 17 | MASK=(1<<64)-1 |
| 18 | SEMDOM=b'omega.source.semantic.v1' |
| 19 | CONTRACT=hashlib.sha256((ROOT/'spec/universal/semantics.md').read_bytes()).digest() |
| 20 | # translation-compose-v2 section 1: OMSA version, language, profile, arithmetic obligations (dialect = language) |
| 21 | MEMBERS={'C':(1,1,1,1),'Rust':(1,2,2,1),'Python':(1,3,4,5),'C++':(2,5,7,1),'Zig':(2,6,8,1),'Go':(2,7,9,1)} |
| 22 | BOUNDARY=[0,1,2,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK] |
| 23 | IMPORT=ROOT/'tools/adapters/go-import';EXPORT=ROOT/'tools/adapters/go-export' |
| 24 | OMC_PIN='734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61' |
| 25 | BRIDGE_COMMIT='012860dbf26ee62a9838594b9dfd1e3e94a540a9' |
| 26 | NATIVE_OM_PIN='2c2c53f61d4ab302f1a2092c3c32189335dd53f6cf2b388f47a475f99f2c3940' |
| 27 | H=b'package main\n\n' |
| 28 | |
| 29 | class Fail(Exception):pass |
| 30 | def check(c,msg): |
| 31 | if not c:raise Fail(msg) |
| 32 | |
| 33 | def run(cmd,data,cwd=None,timeout=60,env=None): |
| 34 | return subprocess.run(cmd,input=data,capture_output=True,timeout=timeout,cwd=cwd,env=env) |
| 35 | |
| 36 | def py(tool,data):return run([sys.executable,str(tool)],data) |
| 37 | |
| 38 | # ---- independent envelope model (not the #621 core) ---- |
| 39 | def split(env): |
| 40 | check(len(env)>=13 and env[:5]==b'OMSB\x01','bad envelope magic') |
| 41 | ns,np_=struct.unpack_from('<II',env,5);check(len(env)==13+ns+np_,'bad envelope length') |
| 42 | return env[13:13+ns],env[13+ns:] |
| 43 | |
| 44 | def ops_of(sem): |
| 45 | count=struct.unpack_from('<H',sem,10)[0];check(len(sem)==44+20*count,'bad semantic length') |
| 46 | return [struct.unpack_from('<8BHHQ',sem,44+20*i) for i in range(count)] |
| 47 | |
| 48 | def decode(env,member): |
| 49 | ver,lang,prof,arob=MEMBERS[member] |
| 50 | sem,side=split(env) |
| 51 | 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) |
| 52 | check(sem[12:44]==CONTRACT,'wrong parent semantics hash') |
| 53 | ops=[];slots=[] |
| 54 | for i,(d,v,op,t,attr,eff,alias,obl,a,b,imm) in enumerate(ops_of(sem)): |
| 55 | check(d==lang and v==1 and t==1 and eff==0 and alias==0,'op %d fields'%i) |
| 56 | if op==9:check(attr==0 and obl==1 and a==b==65535,'input op');slots.append(imm) |
| 57 | elif op==1:check(attr==1 and obl==0 and a==b==65535,'const op') |
| 58 | 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) |
| 59 | ops.append((op,a,b,imm)) |
| 60 | check(sorted(slots)==list(range(len(slots))),'input slots not a permutation') |
| 61 | return sem,side,ops |
| 62 | |
| 63 | def sidecar(sem,side,src,count): |
| 64 | check(side[:6]==b'OMSP\x01\x01','sidecar must be v1 encoding 1 (strict UTF-8)') |
| 65 | 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') |
| 66 | check(len(side)==74+8*count+len(src) and side[74+8*count:]==src,'sidecar source mismatch') |
| 67 | return [struct.unpack_from('<II',side,74+8*i) for i in range(count)] |
| 68 | |
| 69 | def evaluate(ops,args): |
| 70 | vals=[] |
| 71 | for op,a,b,imm in ops: |
| 72 | 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] |
| 73 | vals.append(v&MASK) |
| 74 | return vals[-1] |
| 75 | |
| 76 | def normalized(ops): |
| 77 | n=len(ops) |
| 78 | 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 |
| 79 | |
| 80 | def retarget(sem,member): |
| 81 | """R(U, M), translation-compose-v2 section 2 (semantic bytes; callers wrap them semantic-only).""" |
| 82 | ver,lang,prof,arob=MEMBERS[member];b=bytearray(sem);b[4]=ver;b[5]=lang;b[6]=prof |
| 83 | for i,(_,_,op,*_) in enumerate(ops_of(sem)): |
| 84 | b[44+20*i]=lang |
| 85 | if op in (2,3,4):b[44+20*i+7]=arob |
| 86 | return bytes(b) |
| 87 | |
| 88 | def N(sem):return retarget(sem,'C') |
| 89 | |
| 90 | def strip(sem): |
| 91 | ops=ops_of(sem) |
| 92 | if not normalized([(o[2],o[8],o[9],o[10]) for o in ops]):return sem |
| 93 | n=len(ops)-2;b=bytearray(sem[:44+20*n]);struct.pack_into('<H',b,10,n);return bytes(b) |
| 94 | |
| 95 | def semonly(sem):return b'OMSB\x01'+struct.pack('<II',len(sem),0)+sem |
| 96 | def identity(sem):return hashlib.sha256(SEMDOM+sem).hexdigest() |
| 97 | |
| 98 | # ---- oracles ---- |
| 99 | GO_HARNESS='''package main |
| 100 | |
| 101 | import ( |
| 102 | "bufio" |
| 103 | "fmt" |
| 104 | "os" |
| 105 | "strconv" |
| 106 | "strings" |
| 107 | ) |
| 108 | |
| 109 | func main() { |
| 110 | sc := bufio.NewScanner(os.Stdin) |
| 111 | for sc.Scan() { |
| 112 | f := strings.Fields(sc.Text()) |
| 113 | if len(f) != %d { |
| 114 | panic("arity") |
| 115 | } |
| 116 | v := make([]uint64, 6) |
| 117 | for i, s := range f { |
| 118 | x, err := strconv.ParseUint(s, 10, 64) |
| 119 | if err != nil { |
| 120 | panic(err) |
| 121 | } |
| 122 | v[i] = x |
| 123 | } |
| 124 | _ = v |
| 125 | fmt.Println(%s) |
| 126 | } |
| 127 | } |
| 128 | ''' |
| 129 | |
| 130 | class Oracles: |
| 131 | def __init__(s,out,go,gofmt,cc): |
| 132 | s.out=out;s.go=go;s.gofmt=gofmt;s.cc=cc;s.cache={};s.compiles=0;s.go_builds=0;s.gofmt_runs=0 |
| 133 | s.env=dict(os.environ,GOTOOLCHAIN='local',GOFLAGS='-mod=mod',GOPROXY='off',GOWORK='off',CGO_ENABLED='0', |
| 134 | GOCACHE=str(out/'gocache'),GOPATH=str(out/'gopath'),GOTELEMETRY='off') |
| 135 | def gomodule(s,text,harness): |
| 136 | d=Path(tempfile.mkdtemp(prefix='go-',dir=s.out/'oracle')) |
| 137 | (d/'go.mod').write_text('module oracle\n\ngo 1.27\n');(d/'unit.go').write_bytes(text);(d/'zz_oracle.go').write_text(harness) |
| 138 | return d |
| 139 | def gobuild(s,text,harness): |
| 140 | (s.out/'oracle').mkdir(exist_ok=True);d=s.gomodule(text,harness) |
| 141 | r=run(['nice','-n','19',s.go,'build','-trimpath','-o',str(d/'calc'),'.'],None,cwd=d,timeout=300,env=s.env);s.go_builds+=1 |
| 142 | return r,d/'calc' |
| 143 | def gobare(s,text): |
| 144 | """go build of the unit with a harness that only declares func main: True iff Go accepts the file.""" |
| 145 | r,_=s.gobuild(text,'package main\n\nfunc main() {}\n');return r.returncode==0,r.stderr.decode(errors='replace').strip() |
| 146 | def build(s,kind,text,name,nargs): |
| 147 | key=hashlib.sha256(kind.encode()+b'\0'+name.encode()+b'\0'+text+b'\0%d'%nargs).hexdigest() |
| 148 | if key in s.cache:return s.cache[key] |
| 149 | if kind=='go': |
| 150 | r,exe=s.gobuild(text,GO_HARNESS%(nargs,name+'('+', '.join('v[%d]'%j for j in range(nargs))+')')) |
| 151 | check(r.returncode==0,'go oracle build failed: '+r.stderr.decode(errors='replace')[-800:]) |
| 152 | else: |
| 153 | d=s.out/'oracle';d.mkdir(exist_ok=True);exe=d/key[:24];f=d/(key[:24]+'.c') |
| 154 | body=('uint64_t x[6]={0};while(scanf("'+' '.join(['%" SCNu64 "']*nargs)+'",'+','.join('&x[%d]'%j for j in range(nargs))+')==%d)'%nargs+ |
| 155 | 'printf("%" PRIu64 "\\n",'+name+'('+','.join('x[%d]'%j for j in range(nargs))+'));') if nargs else 'printf("%" PRIu64 "\\n",'+name+'());' |
| 156 | f.write_bytes(text+('\n#include <stdio.h>\n#include <inttypes.h>\nint main(void){'+body+'return 0;}\n').encode()) |
| 157 | r=run(['nice','-n','19',s.cc,'-std=c17','-O2','-Wall','-Wextra','-Werror','-Wno-unused-parameter',str(f),'-o',str(exe)],None,timeout=180) |
| 158 | check(r.returncode==0,'cc oracle compile failed: '+r.stderr.decode(errors='replace')[-800:]) |
| 159 | s.compiles+=1;s.cache[key]=exe;return exe |
| 160 | def values(s,kind,text,name,vectors): |
| 161 | nargs=len(vectors[0]);exe=s.build(kind,text,name,nargs) |
| 162 | r=run([str(exe)],''.join(' '.join(map(str,v))+'\n' for v in vectors).encode(),timeout=60) |
| 163 | check(r.returncode==0,kind+' oracle run failed: '+r.stderr.decode(errors='replace')[-400:]) |
| 164 | return [int(x) for x in r.stdout.split()] |
| 165 | def gofmt_clean(s,text): |
| 166 | r=run([s.gofmt],text);s.gofmt_runs+=1 |
| 167 | return r.returncode==0 and r.stdout==text |
| 168 | |
| 169 | class Native: |
| 170 | """lower(N(U)) -> omc 734f0a39 function mode -> bridge native.om binding -> C caller (translation-v1 section 5).""" |
| 171 | def __init__(s,out,lower,omc,bridge,cc): |
| 172 | s.out=out/'native';s.out.mkdir();s.lower=lower;s.omc=omc;s.cc=cc;s.cache={};s.calls=0 |
| 173 | check(hashlib.sha256(Path(omc).read_bytes()).hexdigest()==OMC_PIN,'omc sha256 pin') |
| 174 | src=subprocess.run(['git','-C',bridge,'show',f'{BRIDGE_COMMIT}:src/native.om'],capture_output=True,check=True).stdout |
| 175 | check(hashlib.sha256(src).hexdigest()==NATIVE_OM_PIN,'bridge native.om sha256 pin') |
| 176 | r=run([omc],src);check(r.returncode==0,'bridge native.om compile') |
| 177 | s.gen=s.out/'native-gen';s.gen.write_bytes(r.stdout);s.gen.chmod(0o700) |
| 178 | def values(s,nsem,vectors): |
| 179 | key=identity(nsem);nargs=len(vectors[0]) |
| 180 | if key not in s.cache: |
| 181 | d=s.out/key[:24];d.mkdir() |
| 182 | r=py(s.lower,semonly(nsem));check(r.returncode==0,'lower refused N(U) rc=%d %s'%(r.returncode,r.stderr)) |
| 183 | unit=r.stdout;(d/'unit.om').write_bytes(unit) |
| 184 | c=run([s.omc],unit);check(c.returncode==0 and c.stdout,'omc function-mode compile failed') |
| 185 | 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') |
| 186 | params=''.join(', uint64_t i%d'%i for i in range(nargs));args=''.join(', a[%d]'%i for i in range(nargs)) |
| 187 | caller=('#include <inttypes.h>\n#include <stdio.h>\n#include <stdlib.h>\nuint32_t omega_calc(uint64_t *result%s);\n' |
| 188 | 'int main(void){char line[512];while(fgets(line,sizeof line,stdin)){char *p=line;uint64_t a[6]={0};' |
| 189 | 'for(int i=0;i<%d;i++)a[i]=strtoull(p,&p,10);(void)a;(void)p;uint64_t r=UINT64_C(6148914691236517205);' |
| 190 | 'uint32_t st=omega_calc(&r%s);printf("%%" PRIu32 " %%" PRIu64 "\\n",st,r);}return 0;}\n')%(params,nargs,args) |
| 191 | (d/'omega_native.c').write_bytes(b.stdout);(d/'caller.c').write_text(caller) |
| 192 | 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) |
| 193 | check(k.returncode==0,'native caller compile: '+k.stderr.decode(errors='replace')[-400:]) |
| 194 | s.cache[key]=d/'caller' |
| 195 | r=run([str(s.cache[key])],''.join(' '.join(map(str,v))+'\n' for v in vectors).encode()) |
| 196 | lines=r.stdout.decode().split('\n')[:-1];check(r.returncode==0 and len(lines)==len(vectors),'native caller run') |
| 197 | out=[] |
| 198 | for line in lines: |
| 199 | st,val=line.split();check(st=='0','native status '+st);out.append(int(val)) |
| 200 | s.calls+=len(lines);return out |
| 201 | |
| 202 | def vectors(nargs,rng): |
| 203 | if nargs==0:return [()] |
| 204 | if nargs<=2:base=[(x,) for x in BOUNDARY] if nargs==1 else [(x,y) for x in BOUNDARY for y in BOUNDARY] |
| 205 | else:base=[tuple(BOUNDARY[(j+k)%len(BOUNDARY)] for k in range(nargs)) for j in range(len(BOUNDARY))] |
| 206 | return base+[tuple(rng.getrandbits(64) for _ in range(nargs)) for _ in range(32)] |
| 207 | |
| 208 | # ---- random constant/variable trees for the untyped-constant rule ---- |
| 209 | CONSTS=[0,1,2,3,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK] |
| 210 | def rtree(rng,d): |
| 211 | if d==0 or rng.random()<0.3: |
| 212 | return ('v',rng.randrange(2)) if rng.random()<0.35 else ('c',rng.choice(CONSTS)) |
| 213 | return (rng.choice('+-*'),rtree(rng,d-1),rtree(rng,d-1)) |
| 214 | def isconst(t):return t[0]=='c' or (t[0] in '+-*' and isconst(t[1]) and isconst(t[2])) |
| 215 | def exact(t): |
| 216 | if t[0]=='c':return t[1] |
| 217 | a,b=exact(t[1]),exact(t[2]);return a+b if t[0]=='+' else a-b if t[0]=='-' else a*b |
| 218 | def profile_ok(t): |
| 219 | """go-u64-v1 section 1.1: every constant-only node of the tree evaluates exactly within 0..2^64-1.""" |
| 220 | if t[0]=='v':return True |
| 221 | if t[0]=='c':return 0<=t[1]<=MASK |
| 222 | return profile_ok(t[1]) and profile_ok(t[2]) and (not isconst(t) or 0<=exact(t)<=MASK) |
| 223 | def bigconst(t): |
| 224 | """types2 rejects any untyped integer constant operation result wider than 512 bits (constant overflow).""" |
| 225 | if t[0]!='c' and isconst(t):return abs(exact(t)).bit_length()>512 or bigconst(t[1]) or bigconst(t[2]) |
| 226 | return False |
| 227 | def go_ok(t): |
| 228 | """The Go rule: every maximal constant expression (operand of a uint64 operation, or the returned value) |
| 229 | is exact and must be representable as uint64; intermediate constant values are unbounded up to 512 bits.""" |
| 230 | if t[0]=='v':return True |
| 231 | if isconst(t):return 0<=exact(t)<=MASK and not bigconst(t) |
| 232 | return go_ok(t[1]) and go_ok(t[2]) |
| 233 | PREC={'+':4,'-':4,'*':5} |
| 234 | def text(t,lang,parent=None,side=None): |
| 235 | if t[0]=='v':return 'ab'[t[1]] |
| 236 | if t[0]=='c':return str(t[1])+('ULL' if lang=='c' else '') |
| 237 | p=PREC[t[0]];s=text(t[1],lang,p,'l')+' '+t[0]+' '+text(t[2],lang,p,'r') |
| 238 | if parent is not None and (p<parent or (side=='r' and p<=parent)):s='('+s+')' |
| 239 | return s |
| 240 | def tval(t,args): |
| 241 | if t[0]=='v':return args[t[1]] |
| 242 | if t[0]=='c':return t[1] |
| 243 | a,b=tval(t[1],args),tval(t[2],args);return (a+b if t[0]=='+' else a-b if t[0]=='-' else a*b)&MASK |
| 244 | |
| 245 | def main(): |
| 246 | ap=argparse.ArgumentParser() |
| 247 | ap.add_argument('--out',required=True) |
| 248 | ap.add_argument('--c-import',default=str(ROOT/'build/L589/c-import'),help='native #622 C importer (mk/c-u64-import.mk)') |
| 249 | ap.add_argument('--sa1-root',default=str(ROOT),help='checkout holding tools/source-aware/sa and build/L574/sa (#621 v1 codec)') |
| 250 | ap.add_argument('--sa2-root',default=str(ROOT),help='checkout holding tools/source-aware/sa and build/L832/sa (#621 v2 codec)') |
| 251 | ap.add_argument('--c-export',default=str(ROOT/'tools/adapters/c-export'),help='public #622 c-export (mk/c-u64-export.mk)') |
| 252 | rdef=ROOT/'tools/adapters/retarget' |
| 253 | ap.add_argument('--retarget',default=str(rdef) if rdef.is_file() else '',help='public #624 tools/adapters/retarget (mk/retarget.mk), cross-checked against the test-code R; in-tree if present') |
| 254 | ap.add_argument('--lower',default=str(ROOT/'tools/adapters/lower')) |
| 255 | omc=os.environ.get('OMEGA_NATIVE_OMC');bridge=os.environ.get('OMEGA_BRIDGE_REPO') |
| 256 | ap.add_argument('--omc',default=omc,required=not omc,help='native omc 734f0a39 (default $OMEGA_NATIVE_OMC)') |
| 257 | ap.add_argument('--bridge',default=bridge,required=not bridge,help='omega-bridge checkout holding 012860db (default $OMEGA_BRIDGE_REPO)') |
| 258 | ap.add_argument('--go',default=os.environ.get('GO') or shutil.which('go'),help='Go 1.27.3 (default $GO, then PATH)') |
| 259 | ap.add_argument('--gofmt',default=os.environ.get('GOFMT') or shutil.which('gofmt'),help='gofmt of the same toolchain (default $GOFMT, then PATH)') |
| 260 | ap.add_argument('--cc',default=os.environ.get('CC','cc')) |
| 261 | ap.add_argument('--random-trees',type=int,default=160) |
| 262 | a=ap.parse_args() |
| 263 | missing=[n for n,p in (('go',a.go),('gofmt',a.gofmt)) if not p or not Path(p).is_file()] |
| 264 | if missing: |
| 265 | print('NOT_RUN Go oracle missing: %s (set $GO/$GOFMT or put them on PATH)'%' '.join(missing));return 3 |
| 266 | out=Path(a.out).resolve();out.mkdir(parents=True,exist_ok=False) |
| 267 | cimp=Path(a.c_import);sa1root=Path(a.sa1_root);sa1=sa1root/'build/L574/sa';sa2root=Path(a.sa2_root) |
| 268 | O=Oracles(out,a.go,a.gofmt,a.cc);rng=random.Random(741);failures=[];counts={} |
| 269 | def bump(k,n=1):counts[k]=counts.get(k,0)+n |
| 270 | have_sa2=(sa2root/'build/L832/sa').is_file() and (sa2root/'tools/source-aware/sa').is_file() |
| 271 | codec_v2='RUN' if have_sa2 else 'NOT_RUN (no build/L832/sa)' |
| 272 | def sa2(cmd,env): |
| 273 | r=run(['bash','tools/source-aware/sa',cmd],env,cwd=sa2root,env=dict(os.environ,SA_BUILD='build/L832'));bump('sa2_requests');return r |
| 274 | def sa1run(cmd,env): |
| 275 | e=dict(os.environ);e.pop('SA_BUILD',None) |
| 276 | r=run(['bash','tools/source-aware/sa',cmd],env,cwd=sa1root,env=e);bump('sa1_requests');return r |
| 277 | def gimport(src): |
| 278 | r=py(IMPORT,src);bump('go_import_runs');return r |
| 279 | def gexport(env): |
| 280 | r=py(EXPORT,env);bump('go_export_runs');return r |
| 281 | try:native=Native(out,Path(a.lower),a.omc,a.bridge,a.cc);native_state='RUN' |
| 282 | except (Fail,subprocess.CalledProcessError,OSError) as e: |
| 283 | print('FAIL native realization setup (omc %s, bridge %s): %s'%(a.omc,a.bridge,e));return 1 |
| 284 | cexp=Path(a.c_export) if a.c_export and Path(a.c_export).is_file() else None |
| 285 | rtool=Path(a.retarget) if a.retarget and Path(a.retarget).is_file() else None |
| 286 | RNAME={'C':'c','Rust':'rust','Python':'python','C++':'cpp','Zig':'zig','Go':'go'} |
| 287 | def R(env,sem,m): |
| 288 | """R(U, M) semantic-only: tools/adapters/retarget when given (must equal the Python R), else the Python R.""" |
| 289 | want=semonly(retarget(sem,m)) |
| 290 | if rtool: |
| 291 | r=run([sys.executable,str(rtool),RNAME[m]],env);bump('retarget_runs') |
| 292 | check(r.returncode==0 and r.stdout==want,'retarget %s rc=%d differs from the Python R'%(RNAME[m],r.returncode)) |
| 293 | return want |
| 294 | |
| 295 | f1=json.loads((ROOT/'tests/universal/translation/fixtures-f1.json').read_text()) |
| 296 | f2=json.loads((ROOT/'tests/universal/translation/fixtures-f2-go.json').read_text()) |
| 297 | f1pos={p['id']:p for p in f1['positives']} |
| 298 | check(len(f2['positives'])+len(f2['not_in_profile'])==len(f1pos),'F2-go does not cover every F1 positive') |
| 299 | check({p['f1_id'] for p in f2['positives']}|{p['f1_id'] for p in f2['not_in_profile']}==set(f1pos),'F2-go F1 id set') |
| 300 | |
| 301 | def codec_checks(env,sem,src): |
| 302 | if not have_sa2:return |
| 303 | ident=sa2('identity',env);check(ident.returncode==0 and ident.stdout.hex()==identity(sem),'v2 sa identity refused or differs') |
| 304 | check(sa2('decode',env).stdout==env,'v2 sa decode changed unit');check(sa2('replay',env).stdout==src,'v2 sa replay differs from source') |
| 305 | r=sa1run('decode',env);check(r.returncode==66 and not r.stdout,'v1 codec must refuse a v2 unit with 66') |
| 306 | |
| 307 | def export_checks(sem,env_with_sidecar,tag): |
| 308 | """Exporter: identical bytes for every family member with or without sidecar, gofmt-clean; returns src_B.""" |
| 309 | r=gexport(env_with_sidecar);check(r.returncode==0 and r.stderr==b'',tag+' export refused rc=%d %s'%(r.returncode,r.stderr)) |
| 310 | text=r.stdout |
| 311 | for m in MEMBERS: |
| 312 | u=R(env_with_sidecar,sem,m) |
| 313 | if MEMBERS[m][0]==1:check(sa1run('decode',u).returncode==0,tag+' R(U,%s) not a valid v1 unit'%m) |
| 314 | elif have_sa2:check(sa2('decode',u).returncode==0,tag+' R(U,%s) not a valid v2 unit'%m) |
| 315 | q=gexport(u);check(q.returncode==0 and q.stdout==text,tag+' export differs for member '+m+' (semantic-only)') |
| 316 | bump('member_exports',len(MEMBERS)) |
| 317 | check(text.startswith(H+b'func calc(') and text.endswith(b'\n}\n') and text.count(b'\n')==5,tag+' export form') |
| 318 | check(O.gofmt_clean(text),tag+' export is not gofmt-clean') |
| 319 | return text |
| 320 | |
| 321 | def reimport_identity(sem_a,src_b,tag): |
| 322 | r=gimport(src_b);check(r.returncode==0,tag+' re-import refused rc=%d %s'%(r.returncode,r.stderr)) |
| 323 | sem_b,side_b,ops_b=decode(r.stdout,'Go');sidecar(sem_b,side_b,src_b,len(ops_b)) |
| 324 | check(N(strip(sem_b))==N(strip(sem_a)),tag+' identity N(strip(U_B)) != N(strip(U_A))') |
| 325 | return sem_b,ops_b |
| 326 | |
| 327 | def go_positive(tag,src,name,nargs,f1src=None,f1name=None): |
| 328 | item={'id':tag} |
| 329 | r=gimport(src);check(r.returncode==0 and r.stderr==b'','import refused rc=%d %s'%(r.returncode,r.stderr)) |
| 330 | env=r.stdout;sem,side,ops=decode(env,'Go');spans=sidecar(sem,side,src,len(ops)) |
| 331 | check(normalized(ops),'importer must append the normalization pair') |
| 332 | check(spans[-1]==spans[-2]==(0,0),'synthetic pair spans') |
| 333 | for (op,_,_,imm),(lo,hi) in zip(ops[:-2],spans[:-2]): |
| 334 | t=src[lo:hi] |
| 335 | if op==1:check(t==b'%d'%imm,'literal span') |
| 336 | elif op==9:check(len(t)>0 and t.isascii() and t.decode().isidentifier(),'input span') |
| 337 | else:check(t=={2:b'+',3:b'-',4:b'*'}[op],'operator span') |
| 338 | codec_checks(env,sem,src) |
| 339 | if f1src is not None: |
| 340 | c=run([str(cimp)],f1src);bump('c_import_runs');check(c.returncode==0,'C import of F1 refused') |
| 341 | csem,_,_=decode(c.stdout,'C');check(N(sem)==N(csem),'cross-importer identity: N(import_Go(F2)) != N(import_C(F1))') |
| 342 | exported=export_checks(sem,env,tag) |
| 343 | sem_b,_=reimport_identity(sem,exported,tag) |
| 344 | check(sem_b==sem,'same-language round trip changed the semantic bytes') |
| 345 | vec=vectors(nargs,rng);ref=[evaluate(ops,v) for v in vec] |
| 346 | check(O.values('go',src,name,vec)==ref,'go(original Go) != reference') |
| 347 | check(O.values('go',exported,'calc',vec)==ref,'go(exported Go) != reference') |
| 348 | bump('go_observations',2*len(vec)) |
| 349 | if f1src is not None:check(O.values('c',f1src,f1name,vec)==ref,'cc(F1 C) != reference');bump('cc_observations',len(vec)) |
| 350 | s2=strip(sem);q=gexport(semonly(s2));check(q.returncode==0,'export of stripped unit refused') |
| 351 | r2=gimport(q.stdout);check(r2.returncode==0,'re-import of stripped export refused') |
| 352 | _,_,ops2=decode(r2.stdout,'Go');sops=[(o[2],o[8],o[9],o[10]) for o in ops_of(s2)] |
| 353 | check([evaluate(ops2,v) for v in vec]==[evaluate(sops,v) for v in vec],'stripped round trip evaluation differs') |
| 354 | item.update(result='PASS',ops=len(ops),vectors=len(vec),semantic_identity=identity(sem),N_identity=identity(N(sem)),exported=exported.decode()) |
| 355 | return item |
| 356 | |
| 357 | rows=[] |
| 358 | for fx in f2['positives']: |
| 359 | try: |
| 360 | src=fx['source'].encode();check(hashlib.sha256(src).hexdigest()==fx['sha256'],'fixture sha') |
| 361 | p1=f1pos[fx['f1_id']];check(p1['sha256']==fx['f1_sha256'] and p1['inputs']==fx['inputs'] and p1['name']==fx['name'],'F1 link') |
| 362 | rows.append(go_positive(fx['id'],src,fx['name'],fx['inputs'],p1['source'].encode(),p1['name'])) |
| 363 | except (Fail,ValueError,KeyError,IndexError,struct.error,subprocess.TimeoutExpired) as e: |
| 364 | it={'id':fx['id'],'result':'FAIL','failure':str(e)};failures.append(it);rows.append(it) |
| 365 | extra_rows=[] |
| 366 | for fx in f2['extra_positives']: |
| 367 | try: |
| 368 | src=fx['source'].encode();check(hashlib.sha256(src).hexdigest()==fx['sha256'],'fixture sha') |
| 369 | extra_rows.append(go_positive(fx['id'],src,fx['function'],fx['inputs'])) |
| 370 | except (Fail,ValueError,KeyError,IndexError,struct.error,subprocess.TimeoutExpired) as e: |
| 371 | it={'id':fx['id'],'result':'FAIL','failure':str(e)};failures.append(it);extra_rows.append(it) |
| 372 | |
| 373 | # ---- Go import refusals; go_build records what Go itself does with the refused file ---- |
| 374 | refusals=[] |
| 375 | for fx in f2['refusals']: |
| 376 | src=bytes.fromhex(fx['source_hex']) if 'source_hex' in fx else fx['source'].encode() |
| 377 | r=gimport(src);ok=hashlib.sha256(src).hexdigest()==fx['sha256'] and r.returncode==fx['status'] and r.stdout==b'' and r.stderr.startswith(b'GO_IMPORT_') |
| 378 | it={'id':fx['id'],'name':fx['name'],'want':fx['status'],'exit':r.returncode,'stderr':r.stderr.decode(errors='replace').strip()} |
| 379 | if fx.get('go_build') in ('accept','reject'): |
| 380 | acc,err=O.gobare(src);it['go_build']='accept' if acc else 'reject' |
| 381 | if not acc:it['go_error']=err.splitlines()[-1][:200] if err else '' |
| 382 | ok=ok and it['go_build']==fx['go_build'] |
| 383 | it['result']='PASS' if ok else 'FAIL' |
| 384 | if not ok:failures.append(it) |
| 385 | refusals.append(it) |
| 386 | |
| 387 | # ---- untyped-constant rule on seeded random trees (go-u64-v1 section 1.1) ---- |
| 388 | crow={'trees':0,'profile_accepted':0,'profile_refused':0,'go_accepts_profile_refused':0,'go_rejects':0,'exporter_refusals_67':0,'failures':0} |
| 389 | seen=set() |
| 390 | while crow['trees']<a.random_trees: |
| 391 | t=rtree(rng,rng.randint(1,4)) |
| 392 | gsrc=H+b'func calc(a uint64, b uint64) uint64 { return '+text(t,'go').encode()+b' }\n' |
| 393 | if gsrc in seen:continue |
| 394 | seen.add(gsrc);crow['trees']+=1 |
| 395 | it={'source':gsrc.decode()} |
| 396 | try: |
| 397 | pok,gok=profile_ok(t),go_ok(t) |
| 398 | check(gok or not pok,'rule model: profile-accepted tree outside the Go rule') |
| 399 | r=gimport(gsrc) |
| 400 | if pok: |
| 401 | check(r.returncode==0,'profile-accepted tree refused rc=%d'%r.returncode);crow['profile_accepted']+=1 |
| 402 | _,_,ops=decode(r.stdout,'Go');vec=vectors(2,rng)[:24] |
| 403 | ref=[tval(t,v) for v in vec];check([evaluate(ops,v) for v in vec]==ref,'imported records != tree') |
| 404 | check(O.values('go',gsrc,'calc',vec)==ref,'go build/run of a profile-accepted tree != modulo-2^64 tree') |
| 405 | else: |
| 406 | check(r.returncode==68 and r.stderr==b'GO_IMPORT_UNSUPPORTED_ARITHMETIC\n','profile-refused tree rc=%d'%r.returncode);crow['profile_refused']+=1 |
| 407 | acc,_=O.gobare(gsrc);check(acc==gok,'go build verdict %s != modelled Go rule %s'%(acc,gok)) |
| 408 | crow['go_accepts_profile_refused' if acc else 'go_rejects']+=1 |
| 409 | c=run([str(cimp)],b'#include <stdint.h>\nuint64_t calc(uint64_t a, uint64_t b) { return '+text(t,'c').encode()+b'; }\n');bump('c_import_runs') |
| 410 | check(c.returncode==0,'C import of the tree refused') |
| 411 | x=gexport(c.stdout) |
| 412 | if pok:check(x.returncode==0,'exporter refused a profile-accepted tree');csem,_=split(c.stdout);reimport_identity(csem,x.stdout,'tree') |
| 413 | else:check(x.returncode==67 and not x.stdout and x.stderr==b'GO_EXPORT_LIMIT\n','exporter must refuse 67, got %d'%x.returncode);crow['exporter_refusals_67']+=1 |
| 414 | except (Fail,ValueError,struct.error,subprocess.TimeoutExpired) as e: |
| 415 | it.update(result='FAIL',failure=str(e));failures.append(it);crow['failures']+=1 |
| 416 | |
| 417 | # ---- import boundary controls (exact and over capacity), each accepted one exported and re-imported ---- |
| 418 | head=H+b'func calc(a uint64, b uint64) uint64 { return ' |
| 419 | base=head+b'a + b }' |
| 420 | chain=lambda k:head+b'a'+b' + a'*k+b' }' |
| 421 | parens=lambda k:head+b'('*k+b'a'+b')'*k+b' }' |
| 422 | controls=[('exact-source-capacity',base+b' '*(4096-len(base)),0,12),('comment-at-capacity',base+b'// '+b'x'*(4096-len(base)-3),0,12), |
| 423 | ('operation-capacity',chain(60),0,61*5),('nesting-limit',parens(16),0,5), |
| 424 | ('over-source-capacity',base+b' '*(4097-len(base)),67,None),('over-operation-capacity',chain(61),67,None), |
| 425 | ('over-nesting-limit',parens(17),67,None)] |
| 426 | ctl=[] |
| 427 | for name,src,want,value in controls: |
| 428 | it={'name':name,'source_bytes':len(src)} |
| 429 | try: |
| 430 | r=gimport(src) |
| 431 | if want:check(r.returncode==want and not r.stdout and r.stderr==b'GO_IMPORT_LIMIT\n','%s rc=%d'%(name,r.returncode)) |
| 432 | else: |
| 433 | check(r.returncode==0,'%s refused rc=%d %s'%(name,r.returncode,r.stderr));sem,side,ops=decode(r.stdout,'Go');sidecar(sem,side,src,len(ops)) |
| 434 | check(evaluate(ops,[5,7])==value,name+' value');codec_checks(r.stdout,sem,src);exported=export_checks(sem,r.stdout,name) |
| 435 | sem_b,_=reimport_identity(sem,exported,name);check(sem_b==sem,name+' round trip') |
| 436 | vec=vectors(2,rng);ref=[evaluate(ops,v) for v in vec] |
| 437 | check(O.values('go',src,'calc',vec)==ref and O.values('go',exported,'calc',vec)==ref,name+' go differential') |
| 438 | it.update(ops=len(ops),exported_bytes=len(exported)) |
| 439 | it.update(result='PASS',exit=r.returncode) |
| 440 | except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it) |
| 441 | ctl.append(it) |
| 442 | r=subprocess.run([str(ROOT/'build/L741/go-import')],stdin=subprocess.DEVNULL,capture_output=True,preexec_fn=lambda:os.close(0),timeout=10) |
| 443 | ctl.append({'name':'import-closed-stdin','exit':r.returncode,'result':'PASS' if r.returncode==77 and not r.stdout and r.stderr==b'GO_IMPORT_IO\n' else 'FAIL'}) |
| 444 | r=subprocess.run([str(ROOT/'build/L741/go-export')],stdin=subprocess.DEVNULL,capture_output=True,preexec_fn=lambda:os.close(0),timeout=10) |
| 445 | ctl.append({'name':'export-closed-stdin','exit':r.returncode,'result':'PASS' if r.returncode==77 and not r.stdout and r.stderr==b'GO_EXPORT_IO\n' else 'FAIL'}) |
| 446 | for tool in (IMPORT,EXPORT): |
| 447 | r=run([sys.executable,str(tool),'unexpected'],base);ctl.append({'name':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'}) |
| 448 | r=run([sys.executable,str(IMPORT)],base);d=run([str(ROOT/'build/L741/go-import')],base) |
| 449 | ctl.append({'name':'public-import-identical-to-native','result':'PASS' if r.returncode==0 and r.stdout==d.stdout else 'FAIL'}) |
| 450 | closure=['src/source-aware/vendor/sha256.om','src/source-aware/core-v2.om','src/adapters/go-u64-import.om','src/adapters/go-u64-export.om','build/L741/build.json','build/L741/go-import','build/L741/go-export'] |
| 451 | for tool,victims in ((IMPORT,['src/adapters/go-u64-import.om','src/source-aware/vendor/sha256.om','build/L741/go-import']),(EXPORT,['src/adapters/go-u64-export.om','src/source-aware/core-v2.om','build/L741/go-export'])): |
| 452 | for victim in victims: |
| 453 | with tempfile.TemporaryDirectory(prefix='closed-build-',dir=out) as td: |
| 454 | t=Path(td) |
| 455 | for rel in ['tools/adapters/'+tool.name]+closure: |
| 456 | p=t/rel;p.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(ROOT/rel,p);p.chmod(0o700) |
| 457 | with (t/victim).open('ab') as f:f.write(b'changed') |
| 458 | r=run([sys.executable,str(t/'tools/adapters'/tool.name)],base) |
| 459 | ok=r.returncode==78 and not r.stdout and b'STALE_OR_MISSING_BUILD' in r.stderr |
| 460 | ctl.append({'name':tool.name+'-stale-'+victim,'exit':r.returncode,'result':'PASS' if ok else 'FAIL'}) |
| 461 | failures+=[c for c in ctl if c['result']=='FAIL' and c not in failures] |
| 462 | |
| 463 | # ---- exporter refusals and accepted exporter boundaries ---- |
| 464 | good=gimport(base).stdout |
| 465 | def unit(ver,lang,prof,runtime,abi,ops,typ=1): |
| 466 | sem=b'OMSA'+bytes([ver,lang,prof,1,runtime,abi])+struct.pack('<H',len(ops))+CONTRACT |
| 467 | for op,attr,eff,alias,obl,a_,b_,imm in ops:sem+=struct.pack('<8BHHQ',lang,1,op,typ,attr,eff,alias,obl,a_,b_,imm) |
| 468 | return semonly(sem) |
| 469 | U=65535 |
| 470 | def shared(k): # t_j = add(t_{j-1}, t_{j-1}): tree size 2^k, depth k |
| 471 | return unit(2,7,9,0,1,[(9,0,0,0,1,U,U,0)]+[(2,1,0,0,1,j,j,0) for j in range(k)]) |
| 472 | bigint=unit(1,3,3,1,1,[(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) |
| 473 | divc=unit(1,1,1,0,1,[(9,0,0,0,1,U,U,0),(9,0,0,0,1,U,U,1),(5,1,0,0,3,0,1,0)]) |
| 474 | divgo=unit(2,7,9,0,1,[(9,0,0,0,1,U,U,0),(9,0,0,0,1,U,U,1),(5,1,0,0,3,0,1,0)]) |
| 475 | gap=unit(2,7,9,0,1,[(9,0,0,0,1,U,U,1)]) |
| 476 | v1go=unit(1,7,9,0,1,[(9,0,0,0,1,U,U,0)]) |
| 477 | v3=bytearray(good);v3[17]=3 |
| 478 | flipped=bytearray(good);flipped[-3]^=1 |
| 479 | deep=[(9,0,0,0,1,U,U,0)] |
| 480 | for j in range(18):deep.append((2,1,0,0,1,0,j,0)) # i0 + (i0 + (...)): 18 adds = parenthesis depth 17 |
| 481 | cneg=unit(1,1,1,0,1,[(9,0,0,0,1,U,U,0),(1,1,0,0,0,U,U,0),(1,1,0,0,0,U,U,1),(3,1,0,0,1,1,2,0),(2,1,0,0,1,0,3,0)]) |
| 482 | cdead=unit(1,1,1,0,1,[(9,0,0,0,1,U,U,0),(1,1,0,0,0,U,U,0),(1,1,0,0,0,U,U,1),(3,1,0,0,1,1,2,0),(4,1,0,0,1,0,0,0)]) |
| 483 | 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), |
| 484 | ('unknown-version-3',bytes(v3),65),('profile3-bigint',bigint,68),('c-div-op5',divc,68),('go-div-op5',divgo,68),('slot-gap',gap,68), |
| 485 | ('go-profile-version-1',v1go,68),('language-profile-mismatch',bytes(good[:18])+b'\x01'+good[19:],68), |
| 486 | ('shared-ops-over-capacity',shared(6),67),('depth-over-limit',unit(2,7,9,0,1,deep),67),('size-over-limit',shared(9),67), |
| 487 | ('constant-subtree-negative',cneg,67)] |
| 488 | xrows=[] |
| 489 | for name,env,want in xr: |
| 490 | if have_sa2 and name in ('profile3-bigint','c-div-op5','go-div-op5','constant-subtree-negative'):check(sa2('decode',env).returncode==0,name+' control is not a valid unit') |
| 491 | r=gexport(env);ok=r.returncode==want and not r.stdout and r.stderr.startswith(b'GO_EXPORT_') |
| 492 | it={'name':name,'want':want,'exit':r.returncode,'stderr':r.stderr.decode(errors='replace').strip(),'result':'PASS' if ok else 'FAIL'} |
| 493 | if not ok:failures.append(it) |
| 494 | xrows.append(it) |
| 495 | 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)] |
| 496 | for name,env,nops in (('shared-ops-at-capacity',unit(2,7,9,0,1,exact),64),('depth-at-limit',unit(2,7,9,0,1,deep[:18]),20),('unreachable-negative-constant',cdead,4)): |
| 497 | it={'name':name} |
| 498 | try: |
| 499 | sem,_=split(env);ops=[(o[2],o[8],o[9],o[10]) for o in ops_of(sem)];r=gexport(env);check(r.returncode==0,name+' refused rc=%d'%r.returncode) |
| 500 | check(O.gofmt_clean(r.stdout),name+' export is not gofmt-clean') |
| 501 | q=gimport(r.stdout);check(q.returncode==0,name+' re-import refused');_,_,ops2=decode(q.stdout,'Go') |
| 502 | check(len(ops2)==nops,name+' re-import operation count %d'%len(ops2)) |
| 503 | vec=vectors(1,rng);ref=[evaluate(ops,v) for v in vec] |
| 504 | check([evaluate(ops2,v) for v in vec]==ref and O.values('go',r.stdout,'calc',vec)==ref,name+' evaluation') |
| 505 | it.update(result='PASS',reimport_ops=len(ops2),identity_equal=N(strip(split(q.stdout)[0]))==N(strip(sem))) |
| 506 | except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it) |
| 507 | xrows.append(it) |
| 508 | |
| 509 | # ---- random SSA units of every member (shared results, unused inputs, slot permutations) ---- |
| 510 | def model(ops,root,ni): |
| 511 | """Exporter limits of go-u64-v1 section 4 on the expanded tree: (re-import ops, paren depth, constants ok).""" |
| 512 | pr=[];dp=[];cn=[];kv=[] |
| 513 | for op,x,y,imm in ops: |
| 514 | if op in (1,9):pr.append(6);dp.append(0);cn.append(int(op==1));kv.append(imm if op==1 else None);continue |
| 515 | p=5 if op==4 else 4;pa=int(pr[x]<p);pb=int(pr[y]<=p) |
| 516 | pr.append(p);dp.append(max(dp[x]+pa,dp[y]+pb));cn.append(cn[x]+cn[y]+1) |
| 517 | kv.append(None if kv[x] is None or kv[y] is None else kv[x]+kv[y] if op==2 else kv[x]-kv[y] if op==3 else kv[x]*kv[y]) |
| 518 | seen=set();stack=[root];cok=True |
| 519 | while stack: |
| 520 | k=stack.pop() |
| 521 | if k in seen:continue |
| 522 | seen.add(k) |
| 523 | if kv[k] is not None and not 0<=kv[k]<=MASK:cok=False |
| 524 | if ops[k][0] in (2,3,4):stack+=[ops[k][1],ops[k][2]] |
| 525 | return ni+cn[root]+2,dp[root],cok |
| 526 | drow={'units':0,'exported':0,'refused_67':0,'go_checked':0,'failures':0} |
| 527 | for k in range(80): |
| 528 | m=rng.choice(list(MEMBERS));ver,lang,prof,arob=MEMBERS[m];ni=rng.randint(0,6);slots=list(range(ni));rng.shuffle(slots) |
| 529 | ops=[(9,U,U,s) for s in slots];recs=[(9,0,0,0,1,U,U,s) for s in slots] |
| 530 | for j in range(rng.randint(1,22)): |
| 531 | if not ops or rng.random()<0.2: |
| 532 | v=rng.choice(CONSTS) if rng.random()<0.7 else rng.getrandbits(64);ops.append((1,U,U,v));recs.append((1,1,0,0,0,U,U,v)) |
| 533 | else: |
| 534 | op=rng.choice((2,3,4));x=rng.randrange(len(ops));y=rng.randrange(len(ops)) |
| 535 | if rng.random()<0.5:x=len(ops)-1 |
| 536 | ops.append((op,x,y,0));recs.append((op,1,0,0,arob,x,y,0)) |
| 537 | if len(ops)>64:continue |
| 538 | drow['units']+=1;env=unit(ver,lang,prof,0,1,recs);sem,_=split(env);it={'member':m,'ops':len(ops)} |
| 539 | try: |
| 540 | root=len(ops)-1 |
| 541 | if normalized(ops):root=ops[-1][1] |
| 542 | nops,depth,cok=model(ops,root,ni);ok=nops<=64 and depth<=16 and cok |
| 543 | r=gexport(env) |
| 544 | if not ok:check(r.returncode==67 and not r.stdout,'model predicts 67 (ops %d depth %d constants %s), got %d'%(nops,depth,cok,r.returncode));drow['refused_67']+=1;continue |
| 545 | check(r.returncode==0,'model predicts export, got %d %s'%(r.returncode,r.stderr));drow['exported']+=1 |
| 546 | check(O.gofmt_clean(r.stdout),'random unit export is not gofmt-clean') |
| 547 | q=gimport(r.stdout);check(q.returncode==0,'re-import refused %d'%q.returncode);_,_,ops2=decode(q.stdout,'Go') |
| 548 | check(len(ops2)==nops,'re-import operation count %d != model %d'%(len(ops2),nops)) |
| 549 | vec=vectors(ni,rng)[:20];ref=[evaluate(ops,v) for v in vec];check([evaluate(ops2,v) for v in vec]==ref,'re-import evaluation differs') |
| 550 | if drow['go_checked']<16:check(O.values('go',r.stdout,'calc',vec)==ref,'go(export) != reference');drow['go_checked']+=1 |
| 551 | except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it);drow['failures']+=1 |
| 552 | |
| 553 | # ---- composition C -> Go: F1 positives and the four accepted C import boundary controls ---- |
| 554 | ch=b'#include <stdint.h>\nuint64_t calc(uint64_t a,uint64_t b){return a+b;}' |
| 555 | 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), |
| 556 | ('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), |
| 557 | ('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)] |
| 558 | comp=[] |
| 559 | for tag,csrc,name,nargs in [(p['id'],p['source'].encode(),p['name'],p['inputs']) for p in f1['positives']]+cctl: |
| 560 | it={'id':'C->Go '+tag} |
| 561 | try: |
| 562 | c=run([str(cimp)],csrc);bump('c_import_runs');check(c.returncode==0,'C import refused') |
| 563 | sem_a,_,ops_a=decode(c.stdout,'C') |
| 564 | src_b=export_checks(sem_a,c.stdout,tag) |
| 565 | sem_b,ops_b=reimport_identity(sem_a,src_b,tag) |
| 566 | vec=vectors(nargs,rng);ref=[evaluate(ops_a,v) for v in vec] |
| 567 | check(O.values('c',csrc,name,vec)==ref,'cc(original C) != reference(U_A)') |
| 568 | check(O.values('go',src_b,'calc',vec)==ref,'go(src_B) != reference(U_A)') |
| 569 | check([evaluate(ops_b,v) for v in vec]==ref,'reference(U_B) != reference(U_A)') |
| 570 | if native:check(native.values(N(sem_a),vec)==ref,'native lower(N(U_A)) != reference(U_A)') |
| 571 | it.update(result='PASS',identity=identity(N(strip(sem_a))),vectors=len(vec),native_realization='PASS' if native else native_state) |
| 572 | except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it) |
| 573 | comp.append(it) |
| 574 | |
| 575 | # ---- composition Go -> C: R(U, C) in test code (retarget not landed), then the #622 C exporter ---- |
| 576 | gc_rows=[];go_to_c='NOT_RUN (no c-export)' |
| 577 | if cexp: |
| 578 | go_to_c='RUN' |
| 579 | for fx in f2['positives']: |
| 580 | it={'id':'Go->C '+fx['id']} |
| 581 | try: |
| 582 | src=fx['source'].encode();r=gimport(src);check(r.returncode==0,'Go import refused');sem_a,_,ops_a=decode(r.stdout,'Go') |
| 583 | rc_env=R(r.stdout,sem_a,'C');q=py(cexp,rc_env);bump('c_export_runs');check(q.returncode==0,'c-export refused R(U,C) rc=%d %s'%(q.returncode,q.stderr)) |
| 584 | q2=py(cexp,semonly(sem_a));check(q2.returncode!=0 and not q2.stdout,'v1-core c-export accepted a v2 unit');bump('c_export_v2_refusal_status_%d'%q2.returncode) |
| 585 | c=run([str(cimp)],q.stdout);bump('c_import_runs');check(c.returncode==0,'C import of exported C refused') |
| 586 | 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))') |
| 587 | vec=vectors(fx['inputs'],rng);ref=[evaluate(ops_a,v) for v in vec] |
| 588 | check(O.values('go',src,fx['name'],vec)==ref,'go(original Go) != reference') |
| 589 | check(O.values('c',q.stdout,'calc',vec)==ref,'cc(src_B) != reference') |
| 590 | check([evaluate(ops_b,v) for v in vec]==ref,'reference(U_B) != reference(U_A)') |
| 591 | if native:check(native.values(N(sem_a),vec)==ref,'native lower(N(U_A)) != reference(U_A)') |
| 592 | it.update(result='PASS',vectors=len(vec),exported_c=q.stdout.decode(),native_realization='PASS' if native else native_state) |
| 593 | except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it) |
| 594 | gc_rows.append(it) |
| 595 | |
| 596 | def ver(cmd): |
| 597 | try:return subprocess.check_output(cmd,text=True,env=O.env).strip() |
| 598 | except (OSError,subprocess.CalledProcessError) as e:return 'unavailable: '+str(e) |
| 599 | report={'schema':'omega.go-u64.selftest.v1','result':'FAIL' if failures else 'PASS','status_flags':'TESTED (author self-test), not QUALIFIED', |
| 600 | 'evidence':'REFERENCE + DIFFERENTIAL (go/cc NATIVE AArch64%s); no PROOF'%(', Omega native realization' if native else ''), |
| 601 | 'source_commit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip(), |
| 602 | 'build':json.loads((ROOT/'build/L741/build.json').read_text()),'go':ver([a.go,'version']),'go_sha256':hashlib.sha256(Path(a.go).read_bytes()).hexdigest(), |
| 603 | 'gofmt_sha256':hashlib.sha256(Path(a.gofmt).read_bytes()).hexdigest(),'cc':ver([a.cc,'--version']).splitlines()[0], |
| 604 | 'c_import_sha256':hashlib.sha256(cimp.read_bytes()).hexdigest(),'sa1_sha256':hashlib.sha256(sa1.read_bytes()).hexdigest(), |
| 605 | 'codec_v2':codec_v2,'sa2_sha256':hashlib.sha256((sa2root/'build/L832/sa').read_bytes()).hexdigest() if have_sa2 else None, |
| 606 | 'c_export':str(cexp) if cexp else None,'retarget_tool':('RUN '+str(rtool)+' sha256 '+hashlib.sha256(rtool.read_bytes()).hexdigest()) if rtool else 'NOT_RUN (Python R only)','native_realization':native_state, |
| 607 | 'positives':len(rows),'positives_passed':sum(r['result']=='PASS' for r in rows),'not_in_profile':len(f2['not_in_profile']), |
| 608 | 'extra_positives':len(extra_rows),'extra_positives_passed':sum(r['result']=='PASS' for r in extra_rows), |
| 609 | 'refusals':len(refusals),'refusals_passed':sum(r['result']=='PASS' for r in refusals), |
| 610 | 'refusals_go_checked':sum('go_build' in r for r in refusals),'constant_rule':crow,'random_units':drow, |
| 611 | '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), |
| 612 | 'c_to_go':len(comp),'c_to_go_passed':sum(r['result']=='PASS' for r in comp),'go_to_c':go_to_c,'go_to_c_cases':len(gc_rows),'go_to_c_passed':sum(r['result']=='PASS' for r in gc_rows), |
| 613 | 'native_calls':native.calls if native else 0,'oracle_compiles':O.compiles,'go_builds':O.go_builds,'gofmt_runs':O.gofmt_runs,'counts':counts, |
| 614 | 'cases':rows,'extra_cases':extra_rows,'refusal_cases':refusals,'control_cases':ctl,'export_rows':xrows,'c_to_go_cases':comp,'go_to_c_rows':gc_rows,'failures':failures} |
| 615 | (out/'result.json').write_text(json.dumps(report,indent=1)+'\n') |
| 616 | keys=['positives','positives_passed','not_in_profile','extra_positives','extra_positives_passed','refusals','refusals_passed','refusals_go_checked','controls','controls_passed', |
| 617 | 'export_cases','export_cases_passed','c_to_go','c_to_go_passed','go_to_c','go_to_c_cases','go_to_c_passed','codec_v2','retarget_tool','native_realization','native_calls','oracle_compiles','go_builds','gofmt_runs'] |
| 618 | print(report['result'],' '.join('%s=%s'%(k,report[k]) for k in keys),'constant_rule='+json.dumps(crow,separators=(',',':')),'random_units='+json.dumps(drow,separators=(',',':')),' '.join('%s=%s'%kv for kv in counts.items())) |
| 619 | for f in failures[:20]:print('FAIL',json.dumps(f)[:600]) |
| 620 | return 1 if failures else 0 |
| 621 | |
| 622 | if __name__=='__main__':raise SystemExit(main()) |