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/xstatic.py ADDED
@@ -0,0 +1,1444 @@
1
+ # experimental static (ecstatic?) compiler
2
+
3
+ import re
4
+ import json
5
+
6
+ from .mtypes import ModelType, ModelArray, ModelObject, ModelError, ModelPath, Symbols
7
+ from .mtypes import Jsonable, Number, JsonScalar
8
+ from .utils import split_object, model_in_models, all_model_type, constant_value
9
+ from .utils import log, tname, MODEL_PREDEFS
10
+ from .runtime.support import _path as json_path
11
+ from .analyze import ultimate_type, disjunct_analyse
12
+ from .model import JsonModel
13
+ from .language import Language, Code, Block, BoolExpr, PathExpr, PropMap, JsonExpr, StrExpr, Var
14
+
15
+
16
+ class CodeGenerator:
17
+ """JSON Models Compilation.
18
+
19
+ - globs: global map of symbols.
20
+ - language: target language abstraction.
21
+ - execute: true for executable, false for module.
22
+ - fname: entry function name.
23
+ - prefix: use this prefix for file-level identifiers.
24
+ - map_threshold: whether to inline property name checks (up to threshold) or use a map.
25
+ - report: whether to report rejection reasons.
26
+ - path: whether to keep track of value path while checking.
27
+ - debug: verbose debug mode.
28
+ """
29
+
30
+ def __init__(self, globs: Symbols, language: Language, fname: str = "check_model", *,
31
+ prefix: str = "", map_threshold: int = 3, map_share: bool = False,
32
+ execute: bool = True, report: bool = True, path: bool = True, debug: bool = False):
33
+
34
+ super().__init__()
35
+
36
+ self._globs = globs
37
+ self._lang = language
38
+ self._prefix = prefix
39
+ self._map_threshold = map_threshold
40
+ self._map_share = map_share
41
+ self._report = report
42
+ self._path = path
43
+ self._debug = debug
44
+
45
+ self._code = Code(language, fname, executable=execute)
46
+
47
+ # identifiers and functions
48
+ # ident-prefix -> next number to use to ensure unique identifiers
49
+ # FIXME global namespace! $-definitions -> function
50
+ self._names: dict[str, str] = {}
51
+ # /re.../ -> regex function name
52
+ self._regs: dict[str, str] = {}
53
+ # model path -> function name
54
+ self._paths: dict[str|tuple[int|str, ...], str] = {}
55
+ # already generated object paths
56
+ self._generated: set[str|tuple[int|str, ...]] = set()
57
+ # compiled json models ids
58
+ self._compiled: set[int] = set()
59
+ self._to_compile: dict[int, tuple[JsonModel, str]] = {}
60
+ # already generated property maps: serialized to function name
61
+ self._generated_maps: dict[str, str] = {}
62
+ self.reset()
63
+
64
+ def reset(self):
65
+ # self._code.clear()
66
+ self._names.clear()
67
+ self._regs.clear()
68
+ self._compiled.clear()
69
+ self._to_compile.clear()
70
+ self._generated_maps.clear()
71
+
72
+ def _exreg(self, jm: JsonModel, name: str, rname: str, remap: dict[str, str],
73
+ regex: str, opts: str, path: str) -> Block:
74
+ """Generate post regex code for extended regular expression."""
75
+ gen = self._lang
76
+ code = (
77
+ gen.match_str_var(rname, "extract", "val", declare=True) +
78
+ gen.match_var("match", gen.match_re(rname, "val", regex, opts), declare=True) +
79
+ gen.if_stmt(gen.match_ko("match"), gen.ret(gen.false()))
80
+ )
81
+ checks = []
82
+ # sname is the name of the substring
83
+ for sname, ref in remap.items():
84
+ checks += gen.match_val("match", rname, sname, "extract")
85
+ checks += gen.if_stmt(
86
+ gen.not_op(self._dollarExpr(jm, ref, "extract", path, is_raw=True)),
87
+ gen.ret(gen.false()))
88
+ checks += gen.ret(gen.true())
89
+ code += checks
90
+
91
+ # generate the string check function
92
+ self._code.strfun(name, code)
93
+
94
+ return []
95
+
96
+ def _regex(self, jm: JsonModel, regex: str, path: str) -> str:
97
+ """Compile a regular expression, with memoization, return function name."""
98
+ gen = self._lang
99
+
100
+ if regex not in self._regs:
101
+
102
+ remap: dict[str, str] = {}
103
+ nparen: int = 0
104
+ pattern, ropts = regex[1:].rsplit("/", 1)
105
+ assert ropts == "" or ropts.isalpha(), f"invalid options: {ropts}"
106
+
107
+ # extract and check actual pattern
108
+ try:
109
+ # model eXtension
110
+ # re: aiLmsux (Ascii/Unicode, Ignore case, Locale, Multi/Single-line, verbose)
111
+ # js: dgimsuvy
112
+ if "X" in ropts:
113
+ ropts = ropts.replace("X", "")
114
+
115
+ # match name to reference
116
+ def subref(match):
117
+ # log.debug(f"subref match={match}")
118
+ nonlocal nparen
119
+ nparen += 1
120
+ name = f"s{nparen}"
121
+ matched = match.group(0)
122
+ if len(matched) > 1:
123
+ matched = matched[1:-1]
124
+ if ":" in matched:
125
+ dollar, pattern = matched.split(":", 2)
126
+ else:
127
+ dollar, pattern = matched, ".*"
128
+ remap[name] = dollar
129
+ return gen.regroup(name, pattern)
130
+ else: # no substitution
131
+ return matched
132
+
133
+ # FIXME this is possibly wrong
134
+ # we want both to count grouping parenthesis and ($FOO) pattern extensions
135
+ pattern = re.sub(r"\((\$\w+(:[^)]*)?\))?", subref, pattern)
136
+
137
+ # statically check re validity by trying to compile it
138
+ if self._lang._relib == "re2":
139
+ import re2 as rex
140
+ else:
141
+ import re as rex
142
+
143
+ # FIXME pcre2 and re syntax can differ
144
+ rex.compile(pattern)
145
+
146
+ except Exception as e:
147
+ log.warning(f"possibly invalid regex: {regex} ({e})")
148
+
149
+ # possibly generate extension function
150
+ if remap:
151
+ fun = gen.ident(self._prefix + "xre")
152
+ self._code.regex(fun + "_re", pattern, ropts)
153
+ self._exreg(jm, fun, fun + "_re", remap, pattern, ropts, path)
154
+ else:
155
+ fun = gen.ident(self._prefix + "re")
156
+ self._code.regex(fun, pattern, ropts)
157
+
158
+ # memoize
159
+ self._regs[regex] = fun
160
+
161
+ return self._regs[regex]
162
+
163
+ def _regExpr(self, jm: JsonModel, regex: str,
164
+ val: JsonExpr|StrExpr, path: PathExpr, is_str: bool = False) -> BoolExpr:
165
+ """Generate an inlined regex check expression on a value."""
166
+ gen = self._lang
167
+ sval: StrExpr = val if is_str else gen.value(val, str) # type: ignore
168
+
169
+ # optimized versions
170
+ if re.match(r"^/\^?.\*\$?/[mis]?$", regex):
171
+ return gen.true()
172
+ elif re.match(r"^/(\?s)\.\+?/$", regex) or re.match(r"^/\.\+?/s$", regex):
173
+ return gen.num_cmp(gen.str_len(sval), ">", gen.const(0))
174
+ elif re.match(r"^/\^[^[({|.+*?\\^$]+/$", regex): # starts with
175
+ return gen.str_start(sval, regex[2:-1])
176
+ elif re.match(r"^/[^[({|.+*?\\^$]+\$/$", regex): # ends with
177
+ return gen.str_end(sval, regex[1:-2])
178
+ elif re.match(r"^/\^[^[({|.+*?\\^$]+\$/$", regex): # streq
179
+ return gen.str_cmp(sval, "=", gen.esc(regex[2:-2]))
180
+ else:
181
+ fun = self._regex(jm, regex, path)
182
+ # TODO inline the internal function if possible?
183
+ return gen.str_check_call(fun, sval, path)
184
+ # TODO f" or _rep(f\"does not match {self._fesc(regex)} at {{{path}}}\", rep)"
185
+
186
+ def _esc(self, val: Jsonable) -> str:
187
+ """Escape value as necessary."""
188
+ # return '"' + string.translate({"\"": "\\\"", "\\": "\\\\"}) + '"'
189
+ return json.dumps(val) if isinstance(val, str) else str(val)
190
+
191
+ def _fesc(self, val: str) -> str:
192
+ """Escape string for an f-string."""
193
+ # FIXME return val.translate({"{": "{{", "\\": "\\\\", "\"": "\\\""})
194
+ return "FESC"
195
+
196
+ def _dollarExpr(self, jm: JsonModel, ref: str, val: str, vpath: str, *, is_raw: bool = False):
197
+ """Generate a call to check for a $REF."""
198
+ # FIXME C val is may be a char*, not a json_t*.
199
+ assert ref and ref[0] == "$"
200
+ if ref in MODEL_PREDEFS: # inline predefs
201
+ # TODO improve
202
+ return self._lang.predef(val, ref, vpath, is_raw)
203
+ # return (self.MODEL_PREDEFS[ref](val, vpath) +
204
+ # (f" or _rep(f\"invalid {ref} at {{{vpath}}}\", rep)" if self._report else ""))
205
+ else:
206
+ fun = self._getNameRef(jm, ref, [])
207
+ return self._lang.check_call(fun, val, vpath, is_ptr=False, is_raw=is_raw)
208
+
209
+ def _compileConstraint(self, jm: JsonModel, model: ModelType, mpath: ModelPath,
210
+ res: Var, val: JsonExpr, vpath: PathExpr):
211
+ """Build constraint checking.
212
+
213
+ This is kind of a pain because operators X overloading X types,
214
+ plus the fact that the compiler may or may not know the value type statically.
215
+
216
+ Comparison values may build a non satisfiable constraint, eg v >= 3 and v < 1.
217
+ Type incompatibilities may also lead to rejections.
218
+ """
219
+
220
+ # TODO make it a function?
221
+ assert isinstance(model, dict) and "@" in model
222
+ smpath = json_path(mpath)
223
+ gen = self._lang
224
+
225
+ tmodel = ultimate_type(jm, model["@"]) # type: ignore
226
+ assert tmodel in (bool, int, float, str, list, dict, type(None), None)
227
+
228
+ # get which props are set
229
+ cmp_props = set(filter(lambda k: k in {"<", ">", "=", "!=", ">=", "<="}, model.keys()))
230
+ has_unique = "!" in model
231
+ if has_unique and not isinstance(model["!"], bool): # should not get there
232
+ raise ModelError("unique constraint value must be a boolean")
233
+ # TODO ensure that not bool
234
+ has_int = any(isinstance(model[k], int) for k in cmp_props)
235
+ has_flt = any(isinstance(model[k], float) for k in cmp_props)
236
+ has_str = any(isinstance(model[k], str) for k in cmp_props)
237
+
238
+ # TODO allow any constant for comparisons?
239
+
240
+ # static type eliminations, no need to check anything!
241
+ # this is probably an unintended model error…
242
+ elim: Block = []
243
+
244
+ # per constraints
245
+ if has_str and has_flt:
246
+ elim += gen.lcom("cannot mix float and string constraints")
247
+
248
+ # per model type
249
+ if tmodel in (bool, type(None)) and (cmp_props or has_unique):
250
+ elim += gen.lcom("no constraint allowed on bool or null")
251
+ # else type check will be enough, standard case below
252
+ elif tmodel in (dict, list) and (has_flt or has_str):
253
+ elim += gen.lcom("no str/flt constraints on object or array")
254
+ elif tmodel is str and has_flt:
255
+ elim += gen.lcom("no float constraints on strings")
256
+ elif tmodel in (int, float) and has_str:
257
+ elim += gen.lcom("no string constraints on numbers")
258
+
259
+ # per unique
260
+ if has_unique and tmodel is not list:
261
+ elim += gen.lcom(f"no unique constraint on {tname(tmodel)}")
262
+
263
+ # TODO value-based elimination
264
+
265
+ # TODO add to "optimize.py"
266
+ if elim:
267
+ log.warning(f"unfeasible model [{smpath}]")
268
+ return elim + gen.bool_var(res, gen.false()) # type: ignore
269
+
270
+ # initial model check
271
+ code: Block = self._compileModel(jm, model["@"], mpath + ["@"], res, val, vpath,
272
+ constrained=len(cmp_props) > 0)
273
+
274
+ # shortcut if nothing to check
275
+ if not cmp_props and not has_unique:
276
+ return code
277
+
278
+ checks: list[BoolExpr] = []
279
+ cvars: Block = []
280
+ if tmodel is None:
281
+ # generic implementations if several model types, using runtime functions
282
+ if has_unique:
283
+ checks.append(gen.is_a(val, list))
284
+ checks.append(gen.check_unique(val, vpath))
285
+ for op in sorted(cmp_props):
286
+ checks.append(gen.check_constraint(op, model[op], val, vpath)) # type: ignore
287
+ else:
288
+ # optimized known-type-specific code
289
+ # NOTE we know that constraints make sense for the target type
290
+ fval, sval, ival = None, None, None
291
+
292
+ if has_unique:
293
+ assert tmodel is list
294
+ # TODO add const-based versions if more is known?
295
+ checks.append(gen.check_unique(val, vpath))
296
+ if has_int:
297
+ if tmodel in (int, str, list, dict):
298
+ # skip float
299
+ ival = gen.ident("ival")
300
+ cvars += gen.int_var(ival, gen.any_int_val(val, tmodel), declare=True)
301
+ else:
302
+ assert tmodel is float
303
+ fval = gen.ident("fval")
304
+ cvars += gen.flt_var(fval,
305
+ gen.value(val,
306
+ Number if jm._loose_float else float), declare=True) # type: ignore
307
+ if has_flt:
308
+ if tmodel is float and not has_int:
309
+ fval = gen.ident("fval")
310
+ cvars += gen.flt_var(fval, gen.value(val,
311
+ Number if jm._loose_float else float), # type: ignore
312
+ declare=True)
313
+ elif tmodel is int:
314
+ fval = gen.ident("fval")
315
+ cvars += gen.flt_var(fval, gen.value(val, Number), declare=True) # type: ignore
316
+ # else cannot happen
317
+ if has_str:
318
+ assert tmodel is str # redundant sanity check
319
+ sval = gen.ident("sval")
320
+ cvars += gen.str_var(sval, gen.value(val, str), declare=True)
321
+ for op in sorted(cmp_props): # FIXME looseness?
322
+ vop = model[op]
323
+ if isinstance(vop, int):
324
+ if tmodel is float:
325
+ checks.append(gen.num_cmp(fval, op, gen.const(vop))) # type: ignore
326
+ else:
327
+ checks.append(gen.num_cmp(ival, op, gen.const(vop))) # type: ignore
328
+ elif isinstance(vop, str):
329
+ checks.append(gen.str_cmp(sval, op, gen.const(vop))) # type: ignore
330
+ elif isinstance(vop, float):
331
+ checks.append(gen.num_cmp(fval, op, gen.const(vop))) # type: ignore
332
+
333
+ assert checks
334
+ if self._debug:
335
+ log.debug(f"checks={checks}")
336
+
337
+ code += gen.if_stmt(res,
338
+ cvars + gen.bool_var(res, gen.and_op(*checks)) +
339
+ self._gen_report(res, f"constraints failed [{smpath}]", vpath))
340
+
341
+ return code
342
+
343
+ def _disjunction(self, jm: JsonModel, model: ModelType, mpath: ModelPath,
344
+ res: str, val: str, vpath: str) -> Block|None:
345
+ """Generate optimized disjunction check, return None if failed."""
346
+
347
+ assert isinstance(model, dict) and "|" in model and isinstance(model["|"], list)
348
+ dis = disjunct_analyse(jm, model, mpath) # type: ignore
349
+ log.debug(f"disjunct at {mpath}: dis={dis}")
350
+ if dis is None:
351
+ return None
352
+
353
+ tag_name, tag_type, models, all_const_props = dis
354
+ smpath = json_path(mpath)
355
+ gen = self._lang
356
+
357
+ log.debug(f"disjunct: tag_name={tag_name} consts={all_const_props}")
358
+
359
+ # Compile all object models in the list if needed
360
+ assert isinstance(model, dict)
361
+
362
+ init = model["|"]
363
+ assert isinstance(init, list) # pyright hint
364
+ assert len(models) == len(init)
365
+
366
+ code = []
367
+
368
+ for i, m in enumerate(models):
369
+ p = mpath + [i]
370
+ tp = tuple(p)
371
+ mi = init[i] # initial model
372
+ if isinstance(mi, str) and mi and mi[0] == "$":
373
+ # it is a reference, it must be compiled for its name, no need to recompile it!
374
+ fun = self._getNameRef(jm, mi, p)
375
+ if tp not in self._paths:
376
+ # several path will lead to the same function
377
+ self._paths[tp] = fun
378
+ # else nothing to do?
379
+ elif tp not in self._paths:
380
+ # else compile the direct object as a side effect…
381
+ # BUT we need to recover the generated function name!
382
+ self._compileModel(jm, m, p, res, val, vpath)
383
+ # log.debug(f"{self._paths}")
384
+
385
+ cmap = self._lang.ident(self._prefix + "map")
386
+
387
+ # mapping from tag values to check functions
388
+ TAG_CHECKS: dict[JsonScalar, str] = {}
389
+ for i in range(len(models)):
390
+ consts = all_const_props[i]
391
+ TAG_CHECKS[consts[tag_name]] = self._paths[tuple(mpath + [i])]
392
+
393
+ self._code.cmap(cmap, TAG_CHECKS)
394
+
395
+ code += gen.bool_var(res, gen.is_a(val, dict))
396
+
397
+ # FIXME None tag value?!
398
+ tag = self._lang.ident("tag")
399
+ itag = gen.json_var(tag, gen.obj_prop_val(val, tag_name, False), declare=True)
400
+
401
+ fun = self._lang.ident("fun")
402
+ ifun = gen.fun_var(fun, gen.get_cmap(cmap, tag, tag_type), True)
403
+ icall = gen.bool_var(res, gen.check_call(fun, val, vpath, is_ptr=True))
404
+
405
+ code += (
406
+ gen.if_stmt(res,
407
+ itag +
408
+ gen.if_stmt(gen.is_def(tag),
409
+ ifun +
410
+ gen.if_stmt(gen.is_def(fun),
411
+ icall,
412
+ gen.bool_var(res, gen.false()) +
413
+ gen.report(f"tag <{tag_name}> value not found [{smpath}]", vpath)),
414
+ gen.bool_var(res, gen.false()) +
415
+ gen.report(f"tag prop <{tag_name}> is missing [{smpath}]", vpath)),
416
+ gen.report(f"value is not an object [{smpath}]", vpath))
417
+ )
418
+
419
+ return code
420
+
421
+ def _gen_report(self, res: str, msg: str, path: str, cleanup: bool = False) -> Block:
422
+ """Maybe generate a report."""
423
+ if self._report:
424
+ gen = self._lang
425
+ if cleanup:
426
+ return gen.if_stmt(res, gen.clean_report(), gen.report(msg, path))
427
+ else:
428
+ return gen.if_stmt(gen.not_op(res), gen.report(msg, path))
429
+ else:
430
+ return []
431
+
432
+ def _gen_reporting(self, report: Block) -> Block:
433
+ """Detailed reporting."""
434
+ gen = self._lang
435
+ return gen.if_stmt(gen.is_reporting(), report) if self._report else []
436
+
437
+ def _gen_fail(self, msg: str, path: PathExpr) -> Block:
438
+ """Generate a report and return false."""
439
+ gen = self._lang
440
+ return gen.report(msg, path) + gen.ret(gen.false())
441
+
442
+ def _gen_short_expr(self, expr: BoolExpr) -> Block:
443
+ """Return immediately if expression is false."""
444
+ gen = self._lang
445
+ return gen.if_stmt(gen.not_op(expr), gen.ret(gen.false()))
446
+
447
+ def _propmap_name(self, model: ModelObject, default: str) -> str:
448
+ """Memoize property map names for reuse.
449
+
450
+ However, generated model path are wrong.
451
+ """
452
+ assert isinstance(model, dict)
453
+ if not self._map_share:
454
+ return default
455
+ # TODO ignore comments?!
456
+ smodel = json.dumps(model, sort_keys=True)
457
+ if smodel in self._generated_maps:
458
+ return self._generated_maps[smodel]
459
+ else:
460
+ self._generated_maps[smodel] = default
461
+ return default
462
+
463
+ def _propmap_gen(self, jm: JsonModel, model: ModelObject, name: str, mpath: ModelPath):
464
+ """Generate property map for sub-model."""
465
+ assert isinstance(model, dict)
466
+ prop_map: dict[str, str] = {}
467
+ for p in sorted(model.keys()):
468
+ m = model[p]
469
+ pid = f"{name}_{p}" # unique identifier for value function
470
+ self._compileName(jm, pid, m, mpath + [p], True)
471
+ prop_map[p] = self._getName(jm, pid)
472
+ self._code.pmap(name, prop_map)
473
+
474
+ def _openMuMaObject(self, jm: JsonModel, must: dict[str, ModelType], may: dict[str, ModelType],
475
+ mpath: ModelPath, oname: str,
476
+ res: Var, val: JsonExpr, vpath: PathExpr) -> Block:
477
+ """Optimize `{"x": ..., "": "?y": ..., "": "$ANY"}`."""
478
+
479
+ assert isinstance(must, dict)
480
+ gen = self._lang
481
+ smpath = json_path(mpath)
482
+
483
+ code = (
484
+ gen.lcom("check must only props") +
485
+ gen.if_stmt(gen.not_op(gen.is_a(val, dict)),
486
+ self._gen_fail(f"not an object [{smpath}]", vpath))
487
+ )
488
+
489
+ # value checks?
490
+ if any(m != "$ANY" for m in must.values()) or any(m != "$ANY" for m in may.values()):
491
+ code += (
492
+ gen.json_var("pval", declare=True) +
493
+ gen.bool_var(res, declare=True)
494
+ )
495
+
496
+ for prop, pmodel in must.items():
497
+ code += gen.if_stmt(
498
+ gen.not_op(gen.has_prop(val, prop)),
499
+ self._gen_fail(f"missing mandatory prop <{prop}> [{smpath}]", vpath))
500
+ if pmodel != "$ANY":
501
+ code += (
502
+ gen.json_var("pval", gen.obj_prop_val(val, prop, False)) +
503
+ self._compileModel(jm, pmodel, mpath + [prop], res, "pval", vpath) +
504
+ gen.if_stmt(
505
+ gen.not_op(res),
506
+ self._gen_fail(f"unexpected value for mandatory prop <{prop}> [{smpath}]",
507
+ vpath))
508
+ )
509
+
510
+ for prop, pmodel in may.items():
511
+ if pmodel != "$ANY":
512
+ code += gen.if_stmt(gen.has_prop(val, prop),
513
+ gen.json_var("pval", gen.obj_prop_val(val, prop, False)) +
514
+ self._compileModel(jm, pmodel, mpath + [prop], res, "pval", vpath) +
515
+ gen.if_stmt(
516
+ gen.not_op(res),
517
+ self._gen_fail(f"unexpected value for optional prop <{prop}> [{smpath}]",
518
+ vpath))
519
+ )
520
+ # else covered by catchall
521
+
522
+ return code + gen.ret(gen.true())
523
+
524
+ def _compileObject(self, jm: JsonModel, model: ModelType, mpath: ModelPath,
525
+ oname: str, res: str, val: JsonExpr, vpath: PathExpr) -> Block:
526
+ """Generate the body of a function which checks an actual object."""
527
+
528
+ assert isinstance(model, dict)
529
+ gen = self._lang
530
+
531
+ # separate properties
532
+ must, may, defs, regs, oth = split_object(model, mpath)
533
+ smpath = json_path(mpath)
534
+
535
+ # generated code helpers
536
+ code: Block = []
537
+ multi_if: list[tuple[BoolExpr, Block]] = []
538
+ prop, pval, must_c, pfun = "prop", "pval", "must_count", "pfun"
539
+
540
+ # should be an object
541
+ code += gen.if_stmt(gen.not_op(gen.is_a(val, dict)),
542
+ self._gen_fail(f"not an object [{smpath}]", vpath))
543
+
544
+ # shorcut for empty/any object
545
+ if not must and not may and not defs and not regs:
546
+ if not oth: # empty object
547
+ code += \
548
+ gen.if_stmt(gen.num_cmp(gen.obj_len(val), "=", gen.const(0)),
549
+ gen.ret(gen.true()),
550
+ self._gen_fail(f"expecting empty object [{smpath}]", vpath))
551
+ return code
552
+ elif oth == { "": "$ANY" }: # any object (empty must/may/defs/regs)
553
+ code += gen.lcom("accept any object") + gen.ret(gen.true())
554
+ return code
555
+ # only check values, fine code will be generated below
556
+
557
+ # shortcut for open object with simple props only
558
+ if not defs and not regs and (must or may) and oth == {"": "$ANY"}:
559
+ return self._openMuMaObject(jm, must, may, mpath, oname, res, val, vpath)
560
+
561
+ # path + [ prop ]
562
+ lpath = gen.ident("lpath")
563
+ lpath_ref: PathExpr = gen.path_lvar(lpath, vpath)
564
+
565
+ # else we have some work to do!
566
+ if defs or regs or oth and oth[""] != "$ANY" or \
567
+ 1 <= len(must) <= self._map_threshold or \
568
+ 1 <= len(may) <= self._map_threshold:
569
+ code += gen.bool_var(res, declare=True)
570
+
571
+ if len(may) > self._map_threshold or len(must) > self._map_threshold:
572
+ # we need a function pointer for simple properties
573
+ code += gen.fun_var(pfun, declare=True)
574
+
575
+ # build multi-if structure to put in prop/val loop
576
+ if must:
577
+
578
+ # must prop counter to check at the end if all were seen
579
+ code += gen.int_var(must_c, gen.const(0), True)
580
+
581
+ if len(must) <= self._map_threshold: # direct property checks
582
+
583
+ for p, m in must.items():
584
+ mu_expr = gen.str_cmp(prop, "=", gen.esc(p))
585
+ mu_code = (
586
+ gen.lcom(f"handle must {p} property") +
587
+ gen.inc_var(must_c) +
588
+ self._compileModel(jm, m, mpath + [p], res, pval, lpath_ref) +
589
+ gen.if_stmt(gen.not_op(res),
590
+ self._gen_fail(
591
+ f"invalid mandatory prop value [{json_path(mpath + [p])}]",
592
+ lpath_ref)
593
+ )
594
+ )
595
+ multi_if += [(mu_expr, mu_code)]
596
+
597
+ else: # generic code above threshold
598
+
599
+ candidate = f"{oname}_mup"
600
+ prop_must = self._propmap_name(must, candidate)
601
+
602
+ # no reuse, generate new map
603
+ if prop_must == candidate:
604
+ self._propmap_gen(jm, must, prop_must, mpath)
605
+
606
+ mu_prop_code = (
607
+ gen.inc_var(must_c) +
608
+ gen.if_stmt(gen.not_op(gen.check_call(pfun, pval, lpath_ref, is_ptr=True)),
609
+ self._gen_fail(f"invalid mandatory prop value [{smpath}]", lpath_ref))
610
+ )
611
+
612
+ # use map
613
+ if gen.assign_expr():
614
+ mu_expr = gen.assign_prop_fun(pfun, prop, prop_must)
615
+ mu_code = (
616
+ gen.lcom(f"handle {len(must)} mandatory props") +
617
+ gen.if_stmt(gen.is_def(pfun), mu_prop_code)
618
+ )
619
+ else:
620
+ mu_expr = gen.has_prop_fun(prop, prop_must)
621
+ mu_code = (
622
+ gen.lcom(f"handle {len(must)} mandatory props") +
623
+ gen.fun_var(pfun, gen.get_prop_fun(prop, prop_must)) +
624
+ mu_prop_code
625
+ )
626
+
627
+ multi_if += [(mu_expr, mu_code)]
628
+
629
+ if may:
630
+
631
+ if len(may) <= self._map_threshold: # simple few-property code
632
+
633
+ for p, m in may.items():
634
+ ma_expr = gen.str_cmp(prop, "=", gen.esc(p))
635
+ ma_code = (
636
+ gen.lcom(f"handle may {p} property") +
637
+ self._compileModel(jm, m, mpath + [p], res, pval, lpath_ref) +
638
+ gen.if_stmt(gen.not_op(res),
639
+ self._gen_fail(
640
+ f"invalid optional prop value [{json_path(mpath + [p])}]",
641
+ lpath_ref)
642
+ )
643
+ )
644
+ multi_if += [(ma_expr, ma_code)]
645
+
646
+ else: # generic code
647
+
648
+ candidate = f"{oname}_map"
649
+ prop_may = self._propmap_name(may, candidate)
650
+
651
+ if prop_may == candidate:
652
+ self._propmap_gen(jm, may, prop_may, mpath)
653
+
654
+ if gen.assign_expr():
655
+ ma_expr = gen.assign_prop_fun(pfun, prop, prop_may)
656
+ ma_code = (
657
+ gen.lcom(f"handle {len(may)} may props") +
658
+ gen.if_stmt(
659
+ gen.and_op(gen.is_def(pfun),
660
+ gen.not_op(gen.check_call(pfun, pval, lpath_ref, is_ptr=True))),
661
+ self._gen_fail(f"invalid optional prop value [{smpath}]", lpath_ref))
662
+ )
663
+ else:
664
+ ma_expr = gen.has_prop_fun(prop, prop_may)
665
+ ma_code = (
666
+ gen.lcom(f"handle {len(may)} may props") +
667
+ gen.fun_var(pfun, gen.get_prop_fun(prop, prop_may)) +
668
+ gen.if_stmt(
669
+ gen.not_op(gen.check_call(pfun, pval, lpath_ref, is_ptr=True)),
670
+ self._gen_fail(f"invalid optional prop value [{smpath}]", lpath_ref))
671
+ )
672
+
673
+ multi_if += [(ma_expr, ma_code)]
674
+
675
+ # $* is inlined expr (FIXME inlining does not work with vpath)
676
+ for d, m in defs.items():
677
+ ref = "$" + d
678
+ dl_expr = self._dollarExpr(jm, ref, prop, lpath_ref, is_raw=True) # FIXME lpath &lpath?
679
+ dl_code = gen.lcom(f"handle {len(defs)} key props") + \
680
+ self._compileModel(jm, m, mpath + [ref], res, pval, lpath_ref) + \
681
+ self._gen_short_expr(res)
682
+ multi_if += [(dl_expr, dl_code)]
683
+
684
+ # // is inlined
685
+ for r, v in regs.items():
686
+ # FIXME options?!
687
+ regex = f"/{r}/"
688
+ rg_expr = self._regExpr(jm, regex, prop, vpath, True) # FIXME lpath &lpath?
689
+ rg_code = gen.lcom(f"handle {len(regs)} re props") + \
690
+ self._compileModel(jm, v, mpath + [regex], res, pval, lpath_ref) + \
691
+ self._gen_short_expr(res)
692
+ multi_if += [(rg_expr, rg_code)]
693
+
694
+ # catchall is inlined?
695
+ ot_code: Block
696
+ if oth:
697
+ omodel = oth[""]
698
+ smpath = json_path(mpath + [""])
699
+ if omodel != "$ANY":
700
+ ot_code = gen.lcom("handle other props") + \
701
+ self._compileModel(jm, omodel, mpath + [""], res, pval, lpath_ref) + \
702
+ self._gen_short_expr(res)
703
+ else: # optimized "": "$ANY" case
704
+ ot_code = gen.lcom("accept any other props") + gen.nope()
705
+ else: # no catch all
706
+ smpath = json_path(mpath)
707
+ ot_code = self._gen_fail(f"unexpected prop [{smpath}]", lpath_ref)
708
+
709
+ code += gen.obj_loop(val, prop, pval,
710
+ gen.path_var(lpath, gen.path_val(vpath, prop, True), True) +
711
+ gen.mif_stmt(multi_if, ot_code))
712
+
713
+ # check that all must were seen, with some effort to report the missing ones
714
+ if must:
715
+ missing = []
716
+ for prop in sorted(must.keys()):
717
+ missing += \
718
+ gen.if_stmt(gen.not_op(gen.has_prop(val, prop)),
719
+ gen.report(f"missing mandatory prop <{prop}> [{smpath}]", vpath))
720
+ code += \
721
+ gen.if_stmt(gen.num_cmp(must_c, "!=", gen.const(len(must))),
722
+ self._gen_reporting(missing) +
723
+ gen.ret(gen.false()))
724
+
725
+ # early returns so no need to look at res
726
+ code += gen.ret(gen.true())
727
+
728
+ return code
729
+
730
+ def _compileOr(self, jm: JsonModel, models: ModelArray, mpath: ModelPath,
731
+ res: str, val: str, vpath: str, known: set[BoolExpr]|None = None) -> Block:
732
+ """Compile a or-list of models."""
733
+
734
+ code = []
735
+ gen = self._lang
736
+ smpath = json_path(mpath)
737
+
738
+ # direct empty list
739
+ # NOTE in practice this case is optimized out so should not come here
740
+ if not models:
741
+ if self._report:
742
+ code += [ gen.report(f"empty or [{smpath}]", vpath) ]
743
+ code += gen.bool_var(res, gen.false())
744
+ return code
745
+
746
+ # partial/full list of constants optimization
747
+ l_const = list(map(lambda m: constant_value(m, mpath), models))
748
+ need_if = False
749
+
750
+ if len(list(filter(lambda t: t[0], l_const))) >= 2:
751
+
752
+ # NOTE we use lists to avoid to squash 1, 1.0 and True…
753
+ constants, n_models = [], []
754
+ for i in range(len(models)):
755
+ # NOTE python equality is a pain, True == 1 == 1.0, False == 0 == 0.0
756
+ # NOTE python typing is a pain, isinstance(True, int) == True
757
+ # thus we only keep strings…
758
+ # TODO also consider int? at least if loose_int/float is false?
759
+ if l_const[i][0] and isinstance(l_const[i][1], self._lang.set_caps):
760
+ cst = l_const[i][1]
761
+ constants.append(cst)
762
+ else:
763
+ n_models.append(models[i])
764
+
765
+ if constants:
766
+ sname = gen.ident(self._prefix + "cst")
767
+ self._code.cset(sname, constants)
768
+ code += gen.bool_var(res,
769
+ gen.and_op(gen.is_scalar(val),
770
+ gen.in_cset(sname, val, constants)))
771
+ code += self._gen_report(res, f"value not in enum [{smpath}]", vpath)
772
+ if not n_models:
773
+ return code
774
+ models = n_models
775
+ if not models:
776
+ # all constants were tested, we are done
777
+ return code
778
+ need_if = True
779
+
780
+ # discriminant optimization for list of objects, None if fails
781
+ tmp: ModelType = {"|": models}
782
+ if dcode := self._disjunction(jm, tmp, mpath, res, val, vpath):
783
+ if need_if:
784
+ return code + gen.if_stmt(gen.not_op(res), dcode)
785
+ else:
786
+ return code + dcode
787
+ return
788
+
789
+ # homogeneous typed list shortcut
790
+ same, expected = all_model_type(models, mpath)
791
+ or_known: set[BoolExpr] = set()
792
+ or_code = []
793
+ if same:
794
+ # all models have the same ultimate type, type check shortcut
795
+ type_test = gen.is_a(val, expected)
796
+ or_known.add(type_test)
797
+ or_code += gen.bool_var(res, type_test)
798
+ or_code += self._gen_report(res, f"unexpected type [{smpath}]", vpath)
799
+
800
+ icode = []
801
+ for i, m in reversed(list(enumerate(models))):
802
+ body = self._compileModel(jm, m, mpath + [i], res, val, vpath, or_known) + icode
803
+ if i > 0:
804
+ icode = gen.if_stmt(gen.not_op(res), body)
805
+ else:
806
+ icode = body
807
+
808
+ icode += self._gen_report(res, f"no model matched [{smpath}]", vpath, True)
809
+
810
+ if or_code:
811
+ or_code += gen.if_stmt(res, icode)
812
+ else:
813
+ or_code += icode
814
+
815
+ if need_if:
816
+ code += gen.if_stmt(gen.not_op(res), or_code)
817
+ else:
818
+ code += or_code
819
+
820
+ return code
821
+
822
+ def _compileXor(self, jm: JsonModel, models: ModelArray, mpath: ModelPath,
823
+ res: str, val: str, vpath: str, known: set[BoolExpr]|None = None) -> Block:
824
+ """Compile a xor-list of models."""
825
+
826
+ assert isinstance(models, list) # pyright hint
827
+ gen = self._lang
828
+ smpath = json_path(mpath)
829
+ code = []
830
+
831
+ # NOTE optimized out under -O
832
+ if len(models) == 0:
833
+ code += (
834
+ gen.lcom("early empty xor list") +
835
+ gen.bool_var(res, gen.false())
836
+ )
837
+ return code
838
+
839
+ # NOTE optimized out under -O
840
+ if len(models) == 1:
841
+ return gen.lcom("early singleton xor list") + \
842
+ self._compileModel(jm, models[0], mpath + [0], res, val, vpath, known)
843
+
844
+ # optimize out repeated models
845
+ if len(models) >= 2:
846
+ seen, dups, kept = [], [], []
847
+ seen_i, dups_i, kept_i = [], [], []
848
+ for i, m in enumerate(models):
849
+ if model_in_models(m, seen):
850
+ if not model_in_models(m, dups):
851
+ dups.append(m)
852
+ dups_i.append(i)
853
+ else:
854
+ seen.append(m)
855
+ seen_i.append(i)
856
+ for i, m in zip(seen_i, seen):
857
+ if not model_in_models(m, dups):
858
+ kept.append(m)
859
+ kept_i.append(i)
860
+
861
+ # direct false if in dups
862
+ if dups:
863
+ isin = gen.ident("is")
864
+ code += (
865
+ gen.lcom("remove duplicate xor list") +
866
+ gen.bool_var(isin, declare=True) +
867
+ gen.bool_var(res, gen.true())
868
+ )
869
+
870
+ # generate flat if, no big deal?
871
+ for i, m in enumerate(dups):
872
+ idx = dups_i[i]
873
+ icode = self._compileModel(jm, m, mpath + [idx], isin, val, vpath) + \
874
+ gen.bool_var(res, gen.not_op(isin))
875
+ if i == 0:
876
+ code += icode
877
+ else:
878
+ code += gen.if_stmt(res, icode)
879
+
880
+ # update remaining models and their index
881
+ models = kept
882
+ models_i = kept_i
883
+ else:
884
+ dups = None
885
+ models_i = list(range(len(models)))
886
+
887
+ # standard case
888
+ # TODO reporting
889
+ xcode = []
890
+ if not models:
891
+ xcode += gen.lcom("empty xor list") + gen.bool_var(res, gen.false())
892
+ elif len(models) == 1:
893
+ mod, idx = models[0], models_i[0]
894
+ xcode += gen.lcom("singleton xor list") + \
895
+ self._compileModel(jm, mod, mpath + [idx], res, val, vpath)
896
+ else: # several models are inlined
897
+ if len(models) == 2 and "$ANY" in models:
898
+ xcode += gen.lcom("not-case xor list")
899
+ # get other model
900
+ if models[0] == "$ANY":
901
+ m = models[1]
902
+ idx = models_i[1]
903
+ else:
904
+ m = models[0]
905
+ idx = models_i[0]
906
+ is_m = self._lang.ident("is")
907
+ xcode += (
908
+ gen.bool_var(is_m, declare=True) +
909
+ self._compileModel(jm, m, mpath + [idx], is_m, val, vpath) +
910
+ gen.bool_var(res, gen.not_op(is_m))
911
+ )
912
+ else:
913
+ # TODO collect which model matched for reporting?
914
+ count = self._lang.ident("xc")
915
+ test = self._lang.ident("xr")
916
+ xcode += (
917
+ gen.lcom("generic xor list") +
918
+ gen.int_var(count, gen.const(0), declare=True) +
919
+ gen.bool_var(test, declare=True)
920
+ )
921
+
922
+ # flat if…
923
+ for i, m in enumerate(models):
924
+ idx = models_i[i]
925
+ icode = self._compileModel(jm, m, mpath + [idx], test, val, vpath) + \
926
+ gen.if_stmt(test, gen.inc_var(count))
927
+ if i < 2:
928
+ xcode += icode
929
+ else: # maybe skip
930
+ xcode += gen.if_stmt(gen.num_cmp(count, "<=", gen.const(1)), icode)
931
+
932
+ # verify that only one matched
933
+ xcode += gen.bool_var(res, gen.num_cmp(count, "=", gen.const(1)))
934
+
935
+ if dups:
936
+ code += gen.if_stmt(res, xcode)
937
+ else:
938
+ code += xcode
939
+
940
+ code += self._gen_report(res, f"not one model match [{smpath}]", vpath, True)
941
+
942
+ return code
943
+
944
+ def _compileAnd(self, jm: JsonModel, models: ModelArray, mpath: ModelPath,
945
+ res: Var, val: JsonExpr, vpath: PathExpr,
946
+ known: set[BoolExpr]|None = None) -> Block:
947
+ """Compile an and-list of models."""
948
+
949
+ assert isinstance(models, list) # pyright hint
950
+
951
+ gen = self._lang
952
+ and_known: set[BoolExpr] = set(known or [])
953
+ smpath = json_path(mpath)
954
+ code = []
955
+
956
+ if not models: # empty & list
957
+ return gen.bool_var(res, gen.true())
958
+
959
+ # homogeneous typed list
960
+ same, expected = all_model_type(models, mpath)
961
+ if same:
962
+ # all models have the same ultimate type, use a type shortcut
963
+ type_test = gen.is_a(val, expected)
964
+ code += gen.bool_var(res, type_test)
965
+ and_known.add(type_test)
966
+ else:
967
+ code += gen.bool_var(res, gen.true())
968
+
969
+ # build in reverse order the if structure
970
+ acode: Block = []
971
+ for i, m in reversed(list(enumerate(models))):
972
+ acode = gen.if_stmt(res,
973
+ self._compileModel(jm, m, mpath + [i], res, val, vpath, and_known) +
974
+ acode
975
+ )
976
+ code += acode
977
+
978
+ code += self._gen_report(res, f"not all model match [{smpath}]", vpath, True)
979
+
980
+ return code
981
+
982
+ def _compileModel(self, jm: JsonModel, model: ModelType, mpath: ModelPath,
983
+ res: str, val: str, vpath: str, known: set[BoolExpr]|None = None,
984
+ constrained: bool = False) -> Block:
985
+ # TODO break each level into a separate function and let the compiler inline
986
+ # known = expression already verified
987
+ log.debug(f"mpath={mpath} model={model} res={res} val={val} vpath={vpath}")
988
+ assert isinstance(mpath, list)
989
+ smpath = json_path(mpath)
990
+ gen = self._lang
991
+ known = known or set()
992
+
993
+ code = gen.lcom(f"{json_path(mpath)}")
994
+ match model:
995
+ case None:
996
+ code += gen.bool_var(res, gen.is_a(val, None)) + \
997
+ self._gen_report(res, f"not null [{smpath}]", vpath)
998
+
999
+ case bool():
1000
+ code += gen.bool_var(res, gen.is_a(val, bool)) + \
1001
+ self._gen_report(res, f"not a bool [{smpath}]", vpath)
1002
+
1003
+ case int():
1004
+ expr: BoolExpr|None = gen.is_a(val, int, jm._loose_int)
1005
+ if known is not None:
1006
+ if expr in known:
1007
+ expr = None
1008
+ if model == -1:
1009
+ if known is not None:
1010
+ if expr is not None:
1011
+ known.add(expr)
1012
+ if not expr:
1013
+ expr = gen.true()
1014
+ elif model == 0:
1015
+ compare = gen.num_cmp(
1016
+ gen.value(val, Number if jm._loose_int else int), # type: ignore
1017
+ ">=", gen.const(0))
1018
+ expr = gen.and_op(expr, compare) if expr else compare
1019
+ elif model == 1:
1020
+ compare = gen.num_cmp(
1021
+ gen.value(val, Number if jm._loose_int else int), # type: ignore
1022
+ ">=", gen.const(1))
1023
+ expr = gen.and_op(expr, compare) if expr else compare
1024
+ else:
1025
+ raise ModelError(f"unexpected int value {model} at {smpath}")
1026
+ if expr:
1027
+ looseness = "loose" if jm._loose_int else "strict"
1028
+ code += gen.bool_var(res, expr) + \
1029
+ self._gen_report(res,
1030
+ f"not a {model} {looseness} int [{smpath}]", vpath)
1031
+
1032
+ case float():
1033
+ expr: BoolExpr|None = gen.is_a(val, float, jm._loose_float)
1034
+ if known is not None:
1035
+ if expr in known:
1036
+ expr = None
1037
+ if model == -1.0:
1038
+ if known is not None:
1039
+ if expr is not None:
1040
+ known.add(expr)
1041
+ if not expr:
1042
+ expr = gen.true()
1043
+ elif model == 0.0:
1044
+ compare = gen.num_cmp(
1045
+ gen.value(val, Number if jm._loose_float else float), # type: ignore
1046
+ ">=", gen.const(0.0))
1047
+ expr = gen.and_op(expr, compare) if expr else compare
1048
+ elif model == 1.0:
1049
+ compare = gen.num_cmp(
1050
+ gen.value(val, Number if jm._loose_float else float), # type: ignore
1051
+ ">", gen.const(0.0))
1052
+ expr = gen.and_op(expr, compare) if expr else compare
1053
+ else:
1054
+ raise ModelError(f"unexpected float value {model} at {mpath}")
1055
+ if expr:
1056
+ looseness = "loose" if jm._loose_float else "strict"
1057
+ code += gen.bool_var(res, expr) + \
1058
+ self._gen_report(res, f"not a {model} {looseness} float [{smpath}]", vpath)
1059
+
1060
+ case str():
1061
+ expr: BoolExpr|None = gen.is_a(val, str)
1062
+ if known is not None:
1063
+ # Skip special cases
1064
+ if model == "" or model[0] not in ["$", "="]:
1065
+ # log.info(f"expr={expr} known={known}")
1066
+ if expr in known:
1067
+ expr = None
1068
+ if model == "":
1069
+ if known is not None:
1070
+ if expr is not None:
1071
+ known.add(expr)
1072
+ code += gen.bool_var(res, expr if expr else gen.true())
1073
+ elif model[0] == "_":
1074
+ compare = gen.str_cmp(gen.value(val, str), "=", # type: ignore
1075
+ gen.const(model[1:])) # type: ignore
1076
+ expr = gen.and_op(expr, compare) if expr else compare
1077
+ code += gen.bool_var(res, expr)
1078
+ elif model[0] == "=":
1079
+ # TODO FIXME known
1080
+ # NOTE expr is ignore here
1081
+ (a_cst, value) = constant_value(model, mpath)
1082
+ if not a_cst:
1083
+ raise ModelError(f"unexpected constant: {model}")
1084
+ if value is None:
1085
+ code += gen.bool_var(res, gen.is_a(val, None))
1086
+ elif isinstance(value, bool):
1087
+ ttest = gen.is_a(val, bool)
1088
+ expr = gen.num_cmp(gen.value(val, bool), "=", gen.const(value))
1089
+ if ttest not in known:
1090
+ expr = gen.and_op(ttest, expr)
1091
+ code += gen.bool_var(res, expr)
1092
+ elif isinstance(value, int):
1093
+ ttest = gen.is_a(val, int, jm._loose_int)
1094
+ # FIXME cast depends on type?
1095
+ expr = gen.num_cmp(gen.value(val, int), "=", gen.const(value))
1096
+ if ttest not in known:
1097
+ expr = gen.and_op(ttest, expr)
1098
+ code += gen.bool_var(res, expr)
1099
+ elif isinstance(value, float):
1100
+ ttest = gen.is_a(val, float, jm._loose_float)
1101
+ expr = gen.num_cmp(
1102
+ gen.value(val, Number if jm._loose_float else float), # type: ignore
1103
+ "=", gen.const(value))
1104
+ if ttest not in known:
1105
+ expr = gen.and_op(ttest, expr)
1106
+ code += gen.bool_var(res, expr)
1107
+ # elif isinstance(value, str):
1108
+ # compare = gen.str_eq(gen.str_val(val), gen.str_cst(model[1:]))
1109
+ # expr = gen.and_op(expr, compare) if expr else compare
1110
+ # code += gen.bool_var(res, expr)
1111
+ else:
1112
+ raise ModelError(f"unexpected constant type: {tname(value)}")
1113
+ elif model[0] == "$":
1114
+ call = self._dollarExpr(jm, model, val, vpath)
1115
+ code += gen.bool_var(res, call)
1116
+ elif model[0] == "/":
1117
+ code += gen.lcom(f"{self._esc(model)}")
1118
+ call = self._regExpr(jm, model, val, vpath)
1119
+ code += gen.bool_var(res, gen.and_op(expr, call) if expr else call)
1120
+ else: # simple string
1121
+ compare = gen.str_cmp(gen.value(val, str), "=", # type: ignore
1122
+ gen.const(model)) # type: ignore
1123
+ expr = gen.and_op(expr, compare) if expr else compare
1124
+ code += gen.bool_var(res, expr)
1125
+ if self._report:
1126
+ smodel = model if model else "string"
1127
+ code += self._gen_report(res, f"unexpected {smodel} [{smpath}]", vpath)
1128
+
1129
+ case list():
1130
+ expr: BoolExpr|None = gen.is_a(val, list)
1131
+ smpath = json_path(mpath)
1132
+
1133
+ if known is not None:
1134
+ if expr in known:
1135
+ expr = None
1136
+ if expr is not None:
1137
+ known.add(expr)
1138
+
1139
+ if len(model) == 0: # []
1140
+ length = gen.num_cmp(gen.arr_len(val), "=", gen.const(0))
1141
+ expr = gen.and_op(expr, length) if expr else length
1142
+ code += gen.bool_var(res, expr)
1143
+ # SHORT RES?
1144
+
1145
+ elif len(model) == 1: # homogeneous vector
1146
+
1147
+ if model[0] == "$ANY":
1148
+ loop = gen.lcom("accept any array") + gen.nope()
1149
+ else:
1150
+ arrayid = gen.ident("arr")
1151
+ idx, item, lpath = f"{arrayid}_idx", f"{arrayid}_item", f"{arrayid}_lpath"
1152
+
1153
+ loop = gen.arr_loop(val, idx, item,
1154
+ gen.path_var(lpath, gen.path_val(vpath, idx, False), True) +
1155
+ self._compileModel(jm, model[0], mpath + [0],
1156
+ res, item,
1157
+ gen.path_lvar(lpath, vpath)) + # type: ignore
1158
+ gen.if_stmt(gen.not_op(res), gen.brk()))
1159
+
1160
+ code += (
1161
+ gen.bool_var(res, expr if expr else gen.true()) +
1162
+ gen.if_stmt(res, loop) if expr else loop
1163
+ )
1164
+
1165
+ else:
1166
+ # non empty list of models, aka tuple
1167
+ lpath = gen.ident("lpath")
1168
+ lpath_ref: PathExpr = gen.path_lvar(lpath, vpath) # type: ignore
1169
+ if not constrained:
1170
+ length = gen.num_cmp(gen.arr_len(val), "=", gen.const(len(model)))
1171
+ expr = gen.and_op(expr, length) if expr else length
1172
+ code += gen.bool_var(res, expr)
1173
+ # else inside a @ with constraints, so we do not check the len
1174
+ # body = gen.path_var(lpath, declare=True)
1175
+ body = []
1176
+ for i, m in reversed(list(enumerate(model))):
1177
+ body = gen.if_stmt(
1178
+ res,
1179
+ gen.path_var(lpath, gen.path_val(vpath, i, False), declare=True) +
1180
+ # FIXME generated variable reference…
1181
+ self._compileModel(
1182
+ jm, model[i], mpath + [i],
1183
+ res, gen.arr_item_val(val, i), lpath_ref) +
1184
+ body)
1185
+ code += body
1186
+ else:
1187
+ # assume varlen tuple: [ A, B, C* ]
1188
+ arlen = gen.ident("len")
1189
+ code += gen.path_var(lpath, None, declare=True)
1190
+ body = []
1191
+
1192
+ # last model for repeats
1193
+ lmodel, start = model[-1], len(model)-1
1194
+
1195
+ if lmodel != "$ANY":
1196
+ idx = gen.ident("idx")
1197
+ body += gen.int_loop(idx, start, arlen,
1198
+ gen.path_var(lpath, gen.path_val(vpath, idx, False)) +
1199
+ self._compileModel(jm, lmodel, mpath + [start], res,
1200
+ gen.arr_item_val(val, idx), lpath_ref) +
1201
+ gen.if_stmt(gen.not_op(res), gen.brk())
1202
+ )
1203
+
1204
+ for i, m in reversed(list(enumerate(model[:-1]))):
1205
+ ith_check = \
1206
+ gen.if_stmt(gen.num_cmp(arlen, ">", i),
1207
+ gen.path_var(lpath, gen.path_val(vpath, i, False)) +
1208
+ self._compileModel(jm, m, mpath + [i], res,
1209
+ gen.arr_item_val(val, i), lpath_ref))
1210
+ if body:
1211
+ body = ith_check + gen.if_stmt(res, body)
1212
+ else:
1213
+ body = ith_check
1214
+
1215
+ # compute len before checking array items
1216
+ body = gen.int_var(arlen, gen.arr_len(val), declare=True) + body
1217
+
1218
+ if lmodel == "$ANY":
1219
+ body += gen.lcom("no array tail value checks needed")
1220
+
1221
+ code += (
1222
+ gen.bool_var(res, expr if expr else gen.true()) +
1223
+ gen.if_stmt(res, body) if expr else body
1224
+ )
1225
+
1226
+ code += self._gen_report(res, f"not array or unexpected array [{smpath}]", vpath)
1227
+
1228
+ case dict():
1229
+ assert isinstance(model, dict) # pyright hint
1230
+ assert "+" not in model, "merge must have been preprocessed"
1231
+ if "@" in model: # TODO known?
1232
+ code += self._compileConstraint(jm, model, mpath, res, val, vpath)
1233
+ elif "|" in model:
1234
+ models = model["|"]
1235
+ assert isinstance(models, list) # pyright hint
1236
+ code += self._compileOr(jm, models, mpath + ["|"], res, val, vpath, known)
1237
+ elif "&" in model:
1238
+ models = model["&"]
1239
+ assert isinstance(models, list) # pyright hint
1240
+ code += self._compileAnd(jm, models, mpath + ["&"], res, val, vpath, known)
1241
+ elif "^" in model:
1242
+ models = model["^"]
1243
+ assert isinstance(models, list) # pyright hint
1244
+ code += self._compileXor(jm, models, mpath + ["^"], res, val, vpath, known)
1245
+ else:
1246
+ # new function to check the object
1247
+ objid = gen.ident(self._prefix + "obj")
1248
+ ocode: Block = (
1249
+ gen.lcom(f"object {json_path(mpath)}") +
1250
+ gen.sub_fun(objid,
1251
+ self._compileObject(jm, model, mpath, objid, "res", "val", "path"))
1252
+ )
1253
+ self._code.subs(ocode)
1254
+
1255
+ # call object check and possibly report
1256
+ code += gen.bool_var(res, gen.check_call(objid, val, vpath))
1257
+ code += self._gen_report(res, f"unexpected element [{smpath}]", vpath)
1258
+
1259
+ # record object function for path
1260
+ self._paths[tuple(mpath)] = objid
1261
+
1262
+ if "#" in model:
1263
+ comment = model["#"].replace("\n", " ") # type: ignore
1264
+ code = gen.lcom(comment) + code
1265
+
1266
+ case _:
1267
+ raise ModelError(f"unexpected model type: {tname(model)}")
1268
+
1269
+ return code
1270
+
1271
+ def _getName(self, jm: JsonModel, name: str) -> str:
1272
+ """Ensure global unique names for internal functions."""
1273
+ # FIXME global name space! prefix with jm._id ?
1274
+ if name not in self._names:
1275
+ self._names[name] = self._lang.ident(self._prefix + "f")
1276
+ log.debug(f"{name} -> {self._names[name]}")
1277
+ return self._names[name]
1278
+
1279
+ def _getNameRef(self, jm: JsonModel, ref: str, path: ModelPath) -> str:
1280
+ assert jm._isRef(ref), f"must be a reference: {ref}"
1281
+
1282
+ # FIXME shortcut hack
1283
+ if ref == "$#" and ref in self._names:
1284
+ return self._names[ref]
1285
+
1286
+ try:
1287
+ gref = jm._defs.gget(ref)
1288
+ except KeyError:
1289
+ if self._debug:
1290
+ log.debug(f"_getNameRef[{jm._id},{jm._defs._id}]({ref}) at {path}")
1291
+ log.debug(f" with gmap={jm._defs._gmap}")
1292
+ # FIXME maybe we already have a global reference?
1293
+ gref = ref
1294
+
1295
+ log.debug(f"name ref: gref={gref} globs={self._globs} names={self._names}")
1296
+ if gref not in self._names:
1297
+ jm = self._globs[gref] # type: ignore
1298
+ if jm._id not in self._compiled:
1299
+ self._to_compile[jm._id] = (jm, gref)
1300
+ self._names[gref] = f"json_model_{jm._id}"
1301
+
1302
+ # log.debug(f"name ref: ref={ref} gref={gref} at {path}: {self._names[gref]}")
1303
+ return self._names[gref]
1304
+
1305
+ def _compileName(self, jm: JsonModel,
1306
+ name: str, model: ModelType, mpath: ModelPath, local: bool = False):
1307
+ """Compile a model under a given name in a given scope."""
1308
+ log.debug(f"compile name={name} jm={jm._id} mpath={mpath} names={self._names}")
1309
+
1310
+ # TODO simplify, clarify, remove
1311
+ # memoize the associated function name that can be retrieved if there is a recursion
1312
+ fun2 = None
1313
+ hpath = tuple(mpath)
1314
+ if hpath in self._paths:
1315
+ fun = self._paths[hpath]
1316
+ if name in self._names:
1317
+ fun2 = self._names[name]
1318
+ else:
1319
+ self._names[name] = fun
1320
+ else:
1321
+ fun = self._getName(jm, name)
1322
+ self._paths[hpath] = fun
1323
+
1324
+ body = self._lang.bool_var("res", declare=True) + \
1325
+ self._compileModel(jm, model, mpath, "res", "val", "path", set()) + \
1326
+ self._lang.ret("res")
1327
+
1328
+ self._code.sub(fun, body, comment=f"check {name} ({json_path(mpath)})")
1329
+
1330
+ if fun2 and fun2 != fun:
1331
+ raise NotImplementedError("2 functions for one?!")
1332
+ # code.add(0, "# named root")
1333
+ # code.add(0, f"{fun2} = {fun}")
1334
+
1335
+ # FIXME!
1336
+ # NOTE yuk! the function may have been generated as a side effect of the previous call.
1337
+ # if so, this version is simply discarded
1338
+ if hpath not in self._generated:
1339
+ # on a named root, two names for the same path
1340
+ self._generated.add(hpath)
1341
+ else:
1342
+ log.warning("should not get there?!")
1343
+
1344
+ def compileOneJsonModel(self, jm: JsonModel, name: str, path: ModelPath, local: bool = False):
1345
+ if jm._id not in self._compiled:
1346
+ self._compiled.add(jm._id)
1347
+ if name not in self._names:
1348
+ self._names[name] = "json_model_" + str(jm._id)
1349
+ self._compileName(jm, name, jm._model, path, local)
1350
+
1351
+ def compileJsonModelHead(self, model: JsonModel):
1352
+ # $# special handing
1353
+ head_model_fun = f"json_model_{model._head._id}"
1354
+ self._names["$#"] = head_model_fun
1355
+ self._names[""] = head_model_fun
1356
+
1357
+ entries: PropMap = {
1358
+ "": head_model_fun,
1359
+ }
1360
+
1361
+ # compile direct definitions
1362
+ for n, jm in model._defs.items():
1363
+ dn = f"${n}"
1364
+ # special handling of the resolution gives another model
1365
+ # eg "foo": "$bla"
1366
+ if dn in self._globs and self._globs[dn]._id != jm._id: # type: ignore
1367
+ # skip compilation and point to other function
1368
+ entries[n] = f"json_model_{self._globs[dn]._id}" # type: ignore
1369
+ else:
1370
+ # actual compilation of a new function
1371
+ entries[n] = f"json_model_{jm._id}"
1372
+ self.compileOneJsonModel(jm, dn, ["$" + n], False)
1373
+ log.debug(f"after {n} ({jm._id}): {self._names}")
1374
+
1375
+ # compile root
1376
+ self.compileOneJsonModel(model, "$", [], False)
1377
+
1378
+ # TODO possibly add entries for referenced models? under an option?
1379
+
1380
+ # compile other encountered references
1381
+ while todo := set(self._to_compile.keys()) - self._compiled:
1382
+ jm, gref = self._to_compile[min(todo)]
1383
+ self.compileOneJsonModel(jm, gref, [gref], True)
1384
+
1385
+ # generate mapping, name must be consistent with data/clang_*.c
1386
+ self._code.pmap(f"{self._code._entry}_map", entries, True)
1387
+
1388
+ return self._code
1389
+
1390
+
1391
+ def xstatic_compile(
1392
+ model: JsonModel,
1393
+ fname: str = "check_model",
1394
+ *,
1395
+ lang: str = "py",
1396
+ prefix: str = "_jm_",
1397
+ relib: str|None = None,
1398
+ map_threshold: int = 3,
1399
+ execute: bool = True,
1400
+ map_share: bool = False,
1401
+ debug: bool = False,
1402
+ report: bool = True,
1403
+ ) -> Code:
1404
+ """Generate the check source code for a model.
1405
+
1406
+ - model: JSON Model root to compile.
1407
+ - fname: target function name.
1408
+ - lang: name of target language.
1409
+ - prefix: prefix for generated functions.
1410
+ - map_threshold: inline property checks under this threshold.
1411
+ - map_share: share generated property maps.
1412
+ - report: whether to generate code to report rejection reasons.
1413
+ - debug: debugging mode generates more traces.
1414
+ """
1415
+ # target language
1416
+ if lang == "py":
1417
+ from .python import Python
1418
+ language = Python(debug=debug, with_report=report, with_path=report,
1419
+ relib=relib or "re2")
1420
+ elif lang == "c":
1421
+ from .clang import CLangJansson
1422
+ language = CLangJansson(debug=debug, with_report=report, with_path=report,
1423
+ relib=relib or "re2")
1424
+ elif lang == "js":
1425
+ from .javascript import JavaScript
1426
+ language = JavaScript(debug=debug,
1427
+ with_report=report, with_path=report, relib=relib or "re")
1428
+ elif lang in ("plpgsql", "sql"):
1429
+ from .plpgsql import PLpgSQL
1430
+ language = PLpgSQL(debug=debug,
1431
+ with_report=report, with_path=report, relib=relib or "re")
1432
+ else:
1433
+ raise NotImplementedError(f"no support yet for language: {lang}")
1434
+
1435
+ # cource code generator
1436
+ gen = CodeGenerator(model._globs, language, fname, prefix=prefix, # type: ignore
1437
+ execute=execute, map_threshold=map_threshold, map_share=map_share,
1438
+ debug=debug, report=report)
1439
+
1440
+ # generate
1441
+ code = gen.compileJsonModelHead(model)
1442
+
1443
+ # debug and log.debug(f"code = {code}")
1444
+ return code