json-model-compiler 2.0b0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. json_model/README.md +32 -0
  2. json_model/__init__.py +18 -0
  3. json_model/analyze.py +409 -0
  4. json_model/clang.py +563 -0
  5. json_model/convert.py +430 -0
  6. json_model/data/clang_entry.c +21 -0
  7. json_model/data/clang_free.c +10 -0
  8. json_model/data/clang_init.c +11 -0
  9. json_model/data/clang_pcre2_fun.c +6 -0
  10. json_model/data/clang_re2_fun.c +5 -0
  11. json_model/data/javascript_exe.js +4 -0
  12. json_model/data/javascript_foot.js +9 -0
  13. json_model/data/javascript_free.js +9 -0
  14. json_model/data/javascript_head.js +1 -0
  15. json_model/data/javascript_init.js +11 -0
  16. json_model/data/javascript_main.js +5 -0
  17. json_model/data/plpgsql_entry.sql +16 -0
  18. json_model/data/python_entry.py +11 -0
  19. json_model/data/python_exe.py +1 -0
  20. json_model/data/python_free.py +6 -0
  21. json_model/data/python_init.py +9 -0
  22. json_model/data/python_main.py +4 -0
  23. json_model/javascript.py +310 -0
  24. json_model/language.py +748 -0
  25. json_model/model.py +1084 -0
  26. json_model/mtypes.py +42 -0
  27. json_model/objmerge.py +165 -0
  28. json_model/optim.py +486 -0
  29. json_model/plpgsql.py +422 -0
  30. json_model/python.py +269 -0
  31. json_model/recurse.py +127 -0
  32. json_model/resolver.py +106 -0
  33. json_model/runtime/META.json +30 -0
  34. json_model/runtime/Makefile +21 -0
  35. json_model/runtime/__init__.py +32 -0
  36. json_model/runtime/json-model.c +1054 -0
  37. json_model/runtime/json-model.h +183 -0
  38. json_model/runtime/json_model--2.0.sql +261 -0
  39. json_model/runtime/json_model.control +2 -0
  40. json_model/runtime/main.c +473 -0
  41. json_model/runtime/support.py +485 -0
  42. json_model/runtime/types.py +16 -0
  43. json_model/script.py +585 -0
  44. json_model/url_cache.py +82 -0
  45. json_model/utils.py +623 -0
  46. json_model/xstatic.py +1444 -0
  47. json_model_compiler-2.0b0.dist-info/METADATA +201 -0
  48. json_model_compiler-2.0b0.dist-info/RECORD +51 -0
  49. json_model_compiler-2.0b0.dist-info/WHEEL +5 -0
  50. json_model_compiler-2.0b0.dist-info/entry_points.txt +2 -0
  51. json_model_compiler-2.0b0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,485 @@
1
+ from collections.abc import MutableMapping, MutableSet
2
+ import datetime
3
+ import time
4
+ import validators
5
+ import json
6
+ import re # FIXME re2?
7
+ import math
8
+
9
+ from json_model.runtime.types import Jsonable, JsonScalar, Report, Path, CheckFun
10
+
11
+ # special undefined value
12
+ def UNDEFINED(v, p, r):
13
+ raise Exception("must not be called")
14
+
15
+ # extract type name
16
+ def _tname(value: Jsonable) -> str:
17
+ return type(value).__name__
18
+
19
+ # maybe add message to report
20
+ def _rep(msg: str, rep: Report) -> bool:
21
+ _ = rep is None or rep.append((msg, []))
22
+ return False
23
+
24
+ # generate path for display
25
+ def _path(path: Path) -> str:
26
+ """Show path as a JSON Path (RFC9535), with proper escaping when necessary."""
27
+ if path is None:
28
+ return ""
29
+
30
+ def esc(item: str|int) -> str:
31
+ if isinstance(item, int):
32
+ return str(item)
33
+ elif item.isidentifier():
34
+ return item
35
+ else:
36
+ items = item.split("'")
37
+ return "'" + "\\'".join(i.replace("\\", "\\\\") for i in items) + "'"
38
+
39
+ return "." + ".".join(map(esc, path))
40
+
41
+ #
42
+ # TYPED VALUES MANAGEMENT
43
+ #
44
+ def typed_eq(v1: Jsonable, v2: Jsonable):
45
+ if type(v1) is not type(v2):
46
+ return False
47
+ if v1 is None:
48
+ return True
49
+ elif isinstance(v1, (bool, int, float, str)):
50
+ return v1 == v2
51
+ elif isinstance(v1, list):
52
+ return len(v1) == len(v2) and all(typed_eq(i1, i2) for i1, i2 in zip(v1, v2)) # pyright: ignore
53
+ else:
54
+ assert isinstance(v1, dict)
55
+ if len(v1) != len(v2) or set(v1.keys()) != set(v2.keys()): # type: ignore
56
+ return False
57
+ # same props, compare values
58
+ return all(typed_eq(v1[p], v2[p]) for p in v1) # pyright: ignore
59
+
60
+
61
+ class Const:
62
+ """A constant holder suitable for set/dict, with a stricly typed comparison.
63
+
64
+ The point is to avoid 1 == 1.0 == True, 0 == 0.0 == False, n == n.0
65
+ """
66
+
67
+ def __init__(self, val: JsonScalar):
68
+ self._val = val
69
+
70
+ def __hash__(self):
71
+ return hash(self._val)
72
+
73
+ def __eq__(self, val):
74
+ return (
75
+ isinstance(val, Const) and
76
+ type(self._val) is type(val._val) and
77
+ self._val == val._val
78
+ )
79
+
80
+
81
+ class ConstSet(MutableSet[JsonScalar]):
82
+ """A set of constants, with strictly typed comparisons."""
83
+
84
+ def __init__(self, init: list[JsonScalar]|str|None = None):
85
+ self._set: set[Const] = set()
86
+ if init:
87
+ for item in init:
88
+ self.add(item)
89
+
90
+ def __len__(self):
91
+ return len(self._set)
92
+
93
+ def __iter__(self):
94
+ return map(lambda i: i._val, self._set)
95
+
96
+ def __contains__(self, item):
97
+ return Const(item) in self._set
98
+
99
+ def add(self, value):
100
+ self._set.add(Const(value))
101
+
102
+ def discard(self, value):
103
+ self._set.discard(Const(value))
104
+
105
+
106
+ class ConstMap(MutableMapping[JsonScalar, CheckFun]):
107
+ """A mapping of constants to check functions."""
108
+
109
+ def __init__(self):
110
+ self._map: dict[Const, CheckFun] = {}
111
+
112
+ def __setitem__(self, key, val):
113
+ self._map[Const(key)] = val
114
+
115
+ def __getitem__(self, key):
116
+ if isinstance(key, (list, dict)):
117
+ return UNDEFINED # pyright: ignore
118
+ else:
119
+ return self._map[Const(key)]
120
+
121
+ def __delitem__(self, key):
122
+ del self._map[Const(key)]
123
+
124
+ def __iter__(self):
125
+ return map(lambda k: k._val, self._map)
126
+
127
+ def __len__(self):
128
+ return self._map.__len__()
129
+
130
+ #
131
+ # PREDEFS HELPERS
132
+ #
133
+
134
+ def is_valid_date(value: Jsonable, path: Path, rep: Report = None) -> bool:
135
+ if isinstance(value, str):
136
+ try:
137
+ datetime.date.fromisoformat(value)
138
+ return True
139
+ except Exception as e:
140
+ _ = rep is None or rep.append((f"invalid date {value} ({e})", path))
141
+ return False
142
+ _ = rep is None or rep.append((f"incompatible type {_tname(value)} for date", path))
143
+ return False
144
+
145
+
146
+ def is_valid_time(value: Jsonable, path: Path, rep: Report = None) -> bool:
147
+ if isinstance(value, str):
148
+ try:
149
+ datetime.time.fromisoformat(value)
150
+ return True
151
+ except Exception as e:
152
+ _ = rep is None or rep.append((f"invalid time {value} ({e})", path))
153
+ return False
154
+ _ = rep is None or rep.append((f"incompatible type {_tname(value)} for time", path))
155
+ return False
156
+
157
+
158
+ def is_valid_datetime(value: Jsonable, path: Path, rep: Report = None) -> bool:
159
+ if isinstance(value, str):
160
+ try:
161
+ datetime.datetime.fromisoformat(value)
162
+ return True
163
+ except Exception as e:
164
+ _ = rep is None or rep.append((f"invalid datetime {value} ({e})", path))
165
+ return False
166
+ _ = rep is None or rep.append((f"incompatible type {_tname(value)} for datetime", path))
167
+ return False
168
+
169
+
170
+ def value_len(value: Jsonable, path: Path) -> None|bool|int|float:
171
+ match value:
172
+ case str()|list()|dict():
173
+ return len(value)
174
+ case _:
175
+ # FIXME should error out on None|bool?
176
+ return value
177
+
178
+
179
+ _UUID_RE = r"(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
180
+ _UUID_SEARCH = re.compile(_UUID_RE).search
181
+
182
+ def is_valid_uuid(value: Jsonable, path: Path, rep: Report = None) -> bool:
183
+ if isinstance(value, str):
184
+ if _UUID_SEARCH(value) is not None:
185
+ return True
186
+ else:
187
+ _ = rep is None or rep.append((f"str not an uuid {value}", path))
188
+ return False
189
+ else:
190
+ _ = rep is None or rep.append((f"incompatible type {_tname(value)} for uuid", path))
191
+ return False
192
+
193
+
194
+ def is_valid_url(value: Jsonable, path: Path, rep: Report = None) -> bool:
195
+ # NOTE urllib.parse accepts any garbage…
196
+ # NOTE simple_host required to accept "localhost"
197
+ # FIXME file:// is not a url…
198
+ valid = isinstance(value, str) and validators.url(value, simple_host=True) is True
199
+ if not valid:
200
+ _ = rep is None or rep.append((f"invalid url {value}", path))
201
+ return valid
202
+
203
+
204
+ def is_valid_email(value: Jsonable, path: Path, rep: Report = None) -> bool:
205
+ valid = isinstance(value, str) and validators.email(value) is True
206
+ if not valid:
207
+ _ = rep is None or rep.append((f"invalid email {value}", path))
208
+ return valid
209
+
210
+
211
+ # quite inefficient but safe
212
+ def is_valid_regex(value: Jsonable, path: Path, rep: Report = None) -> bool:
213
+ if isinstance(value, str):
214
+ try:
215
+ re.compile(value)
216
+ return True
217
+ except Exception as e:
218
+ _ = rep is None or rep.append((f"regex {value} compile error ({e})", path))
219
+ return False
220
+ # other types cannot be valid regex
221
+ _ = rep is None or rep.append((f"incompatible type for regex: {_tname(value)}", path))
222
+ return False
223
+
224
+
225
+ # extension: accept inlined reference syntax ($FOO:...)
226
+ def is_valid_exreg(value: Jsonable, path: Path, rep: Report = None) -> bool:
227
+ if isinstance(value, str):
228
+ # remplace references with named subpattern
229
+ count = 0
230
+ def repl(_):
231
+ nonlocal count
232
+ count += 1
233
+ return f"(P<x{count}>"
234
+ value = re.sub(r"\(\$\w+", repl, value)
235
+ return is_valid_regex(value, path, rep)
236
+
237
+
238
+ def is_unique_array(value: Jsonable, path: Path, rep: Report = None) -> bool:
239
+ if isinstance(value, list):
240
+ # that costs but works in all cases…
241
+ unique = len(set(json.dumps(i, sort_keys=True) for i in value)) == len(value)
242
+ if not unique:
243
+ _ = rep is None or rep.append(("non unique array", path))
244
+ return unique
245
+ # other types cannot be unique
246
+ _ = rep is None or rep.append(("non array for unique", path))
247
+ return False
248
+
249
+ def check_constraint(value: Jsonable, op: str, cst: int|float|str, path: Path, rep: Report) -> bool:
250
+ if value is None or isinstance(value, bool):
251
+ _ = rep is None or \
252
+ rep.append((f"unexpected type {_tname(value)} for {op} constraint", path))
253
+ # get comparison value depending on constant cst type
254
+ if isinstance(cst, int):
255
+ if isinstance(value, (str, list, dict)):
256
+ cval = len(value)
257
+ elif isinstance(value, (int, float)):
258
+ cval = value
259
+ else:
260
+ _ = rep is None or \
261
+ rep.append((f"unexpected type {_tname(value)} for {op} int constraint", path))
262
+ return False
263
+ elif isinstance(cst, float):
264
+ if isinstance(value, (int, float)):
265
+ cval = value
266
+ else: # list, dict, str
267
+ _ = rep is None or \
268
+ rep.append((f"unexpected type {_tname(value)} for {op} float constraint", path))
269
+ return False
270
+ else:
271
+ assert isinstance(cst, str)
272
+ if isinstance(value, str):
273
+ cval = value
274
+ else: # dict, list, int, float
275
+ _ = rep is None or \
276
+ rep.append((f"unexpected type {_tname(value)} for {op} str constraint", path))
277
+ return False
278
+ # actual comparison
279
+ if op == "=":
280
+ cmp = cval == cst
281
+ elif op == "!=":
282
+ cmp = cval != cst
283
+ elif op == "<=":
284
+ cmp = cval <= cst # pyright: ignore
285
+ elif op == "<":
286
+ cmp = cval < cst # pyright: ignore
287
+ elif op == ">=":
288
+ cmp = cval >= cst # pyright: ignore
289
+ elif op == ">":
290
+ cmp = cval > cst # pyright: ignore
291
+ else:
292
+ assert False, f"unexpected operator: {op}"
293
+ if not cmp and rep is not None:
294
+ rep.append((f"invalid {op} {cst} constraint", path))
295
+ return cmp
296
+
297
+
298
+ def main(jm_fun, jm_map, jmc_version):
299
+ """Possibly run as a script: $0 values..."""
300
+
301
+ import json
302
+ import sys
303
+ import argparse
304
+ import logging
305
+
306
+ logging.basicConfig()
307
+ log = logging.getLogger("checker")
308
+
309
+ ap = argparse.ArgumentParser()
310
+ ap.add_argument("--debug", "-d", action="store_true", help="set verbose mode")
311
+ ap.add_argument("--name", "-n", default="", help="select model by name")
312
+ ap.add_argument("--list", "-l", action="store_true", help="show available model names and exit")
313
+ ap.add_argument("--version", "-v", action="store_true", help="show JSON Model compiler version")
314
+ ap.add_argument("--report", "-r", action="store_true", help="show error locations on failure")
315
+ ap.add_argument("--time", "-T", type=int, default=1, help="report performance measures")
316
+ ap.add_argument("--test", "-t", action="store_true", help="assume test vector JSON files")
317
+ ap.add_argument("--jsonl", action="store_true", default=False, help="assume JSONL files")
318
+ ap.add_argument("--jsonschema-benchmark", action="store_true", default=False,
319
+ help="specific JSON Schema Benchmark run")
320
+ ap.add_argument("values", nargs="*", help="JSON files")
321
+ args = ap.parse_args()
322
+
323
+ log.setLevel(logging.DEBUG if args.debug else logging.INFO)
324
+
325
+ if args.list:
326
+ print(f"JSON Models (empty for root):{' '.join(sorted(jm_map.keys()))}")
327
+ sys.exit(0)
328
+ if args.version:
329
+ print(f"Python from JSON Model compiler version {jmc_version}")
330
+ sys.exit(0)
331
+ if args.jsonschema_benchmark:
332
+ args.jsonl = True
333
+
334
+ errors = 0
335
+
336
+ for fn in args.values:
337
+
338
+ try:
339
+ # load json data
340
+ if args.jsonl:
341
+ with open(fn) as f:
342
+ values = [json.loads(r) for r in f]
343
+ else:
344
+ with open(fn) as f:
345
+ value = json.load(f)
346
+ values = value if args.test else [ [ None, value ] ]
347
+
348
+ # benckmarking
349
+ if args.jsonschema_benchmark:
350
+
351
+ checker = jm_fun(args.name)
352
+
353
+ # cold run in µs
354
+ cold_start = time.clock_gettime(time.CLOCK_REALTIME)
355
+ for v in values:
356
+ if not checker(v, None, None):
357
+ errors += 1
358
+ cold_delay = 1_000_000.0 * (time.clock_gettime(time.CLOCK_REALTIME) - cold_start)
359
+
360
+ # more runs to trigger a potential JIT?
361
+ # NOTE probaly useless: JIT should be triggered by previous loop
362
+ for _ in range(min(20, int(10_000_000.0 / cold_delay))):
363
+ for v in values:
364
+ checker(v, None, None)
365
+
366
+ # warm run in µs
367
+ sum1, sum2 = 0.0, 0.0
368
+ for _ in range(args.time):
369
+ start = time.clock_gettime(time.CLOCK_REALTIME)
370
+ for j in values:
371
+ checker(j, None, None)
372
+ delay = 1_000_000.0 * (time.clock_gettime(time.CLOCK_REALTIME) - start)
373
+ sum1 += delay
374
+ sum2 += delay * delay
375
+
376
+ # result
377
+ avg = sum1 / args.time
378
+ stdev = math.sqrt( sum2 / args.time - avg * avg)
379
+ print(f"py validation: pass={len(values)-errors} fail={errors} "
380
+ f"{avg:.03f} ± {stdev:.03f} µs", file=sys.stderr)
381
+
382
+ # cold-run-ns,warm-run-ns
383
+ print(f"{int(1000 * cold_delay)},{int(1000 * avg)}")
384
+ sys.exit(1 if errors else 0)
385
+
386
+ # else usual runs
387
+
388
+ if args.jsonl:
389
+ values = [[None, j] for j in values]
390
+
391
+ index = 0
392
+ for tvect in values:
393
+
394
+ if isinstance(tvect, str): # ignore strings as comments
395
+ continue
396
+
397
+ if not isinstance(tvect, list) or len(tvect) not in (2, 3):
398
+ log.error(f"unexpected test vector: {tvect}")
399
+ print("{fn}[{i}]: ERROR bad test vector")
400
+ errors += 1
401
+ continue
402
+
403
+ if len(tvect) == 2:
404
+ expect, val = tvect
405
+ name = args.name
406
+ else:
407
+ expect, name, val = tvect
408
+
409
+ info = "" if expect is None else f"[{index}]"
410
+
411
+ try:
412
+ checker: CheckFun = jm_fun(name)
413
+ except Exception as e:
414
+ log.debug(e, exc_info=args.debug)
415
+ log.error(f"no such model \"{name}\": {e}")
416
+ print(f"{fn}{info}: ERROR unexpected name {name}")
417
+ errors += 1
418
+ continue
419
+
420
+ valid: bool
421
+ empty, sum1, sum2 = 0.0, 0.0, 0.0
422
+
423
+ if args.time > 1:
424
+
425
+ # evaluate average overhead
426
+ for _ in range(args.time - 1):
427
+ start = time.clock_gettime(0)
428
+ end = time.clock_gettime(0)
429
+ empty += 1000000.0 * (end - start)
430
+ empty /= args.time
431
+
432
+ # evaluate validation time
433
+ if args.report:
434
+ for _ in range(args.time):
435
+ start = time.clock_gettime(0)
436
+ reasons, path = [], []
437
+ valid = checker(val, path, reasons)
438
+ del reasons
439
+ del path
440
+ end = time.clock_gettime(0)
441
+ delay = 1000000.0 * (end - start) - empty
442
+ sum1 += delay
443
+ sum2 += delay * delay
444
+ else:
445
+ for _ in range(args.time):
446
+ start = time.clock_gettime(0)
447
+ valid = checker(val, None, None)
448
+ end = time.clock_gettime(0)
449
+ delay = 1000000.0 * (end - start) - empty
450
+ sum1 += delay
451
+ sum2 += delay * delay
452
+
453
+ avg = sum1 / args.time
454
+ stdev = math.sqrt(sum2 / args.time - avg * avg)
455
+ print(f"{fn}{info}{' rep ' if args.report else ' nop '}"
456
+ f"{avg:.03f} ± {stdev:.03f} µs/call ({empty:.03f})",
457
+ file=sys.stderr)
458
+
459
+ # collect results for actual display
460
+ if args.report:
461
+ reasons, path = [], []
462
+ valid = checker(val, path, reasons)
463
+ else:
464
+ reasons, path = None, None
465
+ valid = checker(val, None, None)
466
+
467
+ if expect is not None and valid != expect:
468
+ print(f"{fn}{info}: ERROR unexpected {'PASS' if valid else 'FAIL'}")
469
+ errors += 1
470
+ elif valid:
471
+ print(f"{fn}{info}: PASS")
472
+ elif reasons:
473
+ msg = "; ".join(f"{_path(p)}: {m}" for m, p in reversed(reasons))
474
+ print(f"{fn}{info}: FAIL ({msg})")
475
+ else:
476
+ print(f"{fn}{info}: FAIL")
477
+
478
+ index += 1
479
+
480
+ except Exception as e:
481
+ log.debug(e, exc_info=args.debug)
482
+ print(f"{fn}: ERROR ({e})")
483
+ errors += 1
484
+
485
+ sys.exit(1 if errors else 0)
@@ -0,0 +1,16 @@
1
+ #
2
+ # type declarations for python jm runtime
3
+ #
4
+ from typing import Callable
5
+
6
+ type JsonScalar = None|bool|int|float|str
7
+ type Jsonable = JsonScalar|list[Jsonable]|dict[str, Jsonable]
8
+
9
+ type Path = list[int|str]|None
10
+ type Report = list[tuple[str, Path]]|None
11
+
12
+ type CheckFun = Callable[[Jsonable, Path, Report], bool]
13
+ type RegexFun = Callable[[str, Path, Report], bool]
14
+ type PropMap = dict[str, CheckFun]
15
+
16
+ type EntryCheckFun = Callable[[Jsonable, str, Report], bool]