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
json_model/script.py ADDED
@@ -0,0 +1,585 @@
1
+ import os
2
+ import sys
3
+ import re
4
+ import json
5
+ import yaml
6
+ import logging
7
+ from importlib.metadata import version as pkg_version
8
+ from importlib.resources import files
9
+ import tempfile
10
+
11
+ from .mtypes import Jsonable, JsonSchema, ModelError
12
+ from .utils import log, tname
13
+ from .resolver import Resolver
14
+ from .model import JsonModel
15
+ from .xstatic import xstatic_compile
16
+ from . import optim, analyze, objmerge
17
+ from .runtime.types import EntryCheckFun, Report
18
+ from .runtime.support import _path as json_path
19
+
20
+ LANG = {
21
+ "c": "C",
22
+ "py": "Python",
23
+ "js": "JavaScript",
24
+ "plpgsql": "PL/pgSQL",
25
+ }
26
+
27
+ def process_model(model: JsonModel, *,
28
+ check: bool = True, merge: bool = True, optimize: bool = True,
29
+ debug: int = 0):
30
+ """Apply necessary preprocessing to JsonModel."""
31
+
32
+ # initial sanity check
33
+ assert model._is_head and model._is_root and model._models
34
+
35
+ all_models = list(sorted(model._models.values(), key=lambda m: m._id))
36
+
37
+ if debug or check:
38
+ for m in all_models:
39
+ if not analyze.valid(m):
40
+ raise ModelError(f"invalid initial model {m._id}")
41
+
42
+ # simplify before merging
43
+ if optimize:
44
+ for m in all_models:
45
+ optim.optimize(m)
46
+
47
+ # check after initial optimize
48
+ if debug or check:
49
+ # log.debug(json.dumps(model.toJSON(), sort_keys=True, indent=2))
50
+ for m in all_models:
51
+ if not analyze.valid(m):
52
+ raise ModelError(f"invalid optimized model {m._id}")
53
+
54
+ # merge in reverse order to move alts up before inlining?!
55
+ if merge:
56
+ for m in reversed(all_models):
57
+ objmerge.merge(m)
58
+
59
+ # optimize again?
60
+ if optimize:
61
+ for m in all_models:
62
+ optim.optimize(m)
63
+
64
+ # check after merge & optimize
65
+ if debug or check:
66
+ for m in all_models:
67
+ if not analyze.valid(m):
68
+ raise ModelError(f"invalid merged model {m._id}")
69
+
70
+
71
+ def model_from_json(
72
+ mjson: Jsonable, *, auto: bool = False,
73
+ debug: int = 0, murl: str = "",
74
+ check: bool = True, merge: bool = True, optimize: bool = True,
75
+ loose_int: bool|None = None, loose_float: bool|None = None,
76
+ resolver: Resolver|None = None) -> JsonModel:
77
+ """JsonModel instanciation from JSON data."""
78
+
79
+ if resolver is None:
80
+ resolver = Resolver()
81
+
82
+ # possibly add resolver mapping rule
83
+ if auto and (isinstance(mjson, dict) and "$" in mjson and \
84
+ isinstance(mjson["$"], dict) and "" in mjson["$"]):
85
+ url = mjson["$"][""]
86
+ assert isinstance(url, str), ".\"$\"." f" expects a string: {tname(url)}"
87
+ fn = re.sub(r"(\.model)?(\.js(on)?|\.yaml)?$", "", murl) # drop suffix
88
+ if debug:
89
+ log.debug(f"url={url} fn={fn}")
90
+ file = fn if "/" in fn else ("./" + fn)
91
+ if fn != url and file != url and "/" in url:
92
+ upref, uend = url.rsplit("/", 1)
93
+ fpref, fend = file.rsplit("/", 1)
94
+ if upref not in resolver._maps and uend == fend:
95
+ log.info(f"auto adding url map: {upref} -> {fpref}")
96
+ resolver._maps[upref] = fpref
97
+
98
+ jm = JsonModel(mjson, resolver, url=murl, debug=debug,
99
+ loose_int=loose_int, loose_float=loose_float)
100
+
101
+ if check or merge or optimize:
102
+ process_model(jm, check=check, merge=merge, optimize=optimize, debug=debug)
103
+
104
+ return jm
105
+
106
+
107
+ def model_from_url(murl: str, *, auto: bool = False, debug: int = 0,
108
+ check: bool = True, merge: bool = True, optimize: bool = True,
109
+ loose_int: bool|None = None, loose_float: bool|None = None,
110
+ resolver: Resolver|None = None, follow: bool = True) -> JsonModel:
111
+ """JsonModel instanciation from a URL."""
112
+
113
+ if resolver is None:
114
+ resolver = Resolver()
115
+
116
+ mjson = resolver(murl, follow=follow)
117
+
118
+ return model_from_json(mjson, murl=murl, auto=auto, debug=debug, resolver=resolver,
119
+ loose_int=loose_int, loose_float=loose_float,
120
+ check=check, merge=merge, optimize=optimize)
121
+
122
+
123
+ def model_from_str(mstring: str, *, auto: bool = False,
124
+ check: bool = True, merge: bool = True, optimize: bool = True,
125
+ loose_int: bool|None = None, loose_float: bool|None = None,
126
+ debug: int = 0, murl: str = "") -> JsonModel:
127
+ """JsonModel instanciation from a string."""
128
+
129
+ return model_from_json(json.loads(mstring), auto=auto, debug=debug, murl=murl,
130
+ loose_int=loose_int, loose_float=loose_float,
131
+ check=check, merge=merge, optimize=optimize)
132
+
133
+
134
+ # it is unclear if this tricks actually works
135
+ def _model_checker(jm: JsonModel, *, debug: bool = False):
136
+ code = xstatic_compile(jm, lang="py", debug=debug)
137
+ env = {}
138
+ exec(str(code), env)
139
+ env["check_model_init"]()
140
+ yield env["check_model"]
141
+ env["check_model_free"]()
142
+
143
+
144
+ def model_checker(jm: JsonModel, *, debug: bool = False) -> EntryCheckFun:
145
+ """Return an executable model checker from a JsonModel."""
146
+ return next(_model_checker(jm, debug=debug))
147
+
148
+
149
+ def model_checker_from_json(
150
+ mjson: Jsonable, *, auto: bool = False, debug: int = 0,
151
+ resolver: Resolver|None = None,
152
+ loose_int: bool|None = None, loose_float: bool|None = None,
153
+ ) -> EntryCheckFun:
154
+ """Return an executable model checker from a URL."""
155
+ jm = model_from_json(mjson, auto=auto, debug=debug, resolver=resolver,
156
+ loose_int=loose_int, loose_float=loose_float)
157
+ return model_checker(jm, debug=debug > 0)
158
+
159
+
160
+ def model_checker_from_url(
161
+ murl: str, *, auto: bool = False, debug: int = 0,
162
+ resolver: Resolver|None = None, follow: bool = True,
163
+ loose_int: bool|None = None, loose_float: bool|None = None,
164
+ ) -> EntryCheckFun:
165
+ """Return an executable model checker from a URL."""
166
+ jm = model_from_url(murl, auto=auto, debug=debug, resolver=resolver, follow=follow,
167
+ loose_int=loose_int, loose_float=loose_float)
168
+ return model_checker(jm, debug=debug > 0)
169
+
170
+
171
+ def create_model(murl: str, resolver: Resolver, *,
172
+ auto: bool = False, follow: bool = True, debug: int = 0,
173
+ check: bool = True, merge: bool = True, optimize: bool = True,
174
+ loose_int: bool|None = None, loose_float: bool|None = None) -> JsonModel:
175
+ """JsonModel instanciation without preprocessing."""
176
+ return model_from_url(murl, auto=auto, follow=follow, debug=debug, resolver=resolver,
177
+ loose_int=loose_int, loose_float=loose_float,
178
+ check=check, merge=merge, optimize=optimize)
179
+
180
+ DEFAULT_CC = "cc"
181
+ DEFAULT_CFLAGS = "-Wall -Wno-address -Wno-c23-extensions -Wno-unused-variable -Wno-unused-function -Ofast"
182
+ DEFAULT_LDFLAGS_PCRE2 = "-ljansson -lpcre2-8 -lm"
183
+ # pkgconf --libs cre2
184
+ DEFAULT_LDFLAGS_CRE2 = "-L/usr/local/lib -ljansson -lcre2 -lpthread -lre2 -lm"
185
+
186
+ def clang_compile(c_code: str, args):
187
+ """Generate an actual executable or object file."""
188
+
189
+ tmp_dir = os.environ.get("TMPDIR", "/dev/shm")
190
+
191
+ # source files
192
+ rt_dir = files("json_model.runtime")
193
+ lib = rt_dir.joinpath("json-model.c")
194
+ main = rt_dir.joinpath("main.c")
195
+
196
+ # compiler setings
197
+ env = os.environ.get
198
+ cc = args.cc or env("CC", DEFAULT_CC)
199
+ cflags = args.cflags or env("CFLAGS", DEFAULT_CFLAGS)
200
+ d_engine = "-DREGEX_ENGINE_PCRE2" if args.regex_engine == "pcre2" else "-DREGEX_ENGINE_RE2"
201
+ cppflags = args.cppflags or \
202
+ f"-I{rt_dir} -I/usr/local/linclude -DCHECK_FUNCTION_NAME=check_model {d_engine}"
203
+ if args.define:
204
+ cppflags = " ".join(f"-D{d}" for d in args.define) + " " + cppflags
205
+ if args.include:
206
+ cppflags = " ".join(f"-I {i}" for i in args.include) + " " + cppflags
207
+ ldflags = args.ldflags or \
208
+ (DEFAULT_LDFLAGS_PCRE2 if args.regex_engine == "pcre2" else DEFAULT_LDFLAGS_CRE2)
209
+ if args.library:
210
+ ldflags = " -L".join([""] + args.library) + " " + ldflags
211
+
212
+ output = "a.out" if args.output == "-" else args.output
213
+
214
+ with tempfile.NamedTemporaryFile(dir=tmp_dir, suffix=".c") as tmp:
215
+ tmp.write(c_code.encode("UTF-8"))
216
+ tmp.flush()
217
+ if args.gen == "exec":
218
+ command = f"{cc} {cppflags} {cflags} -o {output} {main} {lib} {tmp.name} {ldflags}"
219
+ else:
220
+ command = f"{cc} {cppflags} {cflags} -o {output} -c {tmp.name}"
221
+ status = os.system(command)
222
+ assert status == 0, f"C compilation succeeded: {command}"
223
+
224
+ def jmc_script():
225
+
226
+ import argparse
227
+
228
+ logging.basicConfig()
229
+
230
+ ap = argparse.ArgumentParser(
231
+ prog="jmc",
232
+ description="""JSON Model is a compact and intuitive JSON syntax to describe JSON data
233
+ structures. This JSON Model Compiler command allows to derive codes or schemas from
234
+ a model. See https://github.com/clairey-zx81/json-model for details.""",
235
+ epilog="This code is Public Domain."
236
+ )
237
+ arg = ap.add_argument
238
+
239
+ # verbosity and checks
240
+ arg("--version", action="store_true", help="show current version and exit")
241
+ arg("--debug", "-d", default=0, action="count", help="increase debugging verbosity")
242
+ arg("--verbose", "-v", action="store_true", help="more verbose")
243
+ arg("--quiet", "-q", dest="verbose", action="store_false", help="less verbose")
244
+
245
+ # input options
246
+ arg("--maps", "-m", action="append", default=[], help="URL mappings")
247
+ arg("--auto", "-a", action="store_true", help="automatic URL mapping")
248
+
249
+ arg("--loose-int", "-li", action="store_true", default=None,
250
+ help="use loose integers")
251
+ arg("--strict-int", "-si", dest="loose_int", action="store_false", default=None,
252
+ help="use strict integers (default)")
253
+ arg("--loose-float", "-lf", action="store_true", default=None,
254
+ help="use loose floats")
255
+ arg("--strict-float", "-sf", dest="loose_float", action="store_false",
256
+ help="use strict floats (default)")
257
+ arg("--loose-number", "-ln", action="store_true", default=None,
258
+ help="use loose integer and float numbers")
259
+ arg("--strict-number", "-sn", dest="loose_number", action="store_false",
260
+ help="use strict integer and float numbers (default)")
261
+
262
+ # output options
263
+ arg("--output", "-o", default="-", help="output file")
264
+ arg("--entry", "-e", default="check_model", help="name prefix of generated functions")
265
+ arg("--regex-engine", "-re", default=None, choices=["re", "re2", "pcre2"],
266
+ help="select regular expression engine (default depends on target language)")
267
+ arg("--sort", "-s", action="store_true", default=False, help="sorted JSON keys")
268
+ arg("--no-sort", "-ns", dest="sort", action="store_false", help="unsorted JSON keys")
269
+ arg("--indent", "-i", type=int, default=2, help="JSON indentation")
270
+ arg("--reporting", action="store_true", default=None,
271
+ help="add reporting capabilities (default)")
272
+ arg("--no-reporting", dest="reporting", action="store_false",
273
+ help="remove reporting capabilities")
274
+
275
+ arg("--executable", dest="gen", default=None, action="store_const", const="exec",
276
+ help="generate an executable")
277
+ arg("--module", dest="gen", action="store_const", const="module", help="generate a module")
278
+ arg("--code", dest="gen", action="store_const", const="source", help="generate source code")
279
+ arg("--no-gen", "-ng", dest="gen", action="store_const", const="none",
280
+ help="do not generate anything")
281
+
282
+ # TODO cpp ts rs go…
283
+ arg("--format", "-F", choices=["json", "yaml", "py", "c", "js", "plpgsql"], default=None,
284
+ help="output language")
285
+
286
+ arg("--cc", type=str, help="override default C language compiler")
287
+ arg("--cflags", type=str, help="override C compiler flags")
288
+ arg("--cppflags", type=str, help="override C pre-processor flags")
289
+ arg("--ldflags", type=str, help="override C linker flags for executable")
290
+ arg("--include", "-I", nargs="*", default=[], help="add include directory")
291
+ arg("--library", "-L", nargs="*", default=[], help="add library directory")
292
+ arg("--define", "-D", nargs="*", default=[], help="add cpp definitions")
293
+
294
+ # testing mode, expected results on values
295
+ arg("--name", "-n", default="", help="name of validation submodel, default is \"\" (root)")
296
+ arg("--none", dest="expect", action="store_const", const=None, default=None,
297
+ help="no test expectations")
298
+ arg("--true", "-t", dest="expect", action="store_const", const=True,
299
+ help="test values for true")
300
+ arg("--false", "-f", dest="expect", action="store_const", const=False,
301
+ help="test values for false")
302
+ arg("--test-vector", "-tv", action="store_true", default=False,
303
+ help="read values from a test vector file")
304
+ arg("--report", "-r", action="store_true", default=False, help="report reasons on fail")
305
+ arg("--no-report", "-nr", dest="report", action="store_false",
306
+ help="fast mode, do not give reasons")
307
+
308
+ # operations on model
309
+ arg("--check", "-c", action="store_true", default=False, help="check model validity")
310
+ arg("--optimize", "-O", action="store_true", default=True, help="optimize model")
311
+ arg("--no-optimize", "-nO", dest="optimize", action="store_false", help="do not optimize model")
312
+ arg("--map-threshold", "-mt", default=5, type=int, help="property map threshold, default 5")
313
+ arg("--map-share", "-ms", default=False, action="store_true", help="property map sharing")
314
+
315
+ operation = ap.add_mutually_exclusive_group()
316
+ ope = operation.add_argument
317
+ ope("--op", choices=["P", "U", "J", "N", "E", "C"],
318
+ help="select operation")
319
+ ope("--preproc", "-P", dest="op", action="store_const", const="P",
320
+ help="preprocess model")
321
+ ope("--dump", "-U", dest="op", action="store_const", const="U",
322
+ help="dump all models")
323
+ ope("--jdump", "-J", dest="op", action="store_const", const="J",
324
+ help="dump json IR")
325
+ ope("--nope", "-N", dest="op", action="store_const", const="N",
326
+ help="dump (retrieved) seldom processed json model input")
327
+ ope("--export", "-E", dest="op", action="store_const", const="E",
328
+ help="export as JSON Schema")
329
+ ope("--compile", "-C", dest="op", action="store_const", const="C",
330
+ help="code generation")
331
+
332
+ # parameters
333
+ arg("model", default="-", nargs="?", help="JSON model source (file or url or \"-\" for stdin)")
334
+ arg("values", nargs="*", help="JSON values to testing")
335
+ args = ap.parse_args()
336
+
337
+ if args.version:
338
+ print(pkg_version("json-model"))
339
+ sys.exit(0)
340
+
341
+ # format/operation/gen guessing
342
+ if args.output != "-" and args.op is None and args.format is None:
343
+ if args.output.endswith(".c"):
344
+ args.format, args.op = "c", "C"
345
+ if args.output.endswith(".o"):
346
+ args.format, args.op = "c", "C"
347
+ if args.gen is None:
348
+ args.gen = "module"
349
+ elif args.output.endswith(".out"):
350
+ args.format, args.op = "c", "C"
351
+ if args.gen is None:
352
+ args.gen = "exec"
353
+ elif args.output.endswith(".py"):
354
+ args.format, args.op = "py", "C"
355
+ if args.gen is None:
356
+ args.gen = "exec"
357
+ elif args.output.endswith(".mpy"):
358
+ args.format, args.op = "py", "C"
359
+ if args.gen is None:
360
+ args.gen = "module"
361
+ elif args.output.endswith(".js"):
362
+ args.format, args.op = "js", "C"
363
+ if args.gen is None:
364
+ args.gen = "exec"
365
+ elif args.output.endswith(".mjs"):
366
+ args.format, args.op = "js", "C"
367
+ if args.gen is None:
368
+ args.gen = "module"
369
+ elif args.output.endswith(".sql"):
370
+ args.format, args.op, args.gen = "plpgsql", "C", "module"
371
+ elif args.output.endswith(".schema.json"):
372
+ args.format, args.op = "json", "E"
373
+ elif args.output.endswith(".model.json"):
374
+ args.format, args.op = "json", "P"
375
+ elif args.values:
376
+ if args.op is None:
377
+ args.op = "C"
378
+ if args.format is None:
379
+ args.format = "py"
380
+ if args.gen is None:
381
+ args.gen = "none"
382
+
383
+ if args.reporting is None:
384
+ args.reporting = False if args.format == "plpgsql" else True
385
+
386
+ if args.op is None:
387
+ args.op = "P"
388
+
389
+ # update op-dependent default
390
+ if args.gen is None:
391
+ args.gen = "source" if args.op in "C" and not args.values else "module"
392
+
393
+ # option/parameter consistency and defaults
394
+ if args.op in "PUJNE":
395
+ if args.format is None:
396
+ args.format = "json"
397
+ elif args.format not in ("json", "yaml"):
398
+ log.error(f"unexpected format {args.format} for operation {args.op}")
399
+ sys.exit(1)
400
+ elif args.op == "C":
401
+ if args.format is None:
402
+ args.format = "py"
403
+ elif args.format not in ("py", "c", "js", "plpgsql"):
404
+ log.error(f"unexpected format {args.format} for operation {args.op}")
405
+ sys.exit(1)
406
+ else: # pragma: no cover
407
+ log.error(f"unexpected operation {args.op}")
408
+ sys.exit(1)
409
+
410
+ if args.values and (args.op not in "C" or args.format != "py"):
411
+ log.error(f"Testing JSON values requires -C for Python: {args.op} {args.format}")
412
+ sys.exit(1)
413
+ if args.gen == "source" and (args.op not in "C" or args.format not in ("py", "c", "js", "plpgsql")):
414
+ log.error(f"Showing code requires -C for Python, C or JS: {args.op} {args.format}")
415
+ sys.exit(1)
416
+
417
+ # strict/loose numbers
418
+ if args.loose_number is not None:
419
+ if args.loose_int is None:
420
+ args.loose_int = args.loose_number
421
+ else:
422
+ log.warning("keeping integer strictness as already set")
423
+ if args.loose_float is None:
424
+ args.loose_float = args.loose_number
425
+ else:
426
+ log.warning("keeping float strictness as already set")
427
+
428
+ # debug
429
+ log.setLevel(logging.DEBUG if args.debug else logging.INFO if args.verbose else logging.WARNING)
430
+
431
+ # resolver
432
+ maps: dict[str, str] = {}
433
+ for m in args.maps:
434
+ assert " " in m, f"valid map require a space: {m}"
435
+ k, v = m.split(" ", 1)
436
+ maps[k] = v
437
+ resolver = Resolver(None, maps)
438
+
439
+ log.info(f"processing {args.model}")
440
+
441
+ # CREATE FROM FILE OR URL
442
+ try:
443
+ model = create_model(args.model, resolver, auto=args.auto, debug=args.debug,
444
+ loose_int=args.loose_int, loose_float=args.loose_float,
445
+ check=args.check, merge=args.op != "N", optimize=args.optimize,
446
+ follow=False)
447
+ except BaseException as e:
448
+ log.error(e)
449
+ if args.debug:
450
+ raise
451
+ else:
452
+ log.error(f"invalid model {args.model}")
453
+ sys.exit(2)
454
+
455
+ # NOTE preprocessing already done in create_model
456
+ # TODO check why iterating changes things (eg ref to predefs substitions)
457
+ # process_model(model, check=args.check, merge=args.op != "N",
458
+ # optimize=args.optimize, debug=args.debug)
459
+
460
+ # OUTPUT
461
+ # TODO check overwrite?!
462
+ output = open(args.output, "w") if args.output != "-" and args.format != "out" else sys.stdout
463
+ checker = None # pyright: ignore
464
+
465
+ # convert json to a string using prettyprint options
466
+ def json2str(j: Jsonable) -> str:
467
+ if args.format == "json":
468
+ return json.dumps(j, sort_keys=args.sort, indent=args.indent)
469
+ else:
470
+ return yaml.dump(j, sort_keys=args.sort, indent=args.indent)
471
+
472
+ # actual output
473
+ if args.op == "J": # json dump
474
+ verbose = True if args.verbose is None else args.verbose
475
+ show = model.toJSON(verbose=verbose, recurse=verbose)
476
+ # show = [ model._models[mid].toJSON(verbose=args.verbose)
477
+ # for mid in sorted(model._models.keys()) ]
478
+ print(json2str(show), file=output)
479
+ elif args.op == "U": # model dump
480
+ assert model._models
481
+ show = []
482
+ for mid in sorted(model._models.keys()):
483
+ m = model._models[mid]
484
+ j = m.toModel(m._is_root)
485
+ if isinstance(j, dict) or model._is_root:
486
+ show.append(j)
487
+ print(json2str(show), file=output)
488
+ elif args.op == "N": # no operation
489
+ print(json2str(model._init_md), file=output)
490
+ elif args.op == "P": # preprocessed model
491
+ show = model.toModel(True)
492
+ print(json2str(show), file=output)
493
+ elif args.op == "C":
494
+ assert args.format in ("py", "c", "js", "plpgsql"), f"valid output language {args.format}"
495
+
496
+ if args.format in ("plpgsql", "js") and (not model._loose_int or not model._loose_float):
497
+ log.warning(f"{args.model}: {LANG[args.format]} backend does not support strict numbers")
498
+
499
+ # compile to source
500
+ code = xstatic_compile(model, args.entry, lang=args.format, execute=args.gen == "exec",
501
+ map_threshold=args.map_threshold, map_share=args.map_share,
502
+ debug=args.debug, report=args.reporting, relib=args.regex_engine)
503
+ source = str(code)
504
+
505
+ # source to executable
506
+ if args.format == "c" and args.gen in ("exec", "module"):
507
+ clang_compile(source, args)
508
+ elif args.gen != "none":
509
+ print(source, file=output, end="", flush=True)
510
+ if args.output != "-" and args.gen == "exec":
511
+ os.chmod(args.output, 0o755)
512
+
513
+ # import for checks
514
+ if args.format == "py" and args.values:
515
+ env = {}
516
+ exec(source, env)
517
+ env[args.entry + "_init"]()
518
+
519
+ def checker(v: Jsonable, model: str, rep: Report = None) -> bool:
520
+ return env[args.entry](v, model, rep)
521
+
522
+ elif args.op == "E":
523
+ if not model._loose_int or not model._loose_float:
524
+ log.warning(f"{args.model}: JSON Schema does not support strict integer/float")
525
+ schema: JsonSchema
526
+ try:
527
+ schema = model.toSchema()
528
+ except Exception as e:
529
+ log.error(e, exc_info=args.debug)
530
+ schema = {"ERROR": str(e)}
531
+ print(json2str(schema), file=output)
532
+ else:
533
+ raise Exception(f"operation not implemented yet: {args.op}")
534
+
535
+ def _process(checker, model: str, value: Jsonable, fid: str, expect: bool|None, output) -> bool:
536
+ """Process a value and report to output depending on args, return if as expected."""
537
+ reasons = [] if args.report else None
538
+ okay = checker(value, model, reasons)
539
+ sokay = "PASS" if okay else "FAIL"
540
+ if expect is None or args.verbose or fid[-1] == "]":
541
+ msg = f"{fid}: {sokay}"
542
+ if not okay and args.report and reasons:
543
+ msg += " (" + "; ".join(f"{json_path(p)}: {m}" for m, p in reversed(reasons)) + ")"
544
+ print(msg, file=output)
545
+ if expect is not None:
546
+ if okay == expect:
547
+ log.info(f"check value {fid}: {okay}")
548
+ elif okay != expect:
549
+ log.error(f"check value {fid}: {okay}")
550
+ return False
551
+ return True
552
+
553
+ # values
554
+ nerrors = 0
555
+ for fn in args.values:
556
+ assert checker
557
+ with open(fn) as fh:
558
+ try:
559
+ value = json.load(fh)
560
+ if args.test_vector:
561
+ assert isinstance(value, list), "array test vector"
562
+ for idx, test in enumerate(value):
563
+
564
+ assert isinstance(test, list) and len(test) in (2, 3), "2 or 3 tuple test"
565
+
566
+ if len(test) == 2:
567
+ expect, val = test
568
+ model = args.name
569
+ else:
570
+ assert len(test) == 3
571
+ expect, model, val = test
572
+ assert isinstance(expect, bool) and isinstance(model, str), "test format"
573
+
574
+ if not _process(checker, model, val, f"{fn}[{idx}]", expect, output):
575
+ nerrors += 1
576
+
577
+ else: # direct value testing
578
+ if not _process(checker, args.name, value, fn, args.expect, output):
579
+ nerrors += 1
580
+ except Exception as e:
581
+ nerrors += 1
582
+ log.debug(e, exc_info=args.verbose)
583
+ print(f"{fn}: ERROR")
584
+
585
+ sys.exit(4 if nerrors > 0 else 0)
@@ -0,0 +1,82 @@
1
+ #
2
+ # URL to JSON with 2 level caching
3
+ #
4
+
5
+ import os
6
+ import hashlib
7
+ import urllib.parse
8
+ import requests
9
+ import json
10
+ import yaml
11
+
12
+ from .utils import Jsonable, log
13
+
14
+
15
+ class JsonURLCache:
16
+ """Cache JSON URL contents."""
17
+
18
+ # FIXME should invalidate old cache entries?
19
+
20
+ def __init__(self, cache_dir: str|None = None):
21
+
22
+ # loader
23
+ self._requests = requests.Session()
24
+ self._cache_dir: str
25
+
26
+ # cache retrieved url
27
+ if cache_dir is not None:
28
+ self._cache_dir = cache_dir
29
+ elif "JSON_MODEL_CACHEDIR" in os.environ:
30
+ self._cache_dir = os.environ["JSON_MODEL_CACHEDIR"]
31
+ else:
32
+ self._cache_dir = os.environ.get("HOME", ".") + "/.cache/json-model"
33
+
34
+ # create cache dir if necessary
35
+ if not os.path.exists(self._cache_dir):
36
+ os.mkdir(self._cache_dir)
37
+ assert os.path.isdir(self._cache_dir)
38
+
39
+ # in-memory cache
40
+ self._cache: dict[str, Jsonable] = {}
41
+
42
+ def getJSON(self, url: str) -> Jsonable:
43
+ res = self._requests.get(url)
44
+ try:
45
+ return res.json()
46
+ except requests.JSONDecodeError as e: # else try YAML
47
+ log.debug(e)
48
+ return yaml.full_load(res.text)
49
+
50
+ def load(self, url: str):
51
+ """Load JSON URL."""
52
+
53
+ # hmmm… basically remove fragment
54
+ up = urllib.parse.urlparse(url)
55
+ u = up.scheme + "://" + up.netloc + up.path
56
+ if up.query:
57
+ u += "?" + up.query
58
+
59
+ # first cache (memory)
60
+ # log.error("skipping cache!")
61
+ if u in self._cache:
62
+ return self._cache[u]
63
+
64
+ # second cache (file): we assume no hash collision
65
+ h = hashlib.sha3_256(u.encode("UTF-8")).hexdigest()
66
+ hfile = self._cache_dir + "/" + h
67
+ if os.path.exists(hfile):
68
+ log.info(f"loading: {url}")
69
+ with open(hfile) as f:
70
+ j = json.load(f)
71
+ self._cache[u] = j
72
+ return j
73
+
74
+ # download
75
+ log.info(f"downloading: {url}")
76
+ j = self.getJSON(u)
77
+ self._cache[u] = j
78
+ with open(hfile, "w") as f:
79
+ # sort_keys?
80
+ json.dump(j, f, sort_keys=True, indent=2)
81
+
82
+ return j