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 / om / codec / parity / corpus.py

676 lines · 28508 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3"""corpus.py OUTDIR [--check-product DIR]: write the codec parity corpus (deterministic).
4corpus.py OUTDIR --tree ROOT: tree.pack and tree.list, every .omega/.osc/.bin file under ROOT/tests
5and ROOT/examples (not part of expected.txt: it follows the tree).
6
7Packs (records of u32 little-endian length + bytes):
8 decode.pack wire graphs for omega_graph_deserialize_binary: the product builder vectors, structured
9 graphs (every kind, payload shape, sort order, refusal and overread path), single-byte
10 mutants and truncations of valid graphs, random byte strings
11 text.pack inputs for omega_graph_parse_text
12 hexid.pack 129-byte records: a 65-byte window of a C string for omega_parse_hex_semantic_id, then
13 two 32-byte ids for omega_hex_semantic_id / omega_compare_semantic_id
14
15The graphs are built here from the C struct layouts (aarch64 LP64, see README); semantic ids are
16sha256 of the canonical encoding, following omega_canonical.c. --check-product DIR compares the
17three product-builder vectors with the files the C oracle's `emit` wrote into DIR.
18"""
19import hashlib
20import os
21import random
22import struct
23import sys
24
25KIND_VALUE, KIND_TYPE, KIND_OPERATION, KIND_RELATION, KIND_CONSTRAINT = 1, 2, 3, 4, 5
26KIND_MEMORY, KIND_EFFECT = 6, 8
27
28
29def u16be(v):
30 return struct.pack(">H", v & 0xFFFF)
31
32
33def u32be(v):
34 return struct.pack(">I", v & 0xFFFFFFFF)
35
36
37class Obj:
38 def __init__(self, kind, attrs=(), rels=(), consts=(), payload=b"", ver=None, extra=b"", magic=b"OMG0"):
39 self.kind = kind
40 self.attrs = list(attrs) # (raw key bytes, value bytes)
41 self.rels = list(rels) # (kind, 32-byte target)
42 self.consts = list(consts) # (kind, payload bytes)
43 self.payload = payload
44 self.ver = ver
45 self.extra = extra
46 self.magic = magic
47
48 def wire(self):
49 ver = self.ver if self.ver is not None else (2 if self.kind == KIND_EFFECT else 1)
50 b = bytearray(self.magic + bytes([ver & 255, self.kind & 255]))
51 b += u16be(len(self.attrs))
52 for k, v in self.attrs:
53 b += bytes([len(k)]) + k + u16be(len(v)) + v
54 b += u16be(len(self.rels))
55 for k, t in self.rels:
56 b += u16be(k) + t
57 b += u16be(len(self.consts))
58 for k, p in self.consts:
59 b += u16be(k) + u16be(len(p)) + p
60 b += u32be(len(self.payload)) + self.payload + self.extra
61 return bytes(b)
62
63 def canonical(self):
64 """omega_canonical_encode of the decoded object (keys end at their first NUL)."""
65 kind = self.kind & 255
66 b = bytearray(b"OMG0" + bytes([2 if kind == KIND_EFFECT else 1, kind]))
67 keys = [(k.split(b"\0")[0], v) for k, v in self.attrs]
68 keys = sorted(keys, key=lambda kv: kv[0])
69 b += u16be(len(keys))
70 for k, v in keys:
71 b += bytes([len(k)]) + k + u16be(len(v)) + v
72 rels = sorted(self.rels, key=lambda r: (r[0], r[1]))
73 b += u16be(len(rels))
74 for k, t in rels:
75 b += u16be(k) + t
76 cs = sorted(self.consts, key=lambda c: (c[0], c[1]))
77 b += u16be(len(cs))
78 for k, p in cs:
79 b += u16be(k) + u16be(len(p)) + p
80 b += u32be(len(self.payload)) + self.payload
81 return bytes(b)
82
83 def id(self):
84 c = self.canonical()
85 return hashlib.sha256(c).digest() if len(c) <= 4096 else bytes(32)
86
87
88def graph(objs, count=None, magic=b"OMGG", tail=b""):
89 b = bytearray(magic + u16be(len(objs) if count is None else count))
90 for o in objs:
91 w = o if isinstance(o, (bytes, bytearray)) else o.wire()
92 b += u32be(len(w)) + w
93 return bytes(b + tail)
94
95
96# ---- payload images (aarch64 LP64 layouts of omega_types.h) ----
97Z = bytes(32)
98
99
100def type_pl(tag, width=0, length=0, elem=Z):
101 return struct.pack("<IHxxI", tag, width & 0xFFFF, length & 0xFFFFFFFF) + elem
102
103
104def value_pl(type_id, byte_len, data=b""):
105 return type_id + struct.pack("<H", byte_len & 0xFFFF) + (data + bytes(64))[:64]
106
107
108def op_pl(opcode, overflow, type_id=Z, arity=0, inputs=(Z, Z, Z, Z), output=Z):
109 return struct.pack("<II", opcode, overflow) + type_id + bytes([arity]) + b"".join(inputs) + output + bytes(3)
110
111
112def apply_pl(op_id, n, operands=(Z, Z, Z, Z)):
113 return op_id + bytes([n & 255]) + b"".join((list(operands) + [Z] * 4)[:4])
114
115
116def effect_pl(res, opc, slot, gen, cref=Z, params=b"", plen=None):
117 plen = len(params) if plen is None else plen
118 return struct.pack(">HHIQ", res, opc, slot, gen) + cref + struct.pack(">H", plen) + (params + bytes(128))[:128]
119
120
121# ---- product builders (omega_core.c) ----
122def b_type(tag, width=0, length=0, elem=Z):
123 return Obj(KIND_TYPE, payload=type_pl(tag, width, length, elem))
124
125
126def b_val_uint(tid, width, val):
127 n = min(max((width + 7) // 8, 1), 64)
128 data = bytes(((val >> ((n - 1 - i) * 8)) & 255) if (n - 1 - i) * 8 < 64 else 0 for i in range(n))
129 return Obj(KIND_VALUE, payload=value_pl(tid, n, data))
130
131
132def b_op(opc, ov, tid):
133 return Obj(KIND_OPERATION, payload=op_pl(opc, ov, tid, 2, (tid, tid, Z, Z), tid))
134
135
136def b_apply(op, a, b):
137 return Obj(KIND_OPERATION, payload=apply_pl(op, 2, (a, b)))
138
139
140def product_vectors():
141 t = b_type(3, 32)
142 va, vb = b_val_uint(t.id(), 32, 7), b_val_uint(t.id(), 32, 11)
143 op = b_op(3, 1, t.id())
144 add = graph([t, va, vb, op, b_apply(op.id(), va.id(), vb.id())])
145 law = graph([Obj(KIND_CONSTRAINT, consts=[(6, bytes([0x40, 0, 0, 0, 0, 1, 0, 0]) + bytes(8)),
146 (9, bytes([0, 0, 0, 7]) + bytes(4))])])
147 u32 = b_type(3, 32)
148 bt = b_type(2)
149 sub = b_op(4, 3, u32.id())
150 v1 = b_val_uint(u32.id(), 32, 0xDEADBEEF)
151 allb = graph([u32, b_type(4, 16), b_type(5, 8), b_type(7, 0, 10, u32.id()), b_type(1), b_type(2),
152 b_type(14, 32), b_type(6, 8), b_type(11), bt,
153 Obj(KIND_VALUE, payload=value_pl(bt.id(), 1, b"\x01")),
154 Obj(KIND_VALUE, attrs=[(b"omega.param", b"\x00\x03")], payload=value_pl(u32.id(), 0)),
155 sub, v1, b_apply(sub.id(), v1.id(), v1.id()),
156 Obj(KIND_EFFECT, payload=effect_pl(1, 2, 3, 0x0123456789ABCDEF)),
157 Obj(KIND_RELATION, attrs=[(b"a_key", b"2"), (b"z_key", b"1")],
158 rels=[(8, u32.id()), (9, u32.id())])])
159 return {"u32_add_graph.bin": add, "physics_m3_law.bin": law, "builders_all.bin": allb}
160
161
162# ---- structured random graphs ----
163def rkey(r):
164 c = r.random()
165 if c < 0.05:
166 return b""
167 if c < 0.10:
168 return bytes([0]) + r.randbytes(r.randint(0, 5))
169 if c < 0.18:
170 n = r.randint(1, 8)
171 k = bytearray(r.randbytes(n))
172 k[r.randrange(n)] = 0
173 return bytes(k)
174 if c < 0.22:
175 return r.randbytes(63)
176 if c < 0.40:
177 return bytes(r.choice(b"abcz") for _ in range(r.randint(1, 3)))
178 if c < 0.50:
179 return bytes(r.randint(128, 255) for _ in range(r.randint(1, 4)))
180 return bytes(r.choice(b"abcdefghijklmnopqrstuvwxyz._0123456789") for _ in range(r.randint(1, 12)))
181
182
183def rattrs(r, big=False):
184 n = r.choice([0, 0, 1, 2, 3, 5, 8, 32]) if not big else r.randint(4, 32)
185 out = []
186 for _ in range(n):
187 vl = r.choice([0, 1, 2, 7, 64, 512]) if not big else r.randint(100, 512)
188 out.append((rkey(r), r.randbytes(vl)))
189 if out and r.random() < 0.3:
190 out.append(out[0])
191 return out[:32]
192
193
194def rrels(r, ids):
195 n = r.choice([0, 0, 0, 1, 2, 3, 6, 64])
196 out = []
197 for _ in range(n):
198 k = r.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 6, 0, 10, 65535, r.randrange(65536)]) if r.random() < 0.2 else r.randint(1, 9)
199 t = r.choice(ids) if ids and r.random() < 0.85 else r.randbytes(32)
200 out.append((k, t))
201 return out
202
203
204def rconsts(r):
205 n = r.choice([0, 0, 0, 1, 2, 4, 32])
206 out = []
207 for _ in range(n):
208 k = r.randint(1, 9) if r.random() < 0.9 else r.choice([0, 10, 255, 65535])
209 p = r.choice([b"", b"\x01", b"\x01\x02", r.randbytes(r.randint(0, 128)), b"\x01\x02\x03"])
210 out.append((k, p))
211 return out
212
213
214def rtype(r, ids, tids):
215 tag = r.choice([1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 11, 12, 13, 14, 14, 0, 15, 255, 0x100, 0x80000003])
216 width = r.choice([0, 1, 2, 7, 8, 16, 31, 32, 33, 64, 255, 256, 257, 65535, r.randrange(65536)])
217 length = r.choice([0, 1, 10, 65535, 65536, 0xFFFFFFFF])
218 elem = r.choice(tids + ids + [r.randbytes(32)]) if (tids or ids) else r.randbytes(32)
219 pl = type_pl(tag, width, length, elem)
220 if r.random() < 0.08:
221 pl = pl[:r.randint(0, 43)]
222 elif r.random() < 0.05:
223 pl = pl + r.randbytes(r.randint(1, 50))
224 return pl
225
226
227def rvalue(r, ids, tids, wid):
228 tid = r.choice(tids) if tids and r.random() < 0.85 else (r.choice(ids) if ids and r.random() < 0.5 else r.randbytes(32))
229 w = wid.get(tid)
230 bl = (w + 7) // 8 if w is not None and r.random() < 0.7 else r.choice([0, 1, 2, 4, 8, 9, 64, 65, 1000, 65535])
231 pl = value_pl(tid, bl, r.randbytes(64))
232 if r.random() < 0.06:
233 pl = pl[:r.randint(0, 97)]
234 elif r.random() < 0.1:
235 pl = pl + r.randbytes(r.randint(1, 300))
236 return pl
237
238
239def rop(r, ids, tids):
240 opc = r.randint(1, 16) if r.random() < 0.85 else r.choice([0, 17, 255, 0x10000])
241 ov = r.randint(1, 3) if r.random() < 0.85 else r.choice([0, 4, 0xFFFFFFFF])
242 t = r.choice(tids) if tids else Z
243 pl = op_pl(opc, ov, t, r.randint(0, 4), tuple(r.choice(tids or [Z]) for _ in range(4)), t)
244 if r.random() < 0.1:
245 pl = pl + r.randbytes(r.randint(1, 820))
246 return pl
247
248
249def rapply(r, ids, ops, vals):
250 op = r.choice(ops) if ops and r.random() < 0.85 else (r.choice(ids) if ids and r.random() < 0.5 else r.randbytes(32))
251 n = r.choice([0, 1, 2, 2, 2, 3, 4, 5, 255]) if r.random() < 0.9 else r.randrange(256)
252 pool = vals + ops
253 operands = [r.choice(pool) if pool and r.random() < 0.9 else r.randbytes(32) for _ in range(4)]
254 pl = apply_pl(op, n, operands)
255 if r.random() < 0.2:
256 pl = pl + r.randbytes(r.randint(1, 42))
257 return pl
258
259
260def reffect(r):
261 c = r.random()
262 if c < 0.75:
263 pl = r.randint(0, 128)
264 return effect_pl(r.randint(1, 65535), r.randrange(65536), r.randrange(1 << 32), r.randrange(1 << 64), r.randbytes(32), r.randbytes(pl))
265 if c < 0.80:
266 return effect_pl(0, 1, 1, 1)
267 if c < 0.85:
268 return effect_pl(1, 1, 1, 1, plen=r.randint(129, 65535))
269 if c < 0.90:
270 e = bytearray(effect_pl(1, 1, 1, 1, params=b"ab"))
271 e[50 + r.randint(2, 127)] = r.randint(1, 255)
272 return bytes(e)
273 if c < 0.95:
274 return r.randbytes(176)
275 return r.randbytes(r.choice([0, 1, 177, 179, 1024]))
276
277
278def structured(r, nobj):
279 objs, ids, tids, ops, vals, wid = [], [], [], [], [], {}
280 for _ in range(nobj):
281 c = r.random()
282 if c < 0.25:
283 o = Obj(KIND_TYPE, payload=rtype(r, ids, tids))
284 elif c < 0.45:
285 o = Obj(KIND_VALUE, payload=rvalue(r, ids, tids, wid))
286 elif c < 0.58:
287 o = Obj(KIND_OPERATION, payload=rop(r, ids, tids))
288 elif c < 0.70:
289 o = Obj(KIND_OPERATION, payload=rapply(r, ids, ops, vals))
290 elif c < 0.76:
291 o = Obj(KIND_EFFECT, payload=reffect(r))
292 elif c < 0.95:
293 o = Obj(r.choice([4, 5, 6, 7, 9, 10, 11]), payload=r.randbytes(r.choice([0, 0, 3, 44, 98, 161, 204, 1024])))
294 else:
295 o = Obj(r.choice([0, 12, 13, 200, 255]), payload=r.randbytes(r.randint(0, 50)))
296 if r.random() < 0.6:
297 o.attrs = rattrs(r)
298 if r.random() < 0.5:
299 o.rels = rrels(r, ids)
300 if r.random() < 0.3:
301 o.consts = rconsts(r)
302 if r.random() < 0.03:
303 o.attrs = rattrs(r, big=True)
304 if r.random() < 0.05:
305 o.extra = r.randbytes(r.randint(1, 20))
306 i = o.id()
307 objs.append(o)
308 if i != Z:
309 ids.append(i)
310 if o.kind == KIND_TYPE:
311 tids.append(i)
312 tag, w = struct.unpack("<IH", (o.payload + bytes(6))[:6])
313 if tag in (3, 4, 5):
314 wid[i] = w
315 elif o.kind == KIND_OPERATION:
316 ops.append(i)
317 elif o.kind == KIND_VALUE:
318 vals.append(i)
319 if r.random() < 0.1 and objs:
320 objs.append(objs[r.randrange(len(objs))])
321 return objs
322
323
324def clean(r, nobj):
325 """A graph that validates: types, values, operations, applies, relations, effects."""
326 objs = []
327 t32 = b_type(3, 32)
328 objs.append(t32)
329 tids = [t32.id()]
330 vals, ops = [], []
331 for _ in range(nobj):
332 c = r.random()
333 if c < 0.2:
334 w = r.randint(1, 256)
335 o = b_type(r.choice([3, 5]), w)
336 tids.append(o.id())
337 elif c < 0.45:
338 o = b_val_uint(t32.id(), 32, r.randrange(1 << 32))
339 vals.append(o.id())
340 elif c < 0.6:
341 o = b_op(r.randint(1, 16), r.randint(1, 3), r.choice(tids))
342 ops.append(o.id())
343 elif c < 0.75 and ops and vals:
344 o = b_apply(r.choice(ops), r.choice(vals), r.choice(vals + ops))
345 elif c < 0.85:
346 o = Obj(KIND_EFFECT, payload=effect_pl(r.randint(1, 9), r.randint(0, 9), r.randrange(99), r.randrange(1 << 64), params=r.randbytes(r.randint(0, 128))))
347 else:
348 o = Obj(KIND_RELATION, rels=[(r.randint(1, 9), r.choice(tids + vals + ops)) for _ in range(r.randint(1, 6))])
349 if r.random() < 0.3:
350 o.attrs = [(bytes(r.choice(b"abcxyz") for _ in range(r.randint(1, 6))), r.randbytes(r.randint(0, 9))) for _ in range(r.randint(1, 4))]
351 if r.random() < 0.2:
352 o.consts = [(r.randint(1, 9), r.randbytes(r.randint(0, 6))) for _ in range(r.randint(1, 4))]
353 objs.append(o)
354 return objs
355
356
357def cycle_graphs(r):
358 """DFS cycles reachable only through the apply-operand read past the 1024-byte payload into the next
359 object's attribute value (struct offset 106 + 23 = operand 35's window)."""
360 out = []
361 for variant in range(12):
362 a_pl = bytearray(r.randbytes(1024))
363 a_pl[0:8] = struct.pack("<II", r.randint(1, 16), r.randint(1, 3))
364 a_pl[32] = 255
365 a = Obj(KIND_OPERATION, payload=bytes(a_pl))
366 if variant % 3 == 0: # operand window hits A itself
367 tgt = a.id()
368 rest = []
369 elif variant % 3 == 1: # hits B, B's relation targets A
370 b = Obj(KIND_RELATION, rels=[(r.randint(1, 9), a.id())])
371 tgt = b.id()
372 rest = [b]
373 else: # hits a type: no cycle, but the walk follows the window
374 t = b_type(3, 8)
375 tgt = t.id()
376 rest = [t]
377 val = r.randbytes(23) + tgt + r.randbytes(r.randint(0, 100))
378 nxt = Obj(KIND_MEMORY, attrs=[(b"k", val)])
379 out.append(graph([a, nxt] + rest))
380 return out
381
382
383def overread_graphs(r):
384 """format_text reads a VALUE's bytes[byte_len] past the payload into the following objects/past the graph."""
385 out = []
386 t = b_type(3, 32)
387 for bl in [990, 991, 1000, 1500, 25000, 25990, 26000, 40000, 51944, 65535]:
388 v = Obj(KIND_VALUE, payload=value_pl(t.id(), bl, r.randbytes(64)) + r.randbytes(r.randint(0, 900)))
389 nxt = Obj(KIND_MEMORY, attrs=[(rkey(r) or b"k", r.randbytes(512)) for _ in range(3)], rels=[(1, t.id())],
390 consts=[(2, r.randbytes(128))], payload=r.randbytes(1024))
391 out.append(graph([t, v, nxt, nxt]))
392 out.append(graph([t, v]))
393 many = [b_type(3, 32)] + [Obj(KIND_MEMORY, payload=r.randbytes(10)) for _ in range(254)]
394 many.append(Obj(KIND_VALUE, payload=value_pl(many[0].id(), 65535, r.randbytes(64))))
395 out.append(graph(many))
396 return out
397
398
399def edge_graphs(r):
400 out = [b"", b"OMG", b"OMGG", b"OMGG\x00", b"OMGG\x00\x00", b"OMGG\x01\x00", b"OMGG\x01\x01",
401 b"OMGH\x00\x00", b"OMGG\x00\x01", b"OMGG\x00\x01\x00\x00\x00\x05OMG0\x01",
402 graph([], count=256), graph([], count=257), graph([Obj(1)] * 3, count=2),
403 graph([Obj(1)], tail=r.randbytes(100))]
404 o = Obj(KIND_VALUE).wire()
405 out.append(b"OMGG\x00\x01" + u32be(len(o) + 1000) + o)
406 out.append(b"OMGG\x00\x01" + u32be(len(o)) + o[:-1])
407 out.append(graph([Obj(KIND_VALUE, magic=b"OMG1")]))
408 for ver in range(4):
409 for kind in [0, 1, 8, 11, 12, 255]:
410 out.append(graph([Obj(kind, ver=ver, payload=effect_pl(1, 1, 1, 1) if kind == 8 else b"")]))
411 out.append(graph([Obj(KIND_MEMORY, attrs=[(r.randbytes(64), b"")])]))
412 out.append(graph([Obj(KIND_MEMORY, attrs=[(b"k", bytes(513))])]))
413 out.append(graph([Obj(KIND_MEMORY, attrs=[(b"k", b"")] * 33)]))
414 out.append(graph([Obj(KIND_MEMORY, rels=[(1, Z)] * 65)]))
415 out.append(graph([Obj(KIND_MEMORY, consts=[(1, b"")] * 33)]))
416 out.append(graph([Obj(KIND_MEMORY, consts=[(1, bytes(129))])]))
417 out.append(graph([Obj(KIND_MEMORY, payload=bytes(1025))]))
418 out.append(graph([Obj(KIND_MEMORY, payload=bytes(1024))]))
419 big = Obj(KIND_MEMORY, attrs=[(bytes([97 + i % 26]) * 20, r.randbytes(512)) for i in range(32)],
420 rels=[(r.randint(1, 9), r.randbytes(32)) for _ in range(64)],
421 consts=[(r.randint(1, 9), r.randbytes(128)) for _ in range(32)], payload=r.randbytes(1024))
422 out.append(graph([big]))
423 out.append(graph([big, b_type(3, 8)]))
424 t = b_type(3, 32)
425 full = [t] + [b_val_uint(t.id(), 32, i) for i in range(255)]
426 out.append(graph(full))
427 fat = [Obj(KIND_MEMORY, attrs=[(b"k", r.randbytes(400))] * 9) for _ in range(256)]
428 out.append(graph(fat))
429 for n in [1, 2, 3, 30]:
430 out.append(graph([Obj(KIND_MEMORY, attrs=[(bytes([97 + (i * 7) % 26]), bytes([i])) for i in range(n)])]))
431 return out
432
433
434def text_corpus(r):
435 base = ("// Non-canonical human representation\n"
436 "type U32 = UNSIGNED_INTEGER(32)\n"
437 "val a : U32 = 7\n"
438 "val b : U32 = 11\n"
439 "op add = ADD<U32>[WRAP]\n"
440 "apply res = add(a, b)\n")
441 out = [base.encode(), base.replace("ADD", "SUB").encode(), b"", b"\n", b"// only\n"]
442 nums = ["7", "0", "11", "0x1f", "0X1F", "0x", "0xg", "017", "08", "09", "-1", "-0x10", "+5", " \t\v\f\r\n 42",
443 "18446744073709551615", "18446744073709551616", "-18446744073709551616", "99999999999999999999999",
444 "4294967296", "4294967295", "0xffffffffffffffff1", "abc", "", "=3", "0777777777777777777777",
445 "01777777777777777777777", "02000000000000000000000", "- 5", "--5", "+-5", "0x7fffffff", "\x80",
446 "0b101", "0B11", "0b", "0b2", "-0b1", "0b" + "1" * 64, "0b1" + "0" * 64, "0b" + "1" * 33]
447 words = ["type", "val", "op", "apply", "types", "value", "opaque", "applyx", "//", "/", "x", " ", "\t"]
448 for _ in range(1200):
449 lines = []
450 for _ in range(r.randint(0, 14)):
451 w = r.choice(words)
452 c = r.random()
453 if w.startswith("type"):
454 lines.append(w + r.choice([" U32 = UNSIGNED_INTEGER(32)", " X = UNSIGNED_INTEGER(16)", "", " UNSIGNED_INTEGER(32"]))
455 elif w.startswith("val"):
456 lines.append(w + r.choice([" a : U32 = ", " = ", " b ", " c := "]) + r.choice(nums))
457 elif w.startswith("op"):
458 lines.append(w + r.choice([" add = ADD<U32>[WRAP]", " sub = SUB<U32>[WRAP]", " mul = MUL", " ADDSUB", ""]))
459 elif w.startswith("apply"):
460 lines.append(w + r.choice([" res = add(a, b)", "", " r"]))
461 else:
462 lines.append(w + r.choice(["comment", " UNSIGNED_INTEGER(32)", " ADD", " SUB", " = 9", ""]))
463 if c < 0.1:
464 lines[-1] = r.choice([" ", "\t", "\r", "\v", "\f", " \n"]) + lines[-1]
465 sep = r.choice(["\n", "\n", "\r\n", "\n\n"])
466 s = sep.join(lines)
467 if r.random() < 0.5:
468 s += "\n"
469 b = s.encode("latin-1")
470 if r.random() < 0.05 and b:
471 i = r.randrange(len(b))
472 b = b[:i] + b"\0" + b[i:]
473 out.append(b)
474 for n in [255, 256, 257, 300]:
475 out.append((base + "val c : U32 = 5\n" * n + "op ADD\n" * 3 + "apply x\n" * n).encode())
476 out.append(("type U32 = UNSIGNED_INTEGER(32)\n" * 300 + "val a = 1\nval b = 2\nop ADD\napply\n").encode())
477 out.append(("type U32 = UNSIGNED_INTEGER(32)\n" * 254 + "val a = 1\nval b = 2\nop ADD\nop SUB\napply\n").encode())
478 out.append(("type U32 = UNSIGNED_INTEGER(32)\n" * 253 + "val a = 1\nval b = 2\nop ADD\nop ADD\napply\napply\n").encode())
479 for _ in range(300):
480 out.append(r.randbytes(r.randint(0, 200)))
481 for _ in range(100):
482 out.append(bytes(r.choice(b"tyvalopplyADSUBN(32)=x0123456789 \n/") for _ in range(r.randint(0, 300))))
483 return out
484
485
486def hexid_corpus(r):
487 out = []
488 hx = "0123456789abcdefABCDEF"
489 pairs = [" 0", "+f", "-f", "-0", "+0", "0x", "0X", " -", " +", " ", "x1", "g0", "0g", "\t1", "\n2", "\v3", "\f4",
490 "\r5", "1 ", "+-", "-+", "- ", "\x801", "1\x80"]
491 for _ in range(6000):
492 c = r.random()
493 if c < 0.35:
494 s = "".join(r.choice(hx) for _ in range(64)).encode()
495 elif c < 0.75:
496 s = bytearray("".join(r.choice(hx) for _ in range(64)).encode("latin-1"))
497 for _ in range(r.randint(1, 3)):
498 i = r.randrange(32) * 2
499 p = r.choice(pairs).encode("latin-1")
500 s[i:i + 2] = p
501 s = bytes(s)
502 elif c < 0.85:
503 s = bytes(r.randint(1, 255) for _ in range(64))
504 else:
505 s = "".join(r.choice(hx) for _ in range(r.choice([0, 1, 62, 63, 65, 66, 100]))).encode()
506 if r.random() < 0.3 and s:
507 i = r.randrange(len(s))
508 s = s[:i] + b"\0" + s[i + 1:]
509 win = (s + b"\0" * 65)[:65]
510 a = r.randbytes(32)
511 d = r.random()
512 if d < 0.3:
513 b = a
514 elif d < 0.8:
515 b = bytearray(a)
516 b[r.randrange(32)] = r.randrange(256)
517 b = bytes(b)
518 else:
519 b = r.randbytes(32)
520 out.append(win + a + b)
521 return out
522
523
524def targeted(r):
525 """Every validate branch at its boundaries, and walks that are deep or revisit many duplicates."""
526 out = []
527 t32 = b_type(3, 32)
528 v32 = b_val_uint(t32.id(), 32, 5)
529 for tag in range(16):
530 for wd in [0, 1, 2, 31, 32, 33, 255, 256, 257]:
531 out.append(graph([b_type(tag, wd, 0, t32.id()), t32]))
532 for ln in [0, 65535, 65536]:
533 for elem in [t32.id(), v32.id(), r.randbytes(32)]:
534 out.append(graph([t32, v32, b_type(7, 0, ln, elem)]))
535 for tag in [1, 2, 3, 4, 5, 6, 14]:
536 for wd in [1, 7, 8, 9, 64, 256, 65535]:
537 t = b_type(tag, wd)
538 for bl in sorted({(wd + 7) // 8, (wd + 7) // 8 + 1, 0}):
539 out.append(graph([t, Obj(KIND_VALUE, payload=value_pl(t.id(), bl))]))
540 for opc in [0, 1, 16, 17]:
541 for ov in [0, 1, 3, 4]:
542 out.append(graph([t32, b_op(opc, ov, t32.id())]))
543 op = b_op(3, 1, t32.id())
544 rel = Obj(KIND_RELATION, rels=[(1, t32.id())])
545 for n in range(6):
546 for other in [v32.id(), op.id(), t32.id(), rel.id(), r.randbytes(32)]:
547 ops = [v32.id(), other, op.id(), other][:4]
548 out.append(graph([t32, v32, op, rel, Obj(KIND_OPERATION, payload=apply_pl(op.id(), n, ops))]))
549 for opid in [t32.id(), v32.id(), r.randbytes(32)]:
550 out.append(graph([t32, v32, Obj(KIND_OPERATION, payload=apply_pl(opid, 1, [v32.id()]))]))
551 chain = [Obj(KIND_RELATION, attrs=[(b"n", b"0")])]
552 for i in range(1, 200):
553 chain.append(Obj(KIND_RELATION, rels=[(6, chain[-1].id())], attrs=[(b"n", str(i).encode())]))
554 out.append(graph(list(reversed(chain))))
555 out.append(graph(chain))
556 xd = Obj(KIND_MEMORY, payload=b"dup")
557 rels = [Obj(KIND_RELATION, rels=[(r.randint(1, 9), xd.id()) for _ in range(64)], attrs=[(b"i", bytes([i]))]) for i in range(100)]
558 root = Obj(KIND_RELATION, rels=[(7, o.id()) for o in rels[:64]])
559 out.append(graph([root] + rels + [xd] * 120))
560 out.append(graph([xd] * 120 + rels + [root]))
561 return out
562
563
564def filler(n):
565 """A KIND_MEMORY object whose canonical encoding is exactly n bytes (16 <= n <= 4096)."""
566 attrs, left = [], n - 16
567 i = 0
568 while left > 518 + 1028:
569 attrs.append((b"a%02d" % i, bytes([i]) * 512))
570 left -= 518
571 i += 1
572 if left > 1024:
573 attrs.append((b"z", bytes(left - 1028)))
574 left = 1024
575 return Obj(KIND_MEMORY, attrs=attrs, payload=bytes(left))
576
577
578def boundary(r):
579 """Serialize totals around the 8192-byte product buffer, and format_text where a stale line length
580 equals the room left (the C's `w >= max_len - pos` at equality)."""
581 out = []
582 for total in range(8186, 8200):
583 a = 4089
584 b = total - 6 - 8 - a
585 g = graph([filler(a), filler(b)])
586 assert len(g) == total and len(filler(a).canonical()) == a and len(filler(b).canonical()) == b
587 out.append(g)
588 t = b_type(3, 32)
589 for m, val in [(45, 500), (45, 99), (45, 1000), (44, 500)]:
590 objs = [Obj(KIND_MEMORY) for _ in range(m)]
591 objs.append(Obj(KIND_VALUE, payload=value_pl(t.id(), 2, bytes([val >> 8 & 255, val & 255]))))
592 objs.append(Obj(KIND_OPERATION, payload=r.randbytes(r.choice([0, 160]))))
593 out.append(graph(objs))
594 return out
595
596
597def tree_files(root):
598 """Every .omega/.osc/.bin file under ROOT/tests and ROOT/examples, sorted by path."""
599 out = []
600 for top in ("tests", "examples"):
601 for dp, dn, fn in os.walk(os.path.join(root, top)):
602 for f in fn:
603 if f.endswith((".omega", ".osc", ".bin")):
604 out.append(os.path.relpath(os.path.join(dp, f), root))
605 return sorted(out)
606
607
608def pack(path, recs):
609 with open(path, "wb") as f:
610 for b in recs:
611 f.write(struct.pack("<I", len(b)) + b)
612 return len(recs), sum(len(b) for b in recs)
613
614
615def main():
616 args = sys.argv[1:]
617 if len(args) == 3 and args[1] == "--tree":
618 recs = tree_files(args[2])
619 n = pack(os.path.join(args[0], "tree.pack"), [open(os.path.join(args[2], f), "rb").read() for f in recs])
620 with open(os.path.join(args[0], "tree.list"), "w") as f:
621 f.write("\n".join(recs) + "\n")
622 print("tree.pack: %d records, %d bytes" % n)
623 return
624 if len(args) not in (1, 3) or (len(args) == 3 and args[1] != "--check-product"):
625 sys.exit(__doc__)
626 od = args[0]
627 os.makedirs(od, exist_ok=True)
628 r = random.Random(726_0001)
629 pv = product_vectors()
630 if len(args) == 3:
631 for name, b in pv.items():
632 got = open(os.path.join(args[2], name), "rb").read()
633 if got != b:
634 sys.exit("corpus.py: %s differs from the C product builders" % name)
635 print("product vectors: %d equal to the C builders' bytes" % len(pv))
636 dec = list(pv.values())
637 valid = list(pv.values())
638 dec += edge_graphs(r)
639 dec += cycle_graphs(r)
640 dec += overread_graphs(r)
641 dec += targeted(r)
642 dec += boundary(r)
643 for _ in range(300):
644 g = graph(clean(r, r.randint(0, 30)))
645 dec.append(g)
646 valid.append(g)
647 for _ in range(700):
648 dec.append(graph(structured(r, r.choice([1, 1, 2, 3, 5, 8, 12, 20, 40]))))
649 small = [g for g in valid if len(g) <= 4000]
650 for _ in range(2000):
651 g = bytearray(r.choice(small))
652 i = r.randrange(len(g))
653 g[i] = (g[i] + r.randint(1, 255)) & 255
654 dec.append(bytes(g))
655 for _ in range(300):
656 g = r.choice(small)
657 dec.append(g[:r.randrange(len(g))])
658 for _ in range(500):
659 dec.append(r.randbytes(r.randint(0, 300)))
660 for _ in range(300):
661 n = r.randint(0, 3)
662 b = bytearray(b"OMGG" + u16be(n))
663 for _ in range(n):
664 body = b"OMG0" + bytes([r.choice([1, 1, 2, r.randrange(256)]), r.choice([1, 2, 3, 6, 8, r.randrange(256)])]) + r.randbytes(r.randint(0, 120))
665 b += u32be(len(body) if r.random() < 0.9 else r.randint(0, 200)) + body
666 dec.append(bytes(b))
667 st = {}
668 st["decode"] = pack(os.path.join(od, "decode.pack"), dec)
669 st["text"] = pack(os.path.join(od, "text.pack"), text_corpus(r))
670 st["hexid"] = pack(os.path.join(od, "hexid.pack"), hexid_corpus(r))
671 for k, (n, b) in st.items():
672 print("%s.pack: %d records, %d bytes" % (k, n, b))
673
674
675if __name__ == "__main__":
676 main()