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 / seed / json / tests / gen.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Deterministic corpus and expected outputs for seed/json (omega-mv #788). |
| 3 | |
| 4 | Read-only reference oracle and test harness, never part of the build: |
| 5 | * CPython json with its C scanner (json.loads, strict) and lexeme-preserving hooks |
| 6 | (parse_int / parse_float receive the exact number text, object_pairs_hook keeps member |
| 7 | order and duplicates, parse_constant refuses NaN / Infinity); |
| 8 | * CPython float() / repr() / struct for binary64 conversion and shortest text; |
| 9 | * json.encoder.c_encode_basestring for writer escaping. |
| 10 | RFC 8259 rules the oracle adds on top of CPython (documented in README.md): an input |
| 11 | CPython accepts is still refused when a string decodes to a lone surrogate (section 8.2), |
| 12 | when nesting exceeds the depth limit, when the input exceeds the size limit, or when the |
| 13 | token count exceeds the driver's tape. |
| 14 | |
| 15 | Usage: gen.py OUTDIR. Writes OUTDIR/cases.tsv (id, mode, arg2, arg3, kind) and per case |
| 16 | OUTDIR/<id>.in and OUTDIR/<id>.<mode>.want. kind `exact` compares bytes; kind `err` only |
| 17 | requires the driver to print a line starting `ERR ` (the parse was refused). |
| 18 | """ |
| 19 | def gate_require(condition, detail): |
| 20 | if not condition: |
| 21 | raise RuntimeError(detail) |
| 22 | |
| 23 | import json |
| 24 | import json.encoder |
| 25 | import json.scanner |
| 26 | import os |
| 27 | import random |
| 28 | import struct |
| 29 | import sys |
| 30 | from decimal import Decimal, getcontext |
| 31 | |
| 32 | sys.setrecursionlimit(20000) |
| 33 | sys.set_int_max_str_digits(0) |
| 34 | getcontext().prec = 4000 |
| 35 | gate_require(json.scanner.c_make_scanner is not None, "CPython C scanner required") |
| 36 | gate_require(json.encoder.c_encode_basestring is not None, "CPython C encoder required") |
| 37 | |
| 38 | MAXN = 4294967295 # js_init size limit: the tape stores offsets in 32-bit cells (json/growing) |
| 39 | DLIM = 512 # driver default depth limit |
| 40 | TAPE = 262144 # driver tape cells (jsdrv.om dvtape) |
| 41 | CAP = (TAPE - 16) // 4 # tokens the driver tape holds |
| 42 | DRVSRC = 524288 # driver input array (jsdrv.om dvsrc) |
| 43 | WCAP = 1048576 # driver writer array (jsdrv.om dvob) |
| 44 | GATEWAY = 300 * 1024 # gateway request body size |
| 45 | |
| 46 | |
| 47 | class Num(str): |
| 48 | """A number lexeme, exactly as written.""" |
| 49 | |
| 50 | |
| 51 | class Obj: |
| 52 | def __init__(self, pairs): |
| 53 | self.pairs = pairs |
| 54 | |
| 55 | |
| 56 | class Reject(Exception): |
| 57 | pass |
| 58 | |
| 59 | |
| 60 | def _const(s): |
| 61 | raise Reject(s) |
| 62 | |
| 63 | |
| 64 | def stream(v, out, d): |
| 65 | """Token lines in tape order; returns the maximum number of open containers.""" |
| 66 | if isinstance(v, Obj): |
| 67 | out.append("{%d" % len(v.pairs)) |
| 68 | m = d + 1 |
| 69 | for k, x in v.pairs: |
| 70 | out.append("K " + k.encode("utf-8").hex()) |
| 71 | m = max(m, stream(x, out, d + 1)) |
| 72 | out.append("}") |
| 73 | return m |
| 74 | if isinstance(v, list): |
| 75 | out.append("[%d" % len(v)) |
| 76 | m = d + 1 |
| 77 | for x in v: |
| 78 | m = max(m, stream(x, out, d + 1)) |
| 79 | out.append("]") |
| 80 | return m |
| 81 | if isinstance(v, Num): |
| 82 | out.append("N " + v) |
| 83 | return d |
| 84 | if isinstance(v, str): |
| 85 | out.append("S " + v.encode("utf-8").hex()) |
| 86 | return d |
| 87 | if v is True: |
| 88 | out.append("T") |
| 89 | elif v is False: |
| 90 | out.append("F") |
| 91 | elif v is None: |
| 92 | out.append("Z") |
| 93 | else: |
| 94 | raise AssertionError(type(v)) |
| 95 | return d |
| 96 | |
| 97 | |
| 98 | def oracle(b, slim=MAXN, dlim=DLIM): |
| 99 | """(value, lines, depth) when the input must be accepted, else None.""" |
| 100 | if len(b) > slim: |
| 101 | return None |
| 102 | try: |
| 103 | s = b.decode("utf-8") |
| 104 | except UnicodeDecodeError: |
| 105 | return None |
| 106 | try: |
| 107 | v = json.loads(s, parse_int=Num, parse_float=Num, |
| 108 | parse_constant=_const, object_pairs_hook=Obj) |
| 109 | except (ValueError, Reject, RecursionError): |
| 110 | return None |
| 111 | lines = [] |
| 112 | try: |
| 113 | depth = stream(v, lines, 0) |
| 114 | except UnicodeEncodeError: |
| 115 | return None |
| 116 | if depth > dlim or len(lines) > CAP: |
| 117 | return None |
| 118 | return v, lines, depth |
| 119 | |
| 120 | |
| 121 | def canon(v, out): |
| 122 | if isinstance(v, Obj): |
| 123 | out.append("{") |
| 124 | for i, (k, x) in enumerate(v.pairs): |
| 125 | if i: |
| 126 | out.append(",") |
| 127 | out.append(json.encoder.c_encode_basestring(k)) |
| 128 | out.append(":") |
| 129 | canon(x, out) |
| 130 | out.append("}") |
| 131 | elif isinstance(v, list): |
| 132 | out.append("[") |
| 133 | for i, x in enumerate(v): |
| 134 | if i: |
| 135 | out.append(",") |
| 136 | canon(x, out) |
| 137 | out.append("]") |
| 138 | elif isinstance(v, Num): |
| 139 | out.append(str(v)) |
| 140 | elif isinstance(v, str): |
| 141 | out.append(json.encoder.c_encode_basestring(v)) |
| 142 | elif v is True: |
| 143 | out.append("true") |
| 144 | elif v is False: |
| 145 | out.append("false") |
| 146 | else: |
| 147 | out.append("null") |
| 148 | |
| 149 | |
| 150 | def nums(v, out): |
| 151 | if isinstance(v, Obj): |
| 152 | for _, x in v.pairs: |
| 153 | nums(x, out) |
| 154 | elif isinstance(v, list): |
| 155 | for x in v: |
| 156 | nums(x, out) |
| 157 | elif isinstance(v, Num): |
| 158 | out.append(str(v)) |
| 159 | |
| 160 | |
| 161 | def fline(lex): |
| 162 | x = float(lex) |
| 163 | bits = struct.pack(">d", x).hex() |
| 164 | if any(c in lex for c in ".eE"): |
| 165 | return "%s %s 0 -" % (repr(x), bits) |
| 166 | i = int(lex) |
| 167 | if abs(i) > 2**64 - 1: |
| 168 | return "%s %s 2 -" % (repr(x), bits) |
| 169 | if lex.startswith("-") and i < -2**63: |
| 170 | return "%s %s 1 -" % (repr(x), bits) |
| 171 | return "%s %s 1 %d" % (repr(x), bits, i) |
| 172 | |
| 173 | |
| 174 | class Corpus: |
| 175 | def __init__(self, outdir): |
| 176 | self.dir = outdir |
| 177 | self.rows = [] |
| 178 | self.n = 0 |
| 179 | os.makedirs(outdir, exist_ok=True) |
| 180 | |
| 181 | def _new(self, data): |
| 182 | self.n += 1 |
| 183 | cid = "c%05d" % self.n |
| 184 | with open(os.path.join(self.dir, cid + ".in"), "wb") as f: |
| 185 | f.write(data) |
| 186 | return cid |
| 187 | |
| 188 | def _want(self, cid, mode, data): |
| 189 | with open(os.path.join(self.dir, "%s.%s.want" % (cid, mode)), "wb") as f: |
| 190 | f.write(data) |
| 191 | |
| 192 | def parse(self, data, slim=None, dlim=None): |
| 193 | """All four parse modes, expected from the oracle.""" |
| 194 | s = MAXN if slim is None else slim |
| 195 | d = DLIM if dlim is None else dlim |
| 196 | a2 = "-" if slim is None else str(slim) |
| 197 | a3 = "-" if dlim is None else str(dlim) |
| 198 | if slim is None and dlim is not None: |
| 199 | a2 = str(MAXN) |
| 200 | cid = self._new(data) |
| 201 | r = oracle(data, s, d) |
| 202 | if r is None: |
| 203 | for mode in "twfr": |
| 204 | self._want(cid, mode, b"ERR\n") |
| 205 | self.rows.append((cid, mode, a2, a3, "err")) |
| 206 | return cid, False |
| 207 | v, lines, depth = r |
| 208 | toks = ("\n".join(lines) + "\nOK\n").encode() |
| 209 | self._want(cid, "t", toks) |
| 210 | self._want(cid, "w", toks) |
| 211 | nl = [] |
| 212 | nums(v, nl) |
| 213 | self._want(cid, "f", "".join(fline(x) + "\n" for x in nl).encode() + b"OK\n") |
| 214 | if depth > 1024: |
| 215 | self._want(cid, "r", b"WERR 25 0\n") |
| 216 | else: |
| 217 | out = [] |
| 218 | canon(v, out) |
| 219 | self._want(cid, "r", "".join(out).encode("utf-8")) |
| 220 | for mode in "twfr": |
| 221 | self.rows.append((cid, mode, a2, a3, "exact")) |
| 222 | return cid, True |
| 223 | |
| 224 | def pinned(self, data, want, slim=None, dlim=None): |
| 225 | """A refusal whose exact code and position are part of the contract (README).""" |
| 226 | s = MAXN if slim is None else slim |
| 227 | d = DLIM if dlim is None else dlim |
| 228 | gate_require(oracle(data, s, d) is None, ("oracle accepts pinned refusal", data[:40])) |
| 229 | a2 = str(s) |
| 230 | a3 = "-" if dlim is None else str(dlim) |
| 231 | cid = self._new(data) |
| 232 | for mode in "twfr": |
| 233 | self._want(cid, mode, want.encode() + b"\n") |
| 234 | self.rows.append((cid, mode, a2, a3, "exact")) |
| 235 | return cid |
| 236 | |
| 237 | def raw(self, mode, data, want, a2="-", a3="-"): |
| 238 | cid = self._new(data) |
| 239 | self._want(cid, mode, want) |
| 240 | self.rows.append((cid, mode, a2, a3, "exact")) |
| 241 | return cid |
| 242 | |
| 243 | def finish(self): |
| 244 | with open(os.path.join(self.dir, "cases.tsv"), "w") as f: |
| 245 | for row in self.rows: |
| 246 | f.write("\t".join(row) + "\n") |
| 247 | |
| 248 | |
| 249 | # ---------------------------------------------------------------- hand cases |
| 250 | |
| 251 | HAND = [ |
| 252 | b"null", b"true", b"false", b"0", b"-0", b"1", b"-1", b"12.5", b"1e5", b"1E+5", b"1e-5", |
| 253 | b"-0.0e-0", b'""', b'"a"', b"[]", b"{}", b" [ ] ", b"\t\n\r [1,2 ,3]\r\n", b'{"a":1,"a":2}', |
| 254 | b'{"":""}', b'[[[[]]]]', b'{"a":{"b":{"c":[1,{"d":null}]}}}', b'["\\"\\\\\\/\\b\\f\\n\\r\\t"]', |
| 255 | b'"\\u0000"', b'"\\u001f"', b'"\\u001F\\u00e9\\u00E9"', b'"\\u2028\\u2029"', b'"\\uD83D\\uDE00"', |
| 256 | b'"\\ud83d\\ude00"', b'"\\uDBFF\\uDFFF"', b'"\\uD800\\uDC00"', b'"\\uFFFF"', b'"\\uE000"', |
| 257 | '"é€😀\U0010ffff\ud7ff\ue000"'.encode("utf-8", "surrogatepass"), b'"\x7f"', b'"\xc2\x80"', |
| 258 | b'"\xdf\xbf"', b'"\xe0\xa0\x80"', b'"\xed\x9f\xbf"', b'"\xee\x80\x80"', b'"\xef\xbf\xbf"', |
| 259 | b'"\xf0\x90\x80\x80"', b'"\xf4\x8f\xbf\xbf"', b"123456789012345678901234567890", |
| 260 | b"18446744073709551615", b"18446744073709551616", b"-9223372036854775808", |
| 261 | b"-9223372036854775809", b"9223372036854775807", b"9223372036854775808", |
| 262 | b"1.7976931348623157e308", b"1.7976931348623158e308", b"1.7976931348623159e308", b"1e400", |
| 263 | b"-1e400", b"5e-324", b"2.4703282292062327e-324", b"2.4703282292062328e-324", b"1e-400", |
| 264 | b"2.2250738585072011e-308", b"2.2250738585072012e-308", b"9007199254740993", |
| 265 | b"9007199254740993.0000000000000000000000000000001", b"0.1", b"0.30000000000000004", |
| 266 | b"1e16", b"1e15", b"123456789012345680", b"0.0001", b"0.00001", b"1e999999999", |
| 267 | b"0e999999999", b"1e-999999999", b"100e-2", b"0.000000000000000000000000000000001e33", |
| 268 | # refused by the oracle as well |
| 269 | b"", b" ", b"[", b"]", b"{", b"[1,]", b"[,1]", b"{,}", b'{"a"}', b'{"a":}', b'{"a" 1}', |
| 270 | b"{1:2}", b"[1 2]", b"01", b"-01", b"00", b"1.", b".5", b"-", b"+1", b"1e", b"1e+", b"1.e5", |
| 271 | b"0x10", b"Infinity", b"-Infinity", b"NaN", b"nan", b"tru", b"truex", b"nul", b"nulll", |
| 272 | b"True", b"[True]", b'"abc', b'"\x01"', b'"\x1f"', b'"\t"', b'"\n"', b'"\\x"', b'"\\u12"', |
| 273 | b'"\\u12G4"', b'"\\U0041"', b'"\\ud800"', b'"\\udc00"', b'"\\ud800\\u0041"', b'"\\ud800x"', |
| 274 | b'"\\udbff\\udbff"', b'"\\ud800\\"', b'"\xc0\xaf"', b'"\xc1\xbf"', b'"\xe0\x80\x80"', |
| 275 | b'"\xe0\x9f\xbf"', b'"\xed\xa0\x80"', b'"\xed\xbf\xbf"', b'"\xf0\x80\x80\x80"', |
| 276 | b'"\xf0\x8f\xbf\xbf"', b'"\xf4\x90\x80\x80"', b'"\xf5\x80\x80\x80"', b'"\xff"', b'"\x80"', |
| 277 | b'"\xe2\x82"', b'"\xf0\x9f\x98"', b'"\xc2"', b"\xef\xbb\xbf{}", b"{} x", b"[] []", |
| 278 | b"[1]\x00", b"\x00", b"[1,2", b'{"a":1', b'["a\\', b"[\x0c]", b"[\xa0]", b"'a'", |
| 279 | b'{"a":1,}', b"[-]", b"[1.5e]", b"[0.e1]", b"/* */ 1", b"[1]//", |
| 280 | ] |
| 281 | |
| 282 | PINNED = [ |
| 283 | (b"", "ERR 1 0", None, None), |
| 284 | (b" ", "ERR 1 3", None, None), |
| 285 | (b"[", "ERR 1 1", None, None), |
| 286 | (b"[1,]", "ERR 2 3", None, None), |
| 287 | (b'{"a":1,}', "ERR 2 7", None, None), |
| 288 | (b"[1 2]", "ERR 2 3", None, None), |
| 289 | (b'{"a" 1}', "ERR 2 5", None, None), |
| 290 | (b"{1:2}", "ERR 2 1", None, None), |
| 291 | (b"+1", "ERR 2 0", None, None), |
| 292 | (b".5", "ERR 2 0", None, None), |
| 293 | (b"NaN", "ERR 2 0", None, None), |
| 294 | (b"\xef\xbb\xbf{}", "ERR 2 0", None, None), |
| 295 | (b"{} x", "ERR 3 3", None, None), |
| 296 | (b"[[[]]]", "ERR 4 2", None, 2), |
| 297 | (b"[1,2,3,4,5]", "ERR 5 10", 10, None), |
| 298 | (b'"\xc0\xaf"', "ERR 6 1", None, None), |
| 299 | (b'"\xed\xa0\x80"', "ERR 6 2", None, None), |
| 300 | (b'"\xf4\x90\x80\x80"', "ERR 6 2", None, None), |
| 301 | (b'"\xe2\x82"', "ERR 6 3", None, None), |
| 302 | (b'"\\udc00"', "ERR 7 1", None, None), |
| 303 | (b'"\\ud800"', "ERR 7 1", None, None), |
| 304 | (b'"\\ud800\\u0041"', "ERR 7 7", None, None), |
| 305 | (b'"\x01"', "ERR 8 1", None, None), |
| 306 | (b'"\t"', "ERR 8 1", None, None), |
| 307 | (b'"\\x"', "ERR 9 2", None, None), |
| 308 | (b'"\\u12"', "ERR 9 5", None, None), |
| 309 | (b"01", "ERR 10 1", None, None), |
| 310 | (b"1.", "ERR 10 2", None, None), |
| 311 | (b"-", "ERR 10 1", None, None), |
| 312 | (b"1e+", "ERR 10 3", None, None), |
| 313 | (b"[-]", "ERR 10 2", None, None), |
| 314 | (b"tru", "ERR 1 3", None, None), |
| 315 | (b"nul", "ERR 1 3", None, None), |
| 316 | (b"trux", "ERR 12 3", None, None), |
| 317 | (b'"abc', "ERR 1 4", None, None), |
| 318 | (b'["a\\', "ERR 1 4", None, None), |
| 319 | ] |
| 320 | |
| 321 | FLOATS = [ |
| 322 | "0", "-0", "0.0", "-0.0", "1", "-1", "0.1", "0.2", "0.3", "0.30000000000000004", "1e23", |
| 323 | "8.98846567431158e307", "1.7976931348623157e308", "1.7976931348623158e308", |
| 324 | "1.7976931348623159e308", "4.9406564584124654e-324", "2.4703282292062328e-324", |
| 325 | "2.4703282292062327e-324", "2.2250738585072011e-308", "2.2250738585072014e-308", |
| 326 | "2.225073858507201e-308", "9007199254740992", "9007199254740993", "9007199254740995", |
| 327 | "9007199254740994.9999999999999999999999999999999999", "123456789012345678901234567890", |
| 328 | "3.141592653589793238462643383279502884197169399375105820974944592307816406286", |
| 329 | "1e22", "1e21", "1e-7", "0.000123", "1234567890123456.7", "12345678901234567", |
| 330 | "4.35679015789893e-307", "7.3177701707893310e+15", "5e-324", "1e308", "1e-308", |
| 331 | ] |
| 332 | |
| 333 | |
| 334 | def doubles(R, n): |
| 335 | out = [] |
| 336 | while len(out) < n: |
| 337 | k = R.randrange(6) |
| 338 | if k == 0: |
| 339 | bits = R.getrandbits(64) |
| 340 | elif k == 1: |
| 341 | bits = R.getrandbits(52) | (R.randrange(1, 60) << 52) # subnormal-adjacent |
| 342 | elif k == 2: |
| 343 | bits = R.getrandbits(1) << 63 | R.getrandbits(52) # subnormal |
| 344 | elif k == 3: |
| 345 | bits = R.randrange(1, 2047) << 52 # powers of two |
| 346 | elif k == 4: |
| 347 | bits = (R.randrange(990, 1100) << 52) | R.getrandbits(52) # near 1 |
| 348 | else: |
| 349 | bits = (R.randrange(2000, 2047) << 52) | R.getrandbits(52) # huge |
| 350 | if (bits >> 52) & 2047 == 2047: |
| 351 | continue |
| 352 | out.append(struct.unpack(">d", struct.pack(">Q", bits))[0]) |
| 353 | return out |
| 354 | |
| 355 | |
| 356 | def nextup(x): |
| 357 | b = struct.unpack(">Q", struct.pack(">d", x))[0] |
| 358 | return struct.unpack(">d", struct.pack(">Q", b + 1))[0] |
| 359 | |
| 360 | |
| 361 | def dlex(d): |
| 362 | s = format(d, "e") |
| 363 | return s.replace("E", "e") |
| 364 | |
| 365 | |
| 366 | def float_lexemes(R): |
| 367 | out = list(FLOATS) |
| 368 | for x in doubles(R, 400): |
| 369 | out.append(repr(x)) |
| 370 | out.append("%.25e" % x) |
| 371 | out.append("%.17g" % x if "e" in "%.17g" % x or "." in "%.17g" % x else "%.17g.0" % x) |
| 372 | for x in doubles(R, 160): |
| 373 | x = abs(x) |
| 374 | y = nextup(x) |
| 375 | if y == float("inf"): |
| 376 | continue |
| 377 | mid = (Decimal(x) + Decimal(y)) / 2 |
| 378 | tiny = Decimal(x if x else y) * Decimal("1e-900") |
| 379 | out.append(dlex(mid)) |
| 380 | out.append(dlex(mid + tiny)) |
| 381 | out.append(dlex(mid - tiny)) |
| 382 | out.append("-" + dlex(mid)) |
| 383 | for lex in list(out): |
| 384 | gate_require(oracle(lex.encode()) is not None, lex) |
| 385 | return out |
| 386 | |
| 387 | |
| 388 | # ---------------------------------------------------------------- random documents |
| 389 | |
| 390 | CHARS = [chr(c) for c in range(0x20, 0x7f)] * 3 + [ |
| 391 | '"', "\\", "/", "\x00", "\x01", "\x08", "\x09", "\x0a", "\x0c", "\x0d", "\x1f", "\x7f", |
| 392 | "\x80", "é", "ß", "€", "\u2028", "\u2029", "\ufeff", "\uffff", "\ud7ff", "\ue000", |
| 393 | "😀", "\U00010000", "\U0010ffff", "中", "\u0300", |
| 394 | ] |
| 395 | SHORT = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", |
| 396 | "\t": "\\t", "/": "\\/"} |
| 397 | |
| 398 | |
| 399 | def uesc(R, cp): |
| 400 | h = "%04x" % cp |
| 401 | return "\\u" + (h.upper() if R.random() < 0.5 else h) |
| 402 | |
| 403 | |
| 404 | def enc_char(R, ch): |
| 405 | cp = ord(ch) |
| 406 | must = ch in '"\\' or cp < 0x20 |
| 407 | r = R.random() |
| 408 | if must or r < 0.15: |
| 409 | if ch in SHORT and R.random() < 0.6: |
| 410 | return SHORT[ch] |
| 411 | if cp > 0xFFFF: |
| 412 | v = cp - 0x10000 |
| 413 | return uesc(R, 0xD800 + (v >> 10)) + uesc(R, 0xDC00 + (v & 0x3FF)) |
| 414 | return uesc(R, cp) |
| 415 | return ch |
| 416 | |
| 417 | |
| 418 | def rstr(R): |
| 419 | s = "".join(R.choice(CHARS) for _ in range(R.randint(0, 10))) |
| 420 | return '"' + "".join(enc_char(R, c) for c in s) + '"' |
| 421 | |
| 422 | |
| 423 | def rnum(R): |
| 424 | s = "-" if R.random() < 0.3 else "" |
| 425 | if R.random() < 0.2: |
| 426 | s += "0" |
| 427 | else: |
| 428 | s += str(R.randint(1, 9)) + "".join(R.choice("0123456789") |
| 429 | for _ in range(R.choice([0, 1, 2, 5, 15, 19, 20, 25, 60]))) |
| 430 | if R.random() < 0.4: |
| 431 | s += "." + "".join(R.choice("0123456789") for _ in range(R.randint(1, 20))) |
| 432 | if R.random() < 0.3: |
| 433 | s += R.choice("eE") + R.choice(["", "+", "-"]) + str(R.randint(0, 400)) |
| 434 | return s |
| 435 | |
| 436 | |
| 437 | def ws(R): |
| 438 | if R.random() < 0.7: |
| 439 | return "" |
| 440 | return "".join(R.choice(" \t\n\r") for _ in range(R.randint(1, 3))) |
| 441 | |
| 442 | |
| 443 | def rval(R, d): |
| 444 | k = R.randrange(10 if d < 6 else 6) |
| 445 | if k == 0: |
| 446 | return R.choice(["true", "false", "null"]) |
| 447 | if k in (1, 2): |
| 448 | return rnum(R) |
| 449 | if k in (3, 4, 5): |
| 450 | return rstr(R) |
| 451 | if k in (6, 7): |
| 452 | items = [ws(R) + rval(R, d + 1) + ws(R) for _ in range(R.randint(0, 5))] |
| 453 | return "[" + ",".join(items) + "]" if items else "[" + ws(R) + "]" |
| 454 | items = [ws(R) + rstr(R) + ws(R) + ":" + ws(R) + rval(R, d + 1) + ws(R) |
| 455 | for _ in range(R.randint(0, 5))] |
| 456 | return "{" + ",".join(items) + "}" if items else "{" + ws(R) + "}" |
| 457 | |
| 458 | |
| 459 | INTEREST = list(b'{}[]:,"\\/ \t\n\r0123456789-+.eEtfnulasu') + [ |
| 460 | 0x00, 0x1F, 0x7F, 0x80, 0xBF, 0xC0, 0xC1, 0xC2, 0xDF, 0xE0, 0xED, 0xEF, 0xF0, 0xF4, 0xF5, 0xFF] |
| 461 | |
| 462 | |
| 463 | def mutate(R, b): |
| 464 | b = bytearray(b) |
| 465 | for _ in range(R.randint(1, 3)): |
| 466 | op = R.randrange(5) |
| 467 | if not b: |
| 468 | b.append(R.choice(INTEREST)) |
| 469 | continue |
| 470 | i = R.randrange(len(b)) |
| 471 | if op == 0: |
| 472 | b[i] = R.choice(INTEREST) |
| 473 | elif op == 1: |
| 474 | del b[i] |
| 475 | elif op == 2: |
| 476 | b.insert(i, R.choice(INTEREST)) |
| 477 | elif op == 3: |
| 478 | del b[i:] |
| 479 | else: |
| 480 | j = R.randrange(len(b)) |
| 481 | b[i:i] = b[j:j + R.randint(1, 4)] |
| 482 | return bytes(b) |
| 483 | |
| 484 | |
| 485 | def surrogate_doc(R): |
| 486 | parts = [] |
| 487 | for _ in range(R.randint(1, 4)): |
| 488 | k = R.randrange(4) |
| 489 | if k == 0: |
| 490 | parts.append(uesc(R, R.randrange(0xD800, 0xDC00))) |
| 491 | elif k == 1: |
| 492 | parts.append(uesc(R, R.randrange(0xDC00, 0xE000))) |
| 493 | elif k == 2: |
| 494 | parts.append(uesc(R, R.randrange(0xD800, 0xDC00)) + uesc(R, R.randrange(0xDC00, 0xE000))) |
| 495 | else: |
| 496 | parts.append(R.choice(["a", "\\n", "\\u0041", "é"])) |
| 497 | return ('["' + "".join(parts) + '"]').encode("utf-8") |
| 498 | |
| 499 | |
| 500 | def gateway(R): |
| 501 | head = '{"model":"omega-test","messages":[{"role":"system","content":"You are helpful."},' \ |
| 502 | '{"role":"user","content":"' |
| 503 | tail = '"}],"max_tokens":1024,"temperature":0.7,"stream":false}' |
| 504 | pool = list("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,;:!?") * 8 + \ |
| 505 | ["é", "€", "😀", "中", "\\n", "\\t", '\\"', "\\\\", "\\u00e9", "\\ud83d\\ude00", "\\/"] |
| 506 | body = [] |
| 507 | size = len(head.encode()) + len(tail.encode()) |
| 508 | while True: |
| 509 | p = R.choice(pool) |
| 510 | k = len(p.encode()) |
| 511 | if size + k > GATEWAY: |
| 512 | break |
| 513 | body.append(p) |
| 514 | size += k |
| 515 | body.append("x" * (GATEWAY - size)) |
| 516 | data = (head + "".join(body) + tail).encode() |
| 517 | gate_require(len(data) == GATEWAY, 'gate condition failed') |
| 518 | return data |
| 519 | |
| 520 | |
| 521 | # ---------------------------------------------------------------- writer scripts |
| 522 | |
| 523 | def wscript(R, v, lines): |
| 524 | if isinstance(v, Obj): |
| 525 | lines.append("o") |
| 526 | for k, x in v.pairs: |
| 527 | wstr(R, k, lines) |
| 528 | wscript(R, x, lines) |
| 529 | lines.append("O") |
| 530 | elif isinstance(v, list): |
| 531 | lines.append("a") |
| 532 | for x in v: |
| 533 | wscript(R, x, lines) |
| 534 | lines.append("A") |
| 535 | elif isinstance(v, Num): |
| 536 | lines.append("n" + v) |
| 537 | elif isinstance(v, str): |
| 538 | wstr(R, v, lines) |
| 539 | elif v is True: |
| 540 | lines.append("t") |
| 541 | elif v is False: |
| 542 | lines.append("f") |
| 543 | else: |
| 544 | lines.append("z") |
| 545 | |
| 546 | |
| 547 | def wstr(R, s, lines): |
| 548 | b = s.encode("utf-8") |
| 549 | if R.random() < 0.5: |
| 550 | lines.append("s" + b.hex()) |
| 551 | else: |
| 552 | lines.append("S") |
| 553 | lines.extend("b%02x" % c for c in b) |
| 554 | lines.append("E") |
| 555 | |
| 556 | |
| 557 | WPINNED = [ |
| 558 | ("z", "OK null"), ("o\nO", "OK {}"), ("a\nA", "OK []"), |
| 559 | ("o\ns61\nu1\ns62\na\nt\nf\nz\nA\nO", 'OK {"a":1,"b":[true,false,null]}'), |
| 560 | ("s" + b'"\\/\x08\x0c\n\r\t\x00\x1f\x7f'.hex(), |
| 561 | 'OK "\\"\\\\/\\b\\f\\n\\r\\t\\u0000\\u001f\x7f"'), |
| 562 | ("l-9223372036854775808", "OK -9223372036854775808"), ("l-1", "OK -1"), ("l0", "OK 0"), |
| 563 | ("u18446744073709551615", "OK 18446744073709551615"), ("u0", "OK 0"), |
| 564 | ("n-0.0e+00", "OK -0.0e+00"), ("a\nn1\nn-2.5E-3\nA", "OK [1,-2.5E-3]"), |
| 565 | ("n01", "ERR 24 0"), ("n1.", "ERR 24 0"), ("n", "ERR 24 0"), ("n1x", "ERR 24 0"), |
| 566 | ("n+1", "ERR 24 0"), ("d7ff8000000000000", "ERR 24 0"), ("d7ff0000000000000", "ERR 24 0"), |
| 567 | ("dfff0000000000000", "ERR 24 0"), ("z\nz", "ERR 22 0"), ("o\ns61\nO", "ERR 22 0"), |
| 568 | ("a\nO", "ERR 22 0"), ("O", "ERR 22 0"), ("a", "ERR 22 0"), ("", "ERR 22 0"), |
| 569 | ("o\nu1", "ERR 22 0"), ("S\nz", "ERR 22 0"), ("b41", "ERR 22 0"), ("E", "ERR 22 0"), |
| 570 | ("sc0af", "ERR 23 0"), ("seda080", "ERR 23 0"), ("sf4908080", "ERR 23 0"), |
| 571 | ("S\nbe2\nE", "ERR 23 0"), ("S\nb80\nE", "ERR 23 0"), ("S\nb41\nE", 'OK "A"'), |
| 572 | ("o\nS\nb61\nE\nS\nb62\nE\nO", 'OK {"a":"b"}'), |
| 573 | ("o\nsf09f9880\nsf09f9880\nO", 'OK {"\U0001F600":"\U0001F600"}'), |
| 574 | ("se280a8", 'OK "\u2028"'), ("a\nz\nz\nA", "OK [null,null]"), |
| 575 | ("o\ns\nz\ns\nz\nO", 'OK {"":null,"":null}'), |
| 576 | ] |
| 577 | |
| 578 | |
| 579 | def main(): |
| 580 | out = sys.argv[1] |
| 581 | R = random.Random(788) |
| 582 | C = Corpus(out) |
| 583 | for p in PINNED: |
| 584 | C.pinned(p[0], p[1], p[2], p[3]) |
| 585 | for b in HAND: |
| 586 | C.parse(b) |
| 587 | # limits: size and depth boundaries, token capacity, gateway body |
| 588 | C.parse(b"[" * DLIM + b"]" * DLIM) |
| 589 | C.pinned(b"[" * (DLIM + 1) + b"]" * (DLIM + 1), "ERR 4 %d" % DLIM) |
| 590 | C.parse(b"[" * 1100 + b"]" * 1100, dlim=1100) |
| 591 | C.parse(b'{"a":' * 700 + b"1" + b"}" * 700, dlim=1024) |
| 592 | C.parse(b"[1,2,3,4,5]", slim=11) |
| 593 | C.parse(b"[" + b"0," * (CAP - 3) + b"0]") |
| 594 | C.pinned(b"[" + b"0," * (CAP - 1) + b"0]", "ERR 11 %d" % (1 + 2 * (CAP - 1))) |
| 595 | g = gateway(R) |
| 596 | cid, ok = C.parse(g, slim=GATEWAY) |
| 597 | gate_require(ok, 'gate condition failed') |
| 598 | C.pinned(g, "ERR 5 %d" % (GATEWAY - 1), slim=GATEWAY - 1) |
| 599 | C.raw("t", b"1", b"INIT -13\n", str(MAXN + 1), "-") |
| 600 | C.raw("t", b"1", b"INIT -13\n", str(MAXN), "0") |
| 601 | C.raw("t", b"1", b"INIT -13\n", str(MAXN), "65536") |
| 602 | C.raw("t", b"1", b"INIT -13\n", "0", "-") |
| 603 | C.raw("t", b"[[1]]", b"[1\n[1\nN 1\n]\n]\nOK\n", str(MAXN), "65535") |
| 604 | # numbers: f64 parity with CPython float(), arrays of 40 lexemes per case |
| 605 | lex = float_lexemes(R) |
| 606 | for i in range(0, len(lex), 40): |
| 607 | C.parse(("[" + ",".join(lex[i:i + 40]) + "]").encode()) |
| 608 | # random valid documents and their mutants |
| 609 | docs = [] |
| 610 | for _ in range(700): |
| 611 | d = (ws(R) + rval(R, 0) + ws(R)).encode("utf-8", "surrogatepass") |
| 612 | docs.append(d) |
| 613 | C.parse(d) |
| 614 | for _ in range(900): |
| 615 | C.parse(mutate(R, R.choice(docs))) |
| 616 | for _ in range(150): |
| 617 | C.parse(surrogate_doc(R)) |
| 618 | # writer scripts |
| 619 | for script, want in WPINNED: |
| 620 | C.raw("a", script.encode(), want.encode("utf-8") + b"\n") |
| 621 | C.raw("a", ("a\n" * 1024 + "A\n" * 1024).encode(), b"OK " + b"[" * 1024 + b"]" * 1024 + b"\n") |
| 622 | C.raw("a", ("a\n" * 1025 + "A\n" * 1025).encode(), b"ERR 25 0\n") |
| 623 | C.raw("a", b"s68656c6c6f", b"ERR 21 0\n", "1045") |
| 624 | C.raw("a", b"s68656c6c6f", b'OK "hello"\n', "1047") |
| 625 | C.raw("a", b"z", b"ERR 26 0\n", "1040") |
| 626 | for x in doubles(R, 300) + [0.0, -0.0, 1e16, 1e15, 0.0001, 0.00001, 2.0**53, 5e-324, 0.1]: |
| 627 | bits = struct.pack(">d", x).hex() |
| 628 | C.raw("a", ("a\nd" + bits + "\nA").encode(), ("OK [" + repr(x) + "]\n").encode()) |
| 629 | for x in [-(2**63), -(2**63) + 1, -1, 0, 1, 2**63 - 1]: |
| 630 | C.raw("a", ("l%d" % x).encode(), ("OK %d\n" % x).encode()) |
| 631 | for d in docs[:400]: |
| 632 | r = oracle(d) |
| 633 | if r is None or r[2] > 1024: |
| 634 | continue |
| 635 | lines = [] |
| 636 | wscript(R, r[0], lines) |
| 637 | o = [] |
| 638 | canon(r[0], o) |
| 639 | C.raw("a", "\n".join(lines).encode(), b"OK " + "".join(o).encode("utf-8") + b"\n") |
| 640 | C.finish() |
| 641 | print("GEN cases=%d rows=%d" % (C.n, len(C.rows))) |
| 642 | |
| 643 | |
| 644 | if __name__ == "__main__": |
| 645 | main() |
| 646 |