interplane.Get Omega
Read in your language

omega-bridge

Omega-first language interoperability: checked conversion backends and native language bindings

Brought by drakestapleton

branch main Branches Tags History

omega-bridge / tests / native / float.py

183 lines · 9512 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Exercise the same f32/f64 native units from C, ctypes, Rust, Zig and Go.
3
4No host floating arithmetic supplies an expected answer: each input/result is
5compared as its original unsigned bit pattern, including NaN payloads and -0.
6"""
7import ctypes as C
8import importlib.util
9import os
10from pathlib import Path
11import shutil
12import subprocess
13import tempfile
14
15ROOT = Path(__file__).resolve().parents[2]
16
17
18def run(cmd, env=None, cwd=None):
19 p = subprocess.run([str(x) for x in cmd], capture_output=True, env=env, cwd=cwd, timeout=300)
20 assert p.returncode == 0, (cmd, p.returncode, p.stdout.decode(errors="replace"), p.stderr.decode(errors="replace"))
21 return p.stdout
22
23
24C_TEST = r'''#include <stdint.h>
25#include <string.h>
26#include "omega_native.h"
27int main(void){
28 uint32_t b32[]={0,0x80000000u,1,0x007fffffu,0x7f800000u,0xff800000u,0x7fc12345u,0x7f800001u};
29 uint64_t b64[]={0,UINT64_C(0x8000000000000000),1,UINT64_C(0xfffffffffffff),UINT64_C(0x7ff0000000000000),UINT64_C(0xfff0000000000000),UINT64_C(0x7ff8000000012345),UINT64_C(0x7ff0000000000001)};
30 for(unsigned i=0;i<8;i++){
31 float x32,y32;double x64,y64;uint32_t r32;uint64_t r64;
32 memcpy(&x32,&b32[i],4);memcpy(&x64,&b64[i],8);
33 if(omega_identity32(&y32,x32)||omega_identity64(&y64,x64))return 1;
34 memcpy(&r32,&y32,4);memcpy(&r64,&y64,8);
35 if(r32!=b32[i]||r64!=b64[i])return 2;
36 float source,dest=0.0f;uint32_t stored;
37 memcpy(&source,&b32[7-i],4);
38 if(omega_array32(&y32,x32,&source,1,&dest,1))return 4;
39 memcpy(&r32,&y32,4);memcpy(&stored,&dest,4);
40 if(r32!=b32[7-i]||stored!=b32[i])return 5;
41 if(omega_array32(&y32,x32,&source,0,&dest,1)!=OMEGA_BAD_ARG)return 6;
42 if(omega_array32(&source,x32,&source,1,&dest,1)!=OMEGA_BAD_ARG)return 7;
43 if(omega_array32(&y32,x32,&source,1,&source,1)!=OMEGA_BAD_ARG)return 8;
44 memcpy(&r32,&y32,4);memcpy(&stored,&dest,4);
45 if(r32!=b32[7-i]||stored!=b32[i])return 9;
46 }
47 if(omega_identity32(0,0.0f)!=OMEGA_BAD_ARG||omega_identity64(0,0.0)!=OMEGA_BAD_ARG)return 3;
48 return 0;
49}
50'''
51RUST_TEST = r'''mod omega_native;
52use omega_native::*;
53fn main(){unsafe {
54 for b in [0u32,0x80000000,1,0x007fffff,0x7f800000,0xff800000,0x7fc12345,0x7f800001]{
55 let mut r=0f32;assert_eq!(omega_identity32(&mut r,f32::from_bits(b)),0);assert_eq!(r.to_bits(),b);
56 }
57 for b in [0u64,0x8000000000000000,1,0xfffffffffffff,0x7ff0000000000000,0xfff0000000000000,0x7ff8000000012345,0x7ff0000000000001]{
58 let mut r=0f64;assert_eq!(omega_identity64(&mut r,f64::from_bits(b)),0);assert_eq!(r.to_bits(),b);
59 }
60}}
61'''
62ZIG_TEST = r'''const n=@import("omega_native.zig");
63pub fn main() void {
64 for([_]u32{0,0x80000000,1,0x007fffff,0x7f800000,0xff800000,0x7fc12345,0x7f800001}) |b| {
65 var r:f32=0;if(n.omega_identity32(&r,@as(f32,@bitCast(b)))!=0) @panic("status32");
66 if(@as(u32,@bitCast(r))!=b) @panic("bits32");
67 }
68 for([_]u64{0,0x8000000000000000,1,0xfffffffffffff,0x7ff0000000000000,0xfff0000000000000,0x7ff8000000012345,0x7ff0000000000001}) |b| {
69 var r:f64=0;if(n.omega_identity64(&r,@as(f64,@bitCast(b)))!=0) @panic("status64");
70 if(@as(u64,@bitCast(r))!=b) @panic("bits64");
71 }
72}
73'''
74GO_TEST = r'''package omeganative
75import("math";"testing")
76func TestFloatBits(t *testing.T){
77 for _,b:=range []uint32{0,0x80000000,1,0x007fffff,0x7f800000,0xff800000,0x7fc12345,0x7f800001}{
78 var r float32;if Omega_identity32(&r,math.Float32frombits(b))!=0||math.Float32bits(r)!=b{t.Fatal("f32",b)}
79 }
80 for _,b:=range []uint64{0,0x8000000000000000,1,0xfffffffffffff,0x7ff0000000000000,0xfff0000000000000,0x7ff8000000012345,0x7ff0000000000001}{
81 var r float64;if Omega_identity64(&r,math.Float64frombits(b))!=0||math.Float64bits(r)!=b{t.Fatal("f64",b)}
82 }
83}
84'''
85
86
87def main():
88 profile = os.environ.get("OMEGA_NATIVE_FLOAT_PROFILE", "e5")
89 assert profile in ("e5", "next"), profile
90 option = "--float-next" if profile == "next" else "--float"
91 with tempfile.TemporaryDirectory(prefix="omega-native-float-") as td:
92 w = Path(td)
93 units = []
94 for width in (32, 64):
95 p = w / f"identity{width}.om"
96 p.write_text(f"fn identity{width} x f{width} to f{width}\nret x\nend\n")
97 units.append(p)
98 array_unit = w / "array32.om"
99 array_unit.write_text("fn array32 x f32 a view f32 1 b edit f32 1 to f32\nput b 0 x\nret get a 0\nend\n")
100 units.append(array_unit)
101 out = w / "out"
102 for bad in (["--freestanding"], ["--target", "x86linux"]):
103 refused = w / ("refused-" + bad[-1].replace("--", ""))
104 p = subprocess.run([ROOT / "tools/native", option, *bad, refused, *units], capture_output=True)
105 assert p.returncode == 110 and not refused.exists(), (bad, p.returncode, p.stderr)
106 print("PASS native float unsupported target/freestanding refused before output")
107 print(run([ROOT / "tools/native", option, out, *units]).decode().strip())
108 framed = (out / "work/units.in").read_bytes()
109 for mode in ("c", "h", "python", "rust", "zig", "go"):
110 p = subprocess.run([out / "work/native-gen", mode], input=framed, capture_output=True)
111 assert p.returncode == 110 and not p.stdout, (mode, p.returncode, p.stdout)
112 print("PASS direct framed-generator float signatures require explicit profile")
113 host_out = w / "host"
114 run([ROOT / "tools/native", option, "--host", host_out, *units])
115 host_caller = host_out / "float.c"
116 host_caller.write_text(C_TEST)
117 host_exe = host_out / "float-c"
118 run([os.environ.get("CC", "cc"), "-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", host_caller, "-L" + str(host_out), "-lomega_native", "-Wl,-rpath," + str(host_out), "-o", host_exe])
119 run([host_exe])
120 print("PASS native float explicit host-profile C marshalling")
121 caller = out / "float.c"
122 caller.write_text(C_TEST)
123 exe = out / "float-c"
124 run([os.environ.get("CC", "cc"), "-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", caller, "-L" + str(out), "-lomega_native", "-Wl,-rpath," + str(out), "-o", exe])
125 run([exe])
126 print("PASS native float C: NaN payloads/-0/denormals/inf/null")
127 spec = importlib.util.spec_from_file_location("native_float", out / "omega_native.py")
128 module = importlib.util.module_from_spec(spec)
129 spec.loader.exec_module(module)
130 for width, ct, ft, values in ((32, C.c_uint32, C.c_float, [0, 0x80000000, 1, 0x007fffff, 0x7f800000, 0xff800000, 0x7fc12345, 0x7f800001]), (64, C.c_uint64, C.c_double, [0, 0x8000000000000000, 1, 0xfffffffffffff, 0x7ff0000000000000, 0xfff0000000000000, 0x7ff8000000012345, 0x7ff0000000000001])):
131 fn = getattr(module, f"omega_identity{width}")
132 for bits in values:
133 arg, result = ft.from_buffer_copy(ct(bits)), ft()
134 assert fn(C.byref(result), arg) == 0
135 assert ct.from_buffer_copy(result).value == bits
136 print("PASS native float Python ctypes: NaN payloads/-0/denormals/inf")
137 rust = os.environ.get("RUSTC") or shutil.which("rustc")
138 if rust:
139 p = out / "float.rs"
140 p.write_text(RUST_TEST)
141 exe = out / "float-rust"
142 run([rust, "--edition=2021", p, "-L", "native=" + str(out), "-C", "link-arg=-Wl,-rpath," + str(out), "-o", exe])
143 run([exe])
144 print("PASS native float Rust: NaN payloads/-0/denormals/inf")
145 else:
146 print("NOT_RUN native float Rust: rustc not on PATH and RUSTC unset")
147 zig = os.environ.get("ZIG") or shutil.which("zig")
148 if zig:
149 p = out / "float.zig"
150 p.write_text(ZIG_TEST)
151 exe = out / "float-zig"
152 run([zig, "build-exe", p, "-L" + str(out), "-lomega_native", "-lc", "-rpath", out, "-femit-bin=" + str(exe)])
153 run([exe])
154 print("PASS native float Zig: NaN payloads/-0/denormals/inf")
155 else:
156 print("NOT_RUN native float Zig: zig not on PATH and ZIG unset")
157 go = os.environ.get("GO") or shutil.which("go")
158 if go:
159 # cgo directory must contain only generated library C and its Go test.
160 caller.unlink()
161 (out / "go.mod").write_text("module omeganative\n\ngo 1.23\n")
162 (out / "float_test.go").write_text(GO_TEST)
163 env = dict(os.environ, CGO_ENABLED="1", CGO_LDFLAGS="-Wl,-rpath," + str(out))
164 run([go, "test", "."], env=env, cwd=out)
165 print("PASS native float Go: NaN payloads/-0/denormals/inf")
166 else:
167 print("NOT_RUN native float Go: go not on PATH and GO unset")
168 # The native scalar bit-copy mutant must fail the same C oracle.
169 cfile = out / "omega_native.c"
170 code = cfile.read_text()
171 for size in (4, 8):
172 old = f"if(!status)memcpy(result,&r,{size})"
173 assert code.count(old) == (2 if size == 4 else 1)
174 cfile.write_text(code.replace(old, "r^=1;" + old))
175 run([os.environ.get("CC", "cc"), "-std=gnu11", "-O2", "-fPIC", "-shared", "-include", out / "omega_native.h", cfile, "-o", out / "libomega_native.so"])
176 p = subprocess.run([out / "float-c"], capture_output=True)
177 assert p.returncode == 2, ("native float ABI mutant survived", size, p.returncode)
178 print("PASS killed native float ABI marshalling mutant, bytes", size)
179 print("NATIVE-FLOAT PASS (see per-language NOT_RUN lines)")
180
181
182if __name__ == "__main__":
183 main()