interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / seed / qualification / om2 / oracle / s0s2 / oracle.py

320 lines · 12540 bytes Raw Blame History
1# SPDX-License-Identifier: Apache-2.0
2# Independent oracle for seed/qualification/om2/sec/s0s2 (L836 Phase B, lane FixLex).
3# It never runs a compiler. It computes expected stdout, stderr and formatter text from the
4# contract (spec/omegese-om2.md sha256 245bb74e..0881, errata E1/E2/E4) and from the fixture bytes.
5# Run from the worktree root: python3 seed/qualification/om2/oracle/s0s2/oracle.py
6import os
7
8ROOT = "seed/qualification/om2/sec/s0s2"
9EXP = ROOT + "/exp"
10M64 = (1 << 64) - 1
11
12
13def rd(rel):
14 with open(os.path.join(ROOT, rel), "rb") as f:
15 return f.read()
16
17
18def wr(name, data):
19 if isinstance(data, str):
20 data = data.encode()
21 with open(os.path.join(EXP, name), "wb") as f:
22 f.write(data)
23
24
25def lines_out(vals):
26 return "".join("%d\n" % v for v in vals)
27
28
29# ---------------------------------------------------------------- opt-in line (contract 0, line 13)
30def first_non_note_line(src):
31 """1-based number of the first line whose first word is not `note` (a blank line counts)."""
32 for i, ln in enumerate(src.split(b"\n"), 1):
33 words = ln.split()
34 if not (ln.startswith(b"note") and words and words[0] == b"note"):
35 return i
36 raise ValueError("no non-note line")
37
38
39def human(line, code):
40 return "omc: line %d: error %d\n" % (line, code)
41
42
43def line_of(src, needle, nth=1):
44 """1-based line of the nth non-note line containing needle as a whole space/tab-separated word."""
45 seen = 0
46 for i, ln in enumerate(src.split(b"\n"), 1):
47 words = ln.split()
48 if words and words[0] != b"note" and needle in words:
49 seen += 1
50 if seen == nth:
51 return i
52 raise ValueError(needle)
53
54
55# ---------------------------------------------------------------- 0: OM-1 names keep their meaning
56def names_fn():
57 # Re-implementation of the user functions in s0/names-fn.om (OMEGESE 9.3: unsigned wraps).
58 u32 = 0xFFFFFFFF
59 rotr = lambda x, n: (x ^ n) & u32
60 rotl = lambda x, n: (x - n) & u32
61 return [rotr(5, 3), rotl(4000000000, 7), (14 * 3) & M64, 20 + 22, sum(range(10)), 1 + 100,
62 15 ^ 255, 1001 >> 1, 100 % 7, (0 - 1) & M64, (4294967296 * 4294967296) & M64,
63 1234 & 15, 1 | 256, (3 << 4) & M64, 7]
64
65
66def names_var():
67 fresh, at, unroll, inline, seal, opn = 3, 4, 5, 6, 7, 8
68 a = [fresh + at, unroll * inline, seal - 1, opn << 2]
69 layout = [9] * 4
70 field = [11] * 2
71 layout[1] = 42
72 field[0] = field[1] + 1
73 c_at, c_open, c_part = 1, 2, [3, 3] # one value per field; array field gets it in every element
74 c_at = 30
75 c_part[1] = c_open * 5
76 rotl = 9 + 1
77 fmt = 12 + 13
78 return a + [layout[1], layout[3], field[0], c_at, c_part[0], c_part[1], rotl, fmt]
79
80
81# ---------------------------------------------------------------- 2: hex literal values
82def hexv(t):
83 assert t.startswith("0x") and 1 <= len(t) - 2 <= 16
84 assert all(c in "0123456789abcdef" for c in t[2:])
85 return int(t[2:], 16)
86
87
88def hex_max():
89 lits = ["0xff", "0xffff", "0xffffffff", "0xffffffffffffffff", "0x7f", "0x7fff", "0x7fffffff",
90 "0x7fffffffffffffff", "0x0", "0x00000000000000ff", "0x0123456789abcdef"]
91 want = [2**8 - 1, 2**16 - 1, 2**32 - 1, 2**64 - 1, 2**7 - 1, 2**15 - 1, 2**31 - 1, 2**63 - 1,
92 0, 255, 81985529216486895]
93 vals = [hexv(t) for t in lits]
94 assert vals == want, (vals, want)
95 return vals
96
97
98def hex_places():
99 a = [hexv("0x0")] * hexv("0x4")
100 a[hexv("0x1")] = hexv("0x68")
101 a[hexv("0x3")] = hexv("0xa")
102 s = sum(range(hexv("0x5")))
103 out = [s, 2 * hexv("0x15"), a[1]]
104 if s == hexv("0xa"):
105 out.append(hexv("0xabc"))
106 y = hexv("0x10") - hexv("0x20")
107 if y < 0:
108 out.append(-y)
109 return lines_out(out) + "hex\n", a[3]
110
111
112# ---------------------------------------------------------------- 2: canonical formatter (E4)
113WS = (b" ", b"\t")
114
115
116def is_note(ln):
117 """E6 (c,d): a note line is any line whose first token is `note`, indented or not."""
118 w = ln.split()
119 return bool(w) and w[0] == b"note"
120
121
122def fmt_line(ln):
123 if is_note(ln):
124 return ln # kept byte for byte (E6 c,d; contract line 67)
125 if not ln.strip(b" \t"):
126 return b"" # whitespace-only line becomes empty (E6 b)
127 i = 0
128 while i < len(ln) and ln[i:i + 1] in WS:
129 i += 1
130 indent, rest = ln[:i], ln[i:]
131 toks, gaps, j = [], [], 0 # gaps[k] = whitespace written before toks[k]
132 while j < len(rest):
133 g = j
134 while j < len(rest) and rest[j:j + 1] in WS:
135 j += 1
136 if j == len(rest):
137 break # trailing whitespace: dropped (line 65)
138 k = j
139 if rest[j:j + 1] == b'"': # text literal: bytes up to the closing quote
140 k += 1
141 while rest[k:k + 1] != b'"':
142 k += 2 if rest[k:k + 1] == b"\\" else 1
143 if k > len(rest):
144 raise ValueError("open text literal")
145 k += 1
146 else:
147 while k < len(rest) and rest[k:k + 1] not in WS:
148 k += 1
149 gaps.append(rest[g:j])
150 toks.append(rest[j:k])
151 j = k
152 out = indent + toks[0]
153 for k in range(1, len(toks)):
154 near_paren = toks[k - 1][-1:] in (b"(", b")") or toks[k][:1] in (b"(", b")")
155 out += (gaps[k] if near_paren else b" ") + toks[k] # E6 (e): paren spacing kept as written
156 return out
157
158
159def fmt(rest):
160 assert b"\r" not in rest # E6 (g): CR is error 6 anywhere
161 body = rest[:-1] if rest.endswith(b"\n") else rest
162 last = body.split(b"\n")[-1]
163 assert last.strip(b" \t"), "trailing blank lines are error 6 (E6 a), not a fmt output case"
164 out = b"\n".join(fmt_line(ln) for ln in body.split(b"\n")) + b"\n"
165 assert out.count(b"\n") == body.count(b"\n") + 1 # line count unchanged (line 72)
166 return out
167
168
169# ---------------------------------------------------------------- 1: omc-diag records (E4)
170def span_of(src, line, tok, nth=1):
171 """Byte span [A,B) of the nth whole token `tok` on 1-based `line`, and its 1-based column."""
172 starts = [0]
173 for i, b in enumerate(src):
174 if b == 0x0A:
175 starts.append(i + 1)
176 ls = starts[line - 1]
177 le = src.index(b"\n", ls) if b"\n" in src[ls:] else len(src)
178 text = src[ls:le]
179 pos, seen = 0, 0
180 while True:
181 k = text.index(tok, pos)
182 before = text[k - 1:k] if k else b" "
183 after = text[k + len(tok):k + len(tok) + 1] or b" "
184 if before in (b" ", b"\t") and after in (b" ", b"\t"):
185 seen += 1
186 if seen == nth:
187 return ls + k, ls + k + len(tok), k + 1
188 pos = k + 1
189
190
191def eof_span(src):
192 a = len(src)
193 ls = src.rfind(b"\n") + 1
194 line = src.count(b"\n") + 1
195 return a, a, a - ls + 1, line
196
197
198def rec(code, sev, line, col=None, a=None, b=None, expect=None, found=None, obligation="-"):
199 f = ["omc-diag", "1", "code=%d" % code, "sev=%s" % sev, "line=%d" % line]
200 if col is not None:
201 f.append("col=%d" % col)
202 f.append("span=%d-%d" % (a, b))
203 if expect is not None:
204 f.append("expect=%s" % expect)
205 if found is not None:
206 f.append("found=%s" % found)
207 f += ["obligation=%s" % obligation, "profile=OM-2"]
208 return " ".join(f) + "\n"
209
210
211def found_of(src, a, b):
212 return src[a:b][:32].hex() if b > a else "-"
213
214
215def diag():
216 out = {}
217 # d-left: tokens left; offending token = first extra token "3"; parser wanted end of line.
218 s = rd("s1/d-left.om"); ln = line_of(s, b"ret")
219 a, b, col = span_of(s, ln, b"3")
220 out["d-left.err"] = human(ln, 5) + rec(5, "error", ln, col, a, b, "newline", found_of(s, a, b))
221 s = rd("s1/d-left-plain.om"); out["d-left-plain.err"] = human(line_of(s, b"ret"), 5)
222 # d-eof-left: same, input ends after the extra token -> still sev=error (no continuation fixes it)
223 s = rd("s1/d-eof-left.om"); ln = line_of(s, b"ret")
224 a, b, col = span_of(s, ln, b"3")
225 out["d-eof-left.err"] = human(ln, 5) + rec(5, "error", ln, col, a, b, "newline", found_of(s, a, b))
226 # d-eof-mid: input ends inside `ret add x`; a continuation (` 2\nend\n`) is accepted.
227 s = rd("s1/d-eof-mid.om"); a, b, col, ln = eof_span(s)
228 out["d-eof-mid.err"] = human(ln, 4) + rec(4, "incomplete", ln, col, a, b, "value", "-")
229 # d-eof-noend: the function has no end; EOF after the final LF: line = last line + 1, col 1;
230 # E6 Q2: expect=end, sev=incomplete.
231 s = rd("s1/d-eof-noend.om"); a, b, col, ln = eof_span(s)
232 assert col == 1
233 out["d-eof-noend.err"] = human(ln, 15) + rec(15, "incomplete", ln, col, a, b, "end", "-")
234 # d-mid-short: E6 Q2: the LF ending `ret add x` is the offending token, sev=error. OM-1 reports
235 # the human line one later (the end line). The record's line field (LF's line or the human N)
236 # and expect are not fixed by E4/E6, so the tok line omits them; col is A's column on A's line.
237 s = rd("s1/d-mid-short.om"); lret = line_of(s, b"ret")
238 starts = [0] + [i + 1 for i, c in enumerate(s) if c == 0x0A]
239 a = s.index(b"\n", starts[lret - 1]); b = a + 1
240 out["d-mid-short.tok"] = (human(lret + 1, 4) + "omc-diag 1 code=4 sev=error col=%d span=%d-%d "
241 "found=%s obligation=- profile=OM-2\n"
242 % (a - starts[lret - 1] + 1, a, b, found_of(s, a, b)))
243 assert found_of(s, a, b) == "0a"
244 # E6 Q2: bad or out-of-range literal -> expect=number.
245 for n, code, tok in (("d-hexupper", 6, b"0xFF"), ("d-hexrange", 8, b"0xffffffff"),
246 ("d-longtok", 6, b"0x0000000000000000000000000000000000000001")):
247 s = rd("s1/%s.om" % n); ln = line_of(s, tok)
248 a, b, col = span_of(s, ln, tok)
249 out[n + ".err"] = human(ln, code) + rec(code, "error", ln, col, a, b, "number", found_of(s, a, b))
250 s = rd("s1/d-hexupper-plain.om"); out["d-hexupper-plain.err"] = human(line_of(s, b"0xFF"), 6)
251 # E6 Q2: unknown name -> expect=name; incomplete call to an unread function -> callee span.
252 for n, code, tok in (("d-unknown-fn", 3, b"foo"), ("d-unknown-struct", 16, b"Pt"),
253 ("d-unknown-sparam", 16, b"Pt"), ("d-unknown-args", 3, b"g")):
254 s = rd("s1/%s.om" % n); ln = line_of(s, tok)
255 a, b, col = span_of(s, ln, tok)
256 out[n + ".err"] = human(ln, code) + rec(code, "unknown", ln, col, a, b, "name", found_of(s, a, b))
257 assert len(bytes.fromhex(out["d-longtok.err"].split("found=")[1].split()[0])) == 32
258 return out
259
260
261def text_bytes(lit):
262 """Bytes of a text literal per OMEGESE.md 9.4: \\n 10, \\t 9, \\\\ 92, \\" 34."""
263 assert lit[:1] == b'"' and lit[-1:] == b'"'
264 body, out, i = lit[1:-1], bytearray(), 0
265 esc = {b"n": 10, b"t": 9, b"\\": 92, b'"': 34}
266 while i < len(body):
267 if body[i:i + 1] == b"\\":
268 out.append(esc[body[i + 1:i + 2]])
269 i += 2
270 else:
271 out.append(body[i])
272 i += 1
273 return bytes(out)
274
275
276def text_of(rel, name):
277 """Bytes of the text literal `name` declared in fixture rel (any spacing between the words)."""
278 ln = [l for l in rd(rel).split(b"\n") if l.split()[:2] == [b"text", name]][0]
279 return text_bytes(ln[ln.index(b'"'):ln.rindex(b'"') + 1])
280
281
282def x1_run():
283 # s2fmt/x1.om writes text msg to stdout and returns twice 0x15 (exit status, 9.1).
284 return text_of("s2fmt/x1.om", b"msg"), 2 * hexv("0x15")
285
286
287def x5_run():
288 # s2fmt/x5.om (OM-1) writes text m to stdout and returns 9.
289 return text_of("s2fmt/x5.om", b"m"), 9
290
291
292def main():
293 os.makedirs(EXP, exist_ok=True)
294 wr("names-fn.out", lines_out(names_fn()))
295 wr("names-var.out", lines_out(names_var()))
296 wr("hex-max.out", lines_out(hex_max()))
297 o, code = hex_places()
298 wr("hex-places.out", o)
299 assert code == 10
300 wr("om1-crlf.out", "42\n")
301 hdr = rd("s2fmt/hdr.txt")
302 assert hdr == b"om2 fmt\n"
303 for x in ("x1", "x2", "x3", "x4", "x5"):
304 src = rd("s2fmt/%s.om" % x)
305 e = fmt(src)
306 assert fmt(e) == e # idempotent (line 69)
307 wr("%s.fmt" % x, e)
308 assert rd("s2fmt/x2.om") == open(os.path.join(EXP, "x2.fmt"), "rb").read()
309 o, code = x1_run()
310 assert code == 42
311 wr("x1.out", o)
312 o, code = x5_run()
313 assert o == b"ok \n" and code == 9
314 wr("x5.out", o)
315 for k, v in diag().items():
316 wr(k, v)
317
318
319if __name__ == "__main__":
320 main()