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/model.py ADDED
@@ -0,0 +1,1084 @@
1
+ import copy
2
+ import re
3
+ import typing
4
+ from collections.abc import MutableMapping
5
+ import json
6
+
7
+ from .mtypes import ModelPath, ModelTrafo, ModelRename, ModelDefs, ModelType
8
+ from .mtypes import ModelError, Jsonable, JsonSchema, JsonObject
9
+ from .utils import log, tname, PREDEF_RE, UUID_RE
10
+ from .recurse import recModel, allFlt, noRwt, _recModel
11
+ from .resolver import Resolver
12
+
13
+ # FIXME
14
+ JsonModel = typing.NewType("JsonModel", None) # pyright: ignore
15
+
16
+ type SymTable = dict[str, JsonModel]
17
+ type Globals = dict[str, str]
18
+ type ModelRef = list[str] # $stuff#name#inside
19
+
20
+ def json_dump(j: Jsonable):
21
+ return json.dumps(j, indent=2, sort_keys=False)
22
+
23
+
24
+ class Symbols(MutableMapping[str, JsonModel]):
25
+ """JSON Model Symbol Table.
26
+
27
+ This associate models to names, which may be global or local.
28
+ """
29
+
30
+ def __init__(self, mid):
31
+
32
+ self._id = mid
33
+ # symbol definitions
34
+ self._syms: SymTable = {}
35
+ # local names to global names
36
+ self._gmap: Globals = {}
37
+
38
+ def toJSON(self, rec: bool = False):
39
+ """Display as JSON."""
40
+ if rec:
41
+ data = {}
42
+ data["#"] = f"Symbols {self._id}"
43
+ data["__gmap__"] = self._gmap
44
+ data.update({n: jm.toJSON(rec) for n, jm in self.items()})
45
+ else:
46
+ data = f"Symbols {self._id}"
47
+ return data
48
+
49
+ def __str__(self):
50
+ return str({n: m._id for n, m in self.items()})
51
+
52
+ # local to global symbol
53
+ def gset(self, ref: str, gref: str):
54
+ self._gmap[ref] = gref
55
+
56
+ def gget(self, ref: str):
57
+ return self._gmap[ref]
58
+
59
+ def ghas(self, ref: str):
60
+ return ref in self._gmap
61
+
62
+ # local to model
63
+ def __setitem__(self, k, v):
64
+ return self._syms.__setitem__(k, v)
65
+
66
+ def __getitem__(self, k):
67
+ return self._syms.__getitem__(k)
68
+
69
+ def __delitem__(self, k):
70
+ return self._syms.__delitem__(k)
71
+
72
+ def __len__(self):
73
+ return self._syms.__len__()
74
+
75
+ def __iter__(self):
76
+ return self._syms.__iter__()
77
+
78
+
79
+ class JsonModel:
80
+ """Represent a JSON Model v2.
81
+
82
+ There are 3 kinds of JSON Models:
83
+
84
+ 1. The head json model with all its dependent models, which is the first
85
+ root model, holds the global symbol table and a list of all
86
+ its related models from internal definitions or external references.
87
+ 2. Root models which represent distinct loaded files,
88
+ and define an associated naming scope possibly shared with local defs.
89
+ 3. Local models created for the internal definitions of a root model,
90
+ and share their naming scope with their parent.
91
+
92
+ When providing a master model with ~, these models are loaded independently,
93
+ i.e. they are considered a head model.
94
+ """
95
+
96
+ # keyword characters
97
+ LIST_KW = ["|", "&", "^", "+"]
98
+ ROOT_KW = ["$", "%", "~"]
99
+ SCAL_KW = ["@"]
100
+ CONS_KW = ["!", "#", "<", "<=", ">", ">=", "=", "!="]
101
+ TRAN_KW = ["*", "/"]
102
+ KEYWORDS = LIST_KW + ROOT_KW + SCAL_KW + CONS_KW + TRAN_KW
103
+
104
+ # sentinel characters
105
+ # $: reference
106
+ # /: regular expression
107
+ # _: escape character for string
108
+ # =: scalar (not string) constants
109
+ # .: keyword names
110
+ STR_SENTINELS = "/$_=."
111
+ PROP_SENTINELS = "?!"
112
+ SENTINELS = STR_SENTINELS + PROP_SENTINELS
113
+
114
+ PREDEFS: ModelDefs = {
115
+ # specials
116
+ "ANY": {"&": []},
117
+ "NONE": {"|": []},
118
+ # type inference
119
+ "NULL": None,
120
+ "BOOL": True,
121
+ "BOOLEAN": True,
122
+ "INT": -1,
123
+ "INTEGER": -1,
124
+ "I32": -1, # min/max?
125
+ "I64": -1, # min/max?
126
+ "U32": 0, # max?
127
+ "U64": 0, # max?
128
+ "FLOAT": -1.0,
129
+ "F32": -1.0,
130
+ "F64": -1.0,
131
+ "NUMBER": {"|": [-1, -1.0]},
132
+ "STRING": "",
133
+ "URL": r"/^\w+://.*$/", # FIXME relative URL?
134
+ "DATE": r"/^\d\d\d\d-\d?\d-\d?\d$/", # FIXME
135
+ "TIME": r"/^[T ]?\d\d:\d\d:\d\d(\.\d\d\d)?(Z|[-+]\d\d(:?\d\d)?$/", # FIXME
136
+ "DATETIME": "", # FIXME
137
+ "UUID": "/^" + UUID_RE + "$/",
138
+ "REGEX": "", # FIXME
139
+ "EXREG": "",
140
+ "URI": r"^\w+:.*$/", # TODO improve
141
+ "EMAIL": r"^(?i)[a-z0-9_.]+@[a-z0-9_.]+$",
142
+ # to be continued…
143
+ # o = optional
144
+ "oBOOL": {"|": [None, "$BOOL"]},
145
+ "oINT": {"|": [None, "$INT"]},
146
+ "oFLOAT": {"|": [None, "$FLOAT"]},
147
+ "oNUMBER": {"|": [None, "$NUMBER"]},
148
+ "oSTRING": {"|": [None, "$STRING"]},
149
+ "oURL": {"|": [None, "$URL"]},
150
+ "oDATE": {"|": [None, "$DATE"]},
151
+ "oUUID": {"|": [None, "$UUID"]},
152
+ "oREGEX": {"|": [None, "$REGEX"]},
153
+ # to be continued…
154
+ }
155
+
156
+ # OFFICIAL VERSION URLS
157
+ VERSION_URLS = {
158
+ "https://json-model.org/models/json-model", # latest
159
+ "https://json-model.org/models/json-model-v2",
160
+ }
161
+
162
+ def __init__(self,
163
+ model: ModelType,
164
+ resolver: Resolver,
165
+ *,
166
+ url: str = "",
167
+ head: JsonModel|None = None,
168
+ scope: Symbols|None = None,
169
+ debug: int = 0,
170
+ loose_int: bool|None = None,
171
+ loose_float: bool|None = None,
172
+ ):
173
+
174
+ # the root model cannot share a scope
175
+ assert head is not None or head is None and scope is None
176
+
177
+ if head is None: # this is a (new) root model
178
+ # self._lock = threading.RLock()
179
+ self._is_head = True
180
+ self._head = self
181
+ self._id = 1
182
+ self._models = {1: self}
183
+ self._nmodels = 1
184
+ self._globs = Symbols(0)
185
+ self._is_root = True
186
+ self._defs = Symbols(1)
187
+ self._externs = []
188
+ else: # set root model this model belongs to
189
+ # self._lock = None
190
+ self._is_head = False
191
+ self._head = head
192
+ self._nmodels = None
193
+ self._models = None
194
+ # with head._lock:
195
+ assert isinstance(head._nmodels, int) and isinstance(head._models, dict)
196
+ head._nmodels += 1
197
+ self._id = head._nmodels
198
+ head._models[self._id] = self
199
+ self._globs = head._globs
200
+ if scope is None:
201
+ self._is_root = True
202
+ self._defs = Symbols(self._id)
203
+ self._externs = []
204
+ else:
205
+ self._is_root = False
206
+ self._defs = scope
207
+ self._externs = None
208
+
209
+ # unmodified parameters
210
+ self._init_md = model
211
+ self._resolver = resolver
212
+ self._url = url
213
+ self._debug = debug
214
+
215
+ # copy parameter which may be modified
216
+ model = copy.deepcopy(model)
217
+
218
+ # %: names and rewrites
219
+ self._init_pc: dict[str, ModelType] = {}
220
+ self._name: ModelRename = {}
221
+ self._rewrite: dict[str, ModelTrafo] = {}
222
+ self._imports: list[str] = []
223
+
224
+ if debug:
225
+ log.debug(f"{self._id}: model for {url} "
226
+ f"{head._id if head else '-'} {scope._id if scope else '-'}")
227
+
228
+ # set loose/strict int/float
229
+ if isinstance(model, dict) and "#" in model:
230
+ meta = model["#"]
231
+ if isinstance(meta, str):
232
+ # default value from parameters
233
+ li: bool|None = loose_int
234
+ lf: bool|None = loose_float
235
+ # local overrides
236
+ if "JSON_MODEL_LOOSE_NUMBER" in meta:
237
+ li = True
238
+ lf = True
239
+ elif "JSON_MODEL_STRICT_NUMBER" in meta:
240
+ li = False
241
+ lf = False
242
+ if "JSON_MODEL_LOOSE_INT" in meta:
243
+ li = True
244
+ elif "JSON_MODEL_STRICT_INT" in meta:
245
+ li = False
246
+ if "JSON_MODEL_LOOSE_FLOAT" in meta:
247
+ lf = True
248
+ elif "JSON_MODEL_STRICT_FLOAT" in meta:
249
+ lf = False
250
+ self._loose_int = False if li is None else li
251
+ self._loose_float = False if lf is None else lf
252
+ else:
253
+ self._loose_int = loose_int if loose_int is not None else False
254
+ self._loose_float = loose_float if loose_float is not None else False
255
+ else:
256
+ self._loose_int = loose_int if loose_int is not None else False
257
+ self._loose_float = loose_float if loose_float is not None else False
258
+
259
+ # root models can have % $ ~ keywords
260
+ if isinstance(model, dict) and "%" in model:
261
+ assert self._is_root
262
+ lpath = ["%"]
263
+ model_pc = model["%"]
264
+ del model["%"]
265
+ assert isinstance(model_pc, dict), "% expects an object"
266
+
267
+ bads = {
268
+ name: kw
269
+ for name, kw in model_pc.items()
270
+ if (not isinstance(name, str) or name.startswith(".") and
271
+ isinstance(kw, str) and kw not in JsonModel.KEYWORDS)
272
+ }
273
+ if bads:
274
+ raise ModelError(f"keyword renames must be json model keywords at {lpath}: {bads}")
275
+
276
+ # keyword localization
277
+ self._name = {
278
+ name: kw
279
+ for name, kw in model_pc.items()
280
+ if isinstance(name, str) and name.startswith(".") and isinstance(kw, str)
281
+ }
282
+
283
+ # FIXME what is the scope of renamings, eg wrt references?
284
+ model = self.rename(model, [], True)
285
+ assert isinstance(model, dict)
286
+
287
+ # reference imports
288
+ if "<" in model_pc:
289
+ imports = model_pc["<"]
290
+ if isinstance(imports, str):
291
+ imports = [imports]
292
+ else:
293
+ assert (isinstance(imports, list) and
294
+ all(map(lambda i: isinstance(i, str), imports)))
295
+ self._imports = imports # type: ignore
296
+
297
+ # extract rewrites
298
+ # TODO check name syntax? $Path#To#Def.path.to.prop
299
+ self._rewrite = {
300
+ name: rw
301
+ for name, rw in model_pc.items()
302
+ if isinstance(name, str) and
303
+ not name.startswith(".") and
304
+ name not in ("#", "<")
305
+ }
306
+
307
+ # log.warning(f"rewrite={self._rewrite}")
308
+
309
+ # save initial definition
310
+ self._init_pc = model_pc
311
+
312
+ if isinstance(model, dict) and "$" in model:
313
+ assert self._is_root, f"{self._id}: {self._is_head}/{self._is_root} with $"
314
+ dollar = model["$"]
315
+ del model["$"]
316
+ assert isinstance(dollar, dict), "$ expects an object"
317
+ # check that keys are str
318
+ assert all(map(lambda k: isinstance(k, str), dollar.keys())), "$ keys must be str"
319
+ # extract current model identifier if provided
320
+ if u := dollar.get(""):
321
+ assert isinstance(u, str)
322
+ if not self._isUrlRef(f"${u}"):
323
+ raise ModelError(f"model identifier should be a url: {u}")
324
+ if self._url != "" and u != self._url:
325
+ log.info(f"inconsistent url identifier: {u}")
326
+ self._url = u # override
327
+ # TODO restrict names?
328
+ # extract actual definitions
329
+ self._defs.update({
330
+ n: JsonModel(m, resolver, url=self._url + "#" + n,
331
+ head=self._head, scope=self._defs, debug=self._debug,
332
+ loose_int=self._loose_int, loose_float=self._loose_float)
333
+ for n, m in dollar.items()
334
+ if isinstance(n, str) and n not in ("#", "")
335
+ })
336
+ # warn about possibly missing $
337
+ for name, value in self._defs.items():
338
+ m = value._model
339
+ if isinstance(m, str) and re.search("^((https?|file)://|\\.)", m):
340
+ log.warning(f"url-looking {name}: "
341
+ "add missing $ or prefix with _ for string constants")
342
+ # keep initial definitions
343
+ self._init_dl = dollar
344
+ else:
345
+ self._init_dl = None
346
+
347
+ if isinstance(model, dict) and "~" in model:
348
+ assert self._is_root
349
+ version = model["~"]
350
+ del model["~"]
351
+ # FIXME should accept a *model*, not just a URL? or not?
352
+ if not isinstance(version, str):
353
+ raise ModelError(f"invalid model version type: {tname(version)}")
354
+ log.debug(f"url={url} version={version}")
355
+ # FIXME prevent all recursion cycles!?
356
+ if version != self._url: # prevent direct recursion
357
+ # FIXME ~ should be a head model
358
+ self._spec = self.load(version, ["~"], True)
359
+ else:
360
+ self._spec = self
361
+ log.info(f"renaming {self._id} from ~")
362
+ model = self._spec.rename(model, [], True)
363
+ else:
364
+ # FIXME add a default?
365
+ self._spec = None
366
+
367
+ self._model = model
368
+
369
+ # import definitions
370
+ if self._imports:
371
+ log.info(f"importing model definitions from {self._imports}")
372
+ assert isinstance(self._imports, list) and \
373
+ all(isinstance(s, str) and s and s[0] == "$" for s in self._imports), \
374
+ "imports must be an array of references"
375
+ for i, ref in enumerate(self._imports):
376
+ jsub = self.resolveRef(ref, ["%", "~", i], False)
377
+ if len(jsub._defs) > 0:
378
+ for name, jm in jsub._defs.items():
379
+ if name in self._defs:
380
+ raise ModelError(f"cannot override definition {name} in {self._url} from {ref}")
381
+ self._defs[name] = jm
382
+ else:
383
+ log.warning(f"no definition to import from {ref}")
384
+
385
+ if self._is_root:
386
+ # loading twice, rewriting may add references…
387
+ self.allLoads()
388
+ self.rewrite()
389
+
390
+ if self._is_head:
391
+ # hmmm… the above rewriting may have changed external dependencies,
392
+ # probably it would be enough to rewrite only the changed externals,
393
+ # but which one were changed is not visible from here so we load again
394
+ # everything, just in case.
395
+ for mid in reversed(list(self._head._models.keys())): # pyright: ignore
396
+ jm = self._head._models[mid] # pyright: ignore
397
+ if jm._is_root:
398
+ jm.allLoads()
399
+ self.scope(self._globs, [], set(), {})
400
+ # _ = self._debug and log.debug(f"globs = {self._globs}")
401
+ self.unload()
402
+
403
+ def load(self, url: str, path: ModelPath, is_head: bool = False) -> JsonModel:
404
+ """Retrieve external JSON Model for a URL."""
405
+ log.debug(f"{self._id}: getting {url} at {path}")
406
+ # get raw json, may be cached
407
+ j = self._resolver(url, path=path)
408
+ # build a *new* model: distinct refs to the same url are treated independently
409
+ # because each may be rewritten independently.
410
+ # If you want to share, add an explicit definition to a url and use it afterwards.
411
+ return JsonModel(j, self._resolver, url=url, head=None if is_head else self._head,
412
+ scope=None, debug=self._debug,
413
+ loose_int=self._loose_int, loose_float=self._loose_float)
414
+
415
+ def allLoads(self):
416
+ """Load externals, switch un-named externals to local definitions."""
417
+
418
+ assert self._is_root
419
+ log.debug(f"{self._id}: IN allLoads on {self._url}")
420
+
421
+ def follow(model: str, path: ModelPath) -> JsonModel:
422
+ """Follow a simple URL model till the end of the world."""
423
+
424
+ assert isinstance(model, str) and self._isUrlRef(model)
425
+ followed, jm = set(), None
426
+ current: Jsonable = model
427
+
428
+ while self._isUrlRef(current):
429
+ assert isinstance(current, str) # pyright hint
430
+ if self._debug >= 2:
431
+ log.debug(f"{self._id}: following {current} at {path}")
432
+
433
+ # NOTE the first url does not have a fragment, but subsequent urls may have
434
+ if "#" in model:
435
+ url, frag = current[1:].split("#", 1)
436
+ else:
437
+ url, frag = current[1:], None
438
+
439
+ if url in followed:
440
+ raise ModelError(f"infinite recursion when loading {url} at {path}")
441
+
442
+ log.debug(f"{self._id}: loading {url}")
443
+ followed.add(url)
444
+ jm = self.load(url, path)
445
+ log.debug(f"{self._id}: head models: "
446
+ f"{[mid for mid in sorted(self._head._models.keys())]}") # pyright: ignore
447
+
448
+ # handle sequence of fragments
449
+ while frag:
450
+ if "#" in frag:
451
+ name, frag = frag.split("#", 1)
452
+ else:
453
+ name, frag = frag, None
454
+ jm = jm._defs[name]
455
+
456
+ current = jm._model
457
+
458
+ assert jm is not None # pyright hint
459
+ return jm
460
+
461
+ # substitute $<URL>#... with $__external_X#...
462
+ def ldRwt(model: ModelType, path: ModelPath) -> ModelType:
463
+
464
+ if isinstance(model, str) and self._isUrlRef(model):
465
+ log.debug(f"{self._id}: ldRwt at {path} with {model}")
466
+ assert self._externs is not None # pyright hint
467
+ if "#" in model:
468
+ model, frag = model.split("#", 1)
469
+ else:
470
+ frag = None
471
+ ext = follow(model, path)
472
+ name = f"__external_{len(self._externs)}"
473
+ self._defs[name] = ext
474
+ self._externs.append(ext)
475
+ log.debug(f"swith: {name} {model}")
476
+ return "$" + name + (("#" + frag) if frag else "")
477
+
478
+ return model
479
+
480
+ # log.debug(f"{self._id}: root url")
481
+ if self._isUrlRef(self._model):
482
+ # if the root schema is a string, there was no definitions nor rewrites!
483
+ # ??? assert len(self._defs) == 0 and isinstance(self._model, str)
484
+ assert isinstance(self._model, str) # pyright helper
485
+ self.override(follow(self._model, []))
486
+
487
+ names = list(self._defs.keys())
488
+ for name in names:
489
+ # log.debug(f"{self._id}: {name} url")
490
+ model = self._defs[name]._model
491
+ if self._isUrlRef(model):
492
+ assert isinstance(model, str) # pyright hint
493
+ self._defs[name] = follow(model, [name])
494
+
495
+ # look for other external references in the model definitions
496
+ _recModel(self._defs[name]._model, [name], allFlt, ldRwt, True, False)
497
+
498
+ # look for external references in the main model
499
+ _recModel(self._model, [], allFlt, ldRwt, True, True)
500
+
501
+ log.debug(f"{self._id}: OUT allLoads on {self._url}")
502
+
503
+ def override(self, jm: JsonModel):
504
+ """Self replace model with another model, for handling $<url>."""
505
+ # NO _is_root, init_*
506
+ log.debug(f"overriding {self._id} with {jm._id}")
507
+ assert self._is_root and jm._is_root
508
+ assert self._globs._id == jm._globs._id
509
+ self._id = jm._id
510
+ self._defs = jm._defs
511
+ self._name = jm._name
512
+ self._rewrite = jm._rewrite
513
+ self._externs = jm._externs
514
+ self._model = jm._model
515
+ self._loose_int = jm._loose_int
516
+ self._loose_float = jm._loose_float
517
+
518
+ def unload(self):
519
+ """Delete unused models."""
520
+ assert self._is_head and isinstance(self._models, dict)
521
+ todo, keep = {self._id}, set()
522
+
523
+ # transitive closure
524
+ while todo:
525
+ ntodo = set()
526
+ keep.update(todo)
527
+ for mid in sorted(todo):
528
+ model = self._models[mid]
529
+ if not model._is_root:
530
+ continue
531
+ for _, jm in model._defs.items():
532
+ if jm._id not in keep:
533
+ ntodo.add(jm._id)
534
+ todo = ntodo
535
+
536
+ # cleanup
537
+ total = len(self._models)
538
+ for mid in list(self._models.keys()):
539
+ if mid not in keep:
540
+ del self._models[mid]
541
+
542
+ # debug summary
543
+ if self._debug:
544
+ kept = " ".join(str(mid) for mid in sorted(keep))
545
+ log.debug(f"{self._id}: unload {len(self._models)}/{total} models kept ({kept})")
546
+
547
+ #
548
+ # Display
549
+ #
550
+ def toJSON(self, recurse: bool = True, verbose: bool = False) -> Jsonable:
551
+ """Convenient JsonModel debug display."""
552
+ data = {
553
+ "type": "head" if self._is_head else "root" if self._is_root else "local",
554
+ "id": self._id,
555
+ "url": self._url,
556
+ "model": self._model,
557
+ "int": "loose" if self._loose_int else "strict",
558
+ "float": "loose" if self._loose_float else "strict",
559
+ }
560
+ if verbose:
561
+ data["init"] = self._init_md
562
+ if self._is_head:
563
+ assert self._models is not None and isinstance(self._models, dict) # pyright hint
564
+ data["dependents"] = {
565
+ mid: self._head._models[mid]._url # pyright: ignore
566
+ for mid in sorted(self._head._models) # pyright: ignore
567
+ }
568
+ if recurse:
569
+ data["globals"] = {
570
+ name: jm._id # f"Model {jm._id}"
571
+ for name, jm in self._globs.items()
572
+ }
573
+ else:
574
+ data["globals"] = f"Symbols {self._globs._id}"
575
+ # externals?
576
+ if self._is_root and recurse:
577
+ data.update({
578
+ "defs": self._defs.toJSON(recurse), # False?
579
+ "rename": self._name,
580
+ "rewrite": self._rewrite,
581
+ })
582
+ if "defs" not in data:
583
+ data["defs"] = f"Symbols {self._defs._id}"
584
+ return data
585
+
586
+ # FIXME this is **not** very clean YET, should be a valid model?!
587
+ def toModel(self, deep: bool = False) -> Jsonable:
588
+ """Return JSON Model (more or less) for display."""
589
+ model = copy.deepcopy(self._model)
590
+ if isinstance(model, dict):
591
+ if "#" in model:
592
+ del model["#"]
593
+ li = "JSON_MODEL_LOOSE_INT" if self._loose_int else ""
594
+ lf = "JSON_MODEL_LOOSE_FLOAT" if self._loose_float else ""
595
+ loose = f" ({li} {lf})" if self._loose_float and self._loose_int else f" ({li}{lf})"
596
+ model["#"] = \
597
+ f"JsonModel {self._id}{loose if self._loose_float or self._loose_int else ''}"
598
+ if len(self._defs):
599
+ defs = {
600
+ n: jm.toModel() if isinstance(jm, JsonModel) else jm
601
+ for n, jm in self._defs.items()
602
+ } if deep else self._init_dl
603
+ if defs:
604
+ if "" not in defs:
605
+ defs["#"] = f"Symbol {self._defs._id}"
606
+ defs[""] = self._url
607
+ if isinstance(model, dict):
608
+ assert "$" not in model
609
+ model["$"] = defs
610
+ else:
611
+ model = {
612
+ "#": f"JsonModel {self._id} with defs",
613
+ "$": defs if deep else f"Symbol {self._defs._id}",
614
+ "@": model,
615
+ }
616
+ if self._spec and isinstance(model, dict):
617
+ model["~"] = self._spec._url
618
+ return model
619
+
620
+ def toSchema(self, recurse: bool = True, path: ModelPath|None = None) -> JsonSchema:
621
+ from . import convert
622
+ schema: JsonSchema
623
+ model = copy.deepcopy(self._model)
624
+ changed = False
625
+ if path is None:
626
+ path = []
627
+
628
+ # try to replace some key references
629
+ def keyFlt(model: ModelType, path: ModelPath) -> bool:
630
+ nonlocal changed
631
+ if isinstance(model, dict):
632
+ for key in list(model.keys()):
633
+ lpath = path + [key]
634
+ if self._isRef(key):
635
+ jm = self.resolveRef(key, lpath)
636
+ if isinstance(jm._model, str):
637
+ m = jm._model
638
+ else:
639
+ log.info(f"tring re for prop ref {key} at {lpath}")
640
+ pattern = convert.propRefRegex(jm, jm._model, lpath) # type: ignore
641
+ if pattern is not None:
642
+ if pattern == "": # special case
643
+ m = pattern
644
+ else:
645
+ m = r"/" + pattern + r"/"
646
+ else:
647
+ log.warning(f"cannot replace {key} at {lpath}, rough approximation")
648
+ # this may lead to an invalid schema
649
+ m = "/^.*$/s"
650
+ else:
651
+ m = key
652
+ if m == "":
653
+ pass
654
+ elif m in PREDEF_RE:
655
+ m = r"/^" + PREDEF_RE[m] + "$/"
656
+ elif m[0] == "_":
657
+ m = "!" + m[1:]
658
+ elif m[0] not in ("/", "$", "="):
659
+ m = "?" + m
660
+ if m != key and (m == "" or m[0] == "/"):
661
+ changed = True
662
+ log.info(f"replacing {key} with {m} at {lpath}")
663
+ assert m not in model, f"cannot overwrite key {m} at {lpath}"
664
+ model[m] = model[key]
665
+ del model[key]
666
+ return isinstance(model, (list, dict))
667
+
668
+ model = recModel(model, keyFlt, noRwt)
669
+
670
+ if changed:
671
+ log.debug(f"filtered model={model}")
672
+
673
+ # convert root model
674
+ schema = convert.model2schema(model, path, self._defs) # type: ignore
675
+
676
+ # root specific, only when there are defs though
677
+ if recurse and self._defs:
678
+ # ensure that schema is an object
679
+ if isinstance(schema, bool): # we need an object to store defs
680
+ schema = {} if schema else {"not": True}
681
+ # possibly salvage root comment
682
+ if isinstance(self._model, dict) and "#" in self._model:
683
+ schema["description"] = self._model["#"]
684
+ # build root object, in order
685
+ root: JsonObject = {}
686
+ root["$comment"] = "JSON Schema generated by JSON Model Compiler"
687
+ root["$schema"] = "https://json-schema.org/draft/2020-12/schema"
688
+ # Hmmm… not really?!
689
+ # if self._url:
690
+ # root["$id"] = self._url
691
+ if "description" in schema: # move description ahead
692
+ root["description"] = schema["description"]
693
+ del schema["description"]
694
+ root["$defs"] = { # type: ignore
695
+ name: jm.toSchema(False, ["$", name])
696
+ for name, jm in self._defs.items()
697
+ }
698
+ root.update(schema)
699
+ schema = root
700
+
701
+ return schema # type: ignore
702
+
703
+ #
704
+ # Resolution
705
+ #
706
+ # @staticmethod?
707
+ def _isPredef(self, s: Jsonable) -> bool:
708
+ return isinstance(s, str) and s != "" and s[0] == "$" and s[1:] in JsonModel.PREDEFS
709
+
710
+ # @staticmethod?
711
+ def _isRef(self, model: Jsonable) -> bool:
712
+ return isinstance(model, str) and (
713
+ model != "" and model[0] == "$" and not self._isPredef(model))
714
+
715
+ # @staticmethod?
716
+ def _isUrlRef(self, model: Jsonable) -> bool:
717
+ return isinstance(model, str) and re.match(r"\$(file://|https?://|\.|/)", model) is not None
718
+
719
+ # @staticmethod?
720
+ def _isSimpleRef(self, model: Jsonable) -> bool:
721
+ return self._isRef(model) and not self._isUrlRef(model)
722
+
723
+ def isRef(self) -> bool:
724
+ return self._isRef(self._model)
725
+
726
+ def isUrlRef(self) -> bool:
727
+ return self._isUrlRef(self._model)
728
+
729
+ def resolveDef(self, ref: str, path: ModelPath, create: bool = False) -> JsonModel:
730
+ """Resolve a definition in the current Model context.
731
+
732
+ format: /\\$($URL#)*name/
733
+ """
734
+
735
+ if self._debug >= 3:
736
+ log.debug(f"{self._id}: RD {ref} at {path} (defs: {list(self._defs.keys())})")
737
+
738
+ assert ref and ref[0] == "$" and len(ref) > 1
739
+ name = ref[1:]
740
+
741
+ # extract first name, will have to recurse
742
+ if "#" in name:
743
+ name, others = name.split("#", 1)
744
+ while name == "" and "#" in others: # self!
745
+ name, others = others.split("#", 1)
746
+ if name == "" and others == "":
747
+ return self
748
+ else:
749
+ others = None
750
+
751
+ # name resolution
752
+ if name in self._defs:
753
+ log.debug(f"{self._id}: ref={ref} model={self._model} namedef={self._defs[name]._id}")
754
+ jm = self._defs[name]
755
+ if isinstance(jm._model, str) and jm.isRef():
756
+ log.debug(f"{self._id}: following {ref} in {jm._model}")
757
+ model = jm._model
758
+ if others:
759
+ model += "#" + others
760
+ return jm.resolveRef(model, path + [name, jm._model], create)
761
+ else:
762
+ return jm.resolveRef("$" + others, path + [name], create) if others else jm
763
+ else:
764
+ if not create:
765
+ if self._debug:
766
+ log.debug(f"{self._id}: ref={ref} model={self._model} defs={list(self._defs.keys())}")
767
+ raise ModelError(f"{self._id}: cannot find definition for \"{name}\" ({path})")
768
+ # creation only allowed while rewriting, as new defs may be added _after_ a reference
769
+ log.info(f"{self._id}: creating empty definition \"{name}\"")
770
+ self._defs[name] = JsonModel(None, self._resolver, url=self._url + "#" + name,
771
+ head=self._head, scope=self._defs, debug=self._debug,
772
+ loose_int=self._loose_int, loose_float=self._loose_float)
773
+ return self._defs[name]
774
+
775
+ def resolveRef(self, model: Jsonable, path: ModelPath, create: bool = False) -> JsonModel:
776
+ """Resolve references up to an actual model, maybe."""
777
+ jm, initial, followed = self, model, []
778
+
779
+ if self._debug >= 2:
780
+ log.debug(f"{self._id}: RR {model} at {path}")
781
+
782
+ # no jm for predefs
783
+ assert not self._isPredef(model), f"no resolution for {model}"
784
+
785
+ # shortcut with global scoping
786
+ if isinstance(model, str) and self._isRef(model) and self._defs.ghas(model):
787
+ if self._debug >= 3:
788
+ log.debug(f"{self._id}: gmap shortcut {self._defs._gmap}")
789
+ log.debug(f"{self._id}: globs = {self._globs}")
790
+ return self._globs[self._defs.gget(model)]
791
+
792
+ # NOTE after a merge, some references may be global
793
+ if isinstance(model, str) and self._isRef(model) and model in self._globs:
794
+ if self._debug >= 3:
795
+ log.debug(f"{self._id}: direct globs shortcut for {model}")
796
+ return self._globs[model]
797
+
798
+ # actual resolution
799
+ while jm._isRef(model):
800
+ jm_id = jm._id # entry id
801
+ assert isinstance(model, str) # pyright hint
802
+ if self._debug >= 3:
803
+ log.debug(f"{self._id}: [{jm._id}] RR ref loop on {model}")
804
+ if jm._isUrlRef(model):
805
+ # detect recursion
806
+ if model in followed:
807
+ raise ModelError(f"cycle while resolving ref at {path}: {initial} ({followed})")
808
+ # change scope
809
+ followed.append(model)
810
+ if "#" in model:
811
+ url, model = model[1:].split("#", 1)
812
+ model = "$" + model
813
+ else:
814
+ url, model = model[1:], None # will stop resolution loop
815
+ jm = jm.load(url, path)
816
+ else: # reference to a definition
817
+ if self._debug >= 3:
818
+ log.debug(f"{self._id}: [{jm._id}] RR to RD for {model} at {path}")
819
+ jm = jm.resolveDef(model, path, create)
820
+ # if self._debug >= 3:
821
+ # log.debug(f"{self._id}: [{jm._id}] after RD")
822
+
823
+ # special case for "$#" which leads to a direct recursion
824
+ if jm._id == jm_id and model == jm._model:
825
+ if model == "$#":
826
+ break
827
+ else:
828
+ raise ModelError(f"{self._id}: (jm={jm._id}) resolution cycle on {model}")
829
+ model = jm._model
830
+
831
+ if self._debug >= 3:
832
+ log.debug(f"{self._id}: RR next {model} in {jm._id}")
833
+
834
+ if self._debug >= 2:
835
+ log.debug(f"{self._id}: RR resolved {initial} to {jm._id}")
836
+
837
+ return jm
838
+
839
+ #
840
+ # Build global symbol table
841
+ # Build mapping of local references to global references
842
+ #
843
+ def scope(self, symbols: Symbols, root: ModelRef,
844
+ visited: set[tuple[str, int]], references: dict[int, str]):
845
+ """Move all local references to the root scope."""
846
+ if self._debug >= 2:
847
+ log.debug(f"{self._id}: scoping {root} ({visited} / {references})")
848
+ if self._debug >= 3:
849
+ log.debug(f"{self._id}: scope in symbols: {symbols}")
850
+
851
+ # prevent infinite recursion
852
+ mid = ("m", self._id)
853
+ if mid in visited:
854
+ return
855
+ visited.add(mid)
856
+
857
+ root_ref = "$" + "#".join(root)
858
+
859
+ if root_ref not in symbols:
860
+ symbols[root_ref] = self
861
+
862
+ if root_ref == "$": # also add "$#" for the root model
863
+ if "$#" not in symbols:
864
+ symbols["$#"] = self
865
+
866
+ if self._id not in references:
867
+ references[self._id] = root_ref
868
+
869
+ # override URLs with their target?!
870
+ if self.isUrlRef():
871
+ jm = self.resolveRef(self._model, [])
872
+ symbols[root_ref] = jm
873
+ jm.scope(symbols, root, visited, references)
874
+
875
+ # handle models's symbol table if not done yet
876
+ sid = ("s", self._defs._id)
877
+ if sid not in visited:
878
+ visited.add(sid)
879
+ # two phase ensure that maps are okay for resolveRef
880
+ # names = list(self._defs.keys())
881
+ for name, jm in self._defs.items():
882
+ if jm._id not in references:
883
+ gref = "$" + "#".join(root + [name])
884
+ references[jm._id] = gref
885
+ self._defs.gset("$" + name, gref)
886
+ # FIXME should also but "$#" + name?
887
+ # NOTE for $#, we put the root jm directly
888
+ # FIXME this kludge avoids bad recursions later…
889
+ if isinstance(jm._model, str) and jm._model == "$#":
890
+ symbols[gref] = self
891
+ else:
892
+ symbols[gref] = jm
893
+ if self._debug >= 3:
894
+ log.debug(f"{self._id}: gmap={self._defs._gmap}")
895
+ for name, jm in self._defs.items():
896
+ jm.scope(symbols, root + [name], visited, references)
897
+
898
+ # update map of local references to global references
899
+ def globRwt(m: ModelType, p: ModelPath) -> ModelType:
900
+ if isinstance(m, str):
901
+ if self._isSimpleRef(m):
902
+ jm = self.resolveRef(m, p + [m])
903
+ if jm._id in references:
904
+ gref = references[jm._id]
905
+ else:
906
+ # assert False # FIXME ?!
907
+ gref = root_ref + "#" + m[1:]
908
+ if gref not in symbols:
909
+ symbols[gref] = jm
910
+ jm.scope(symbols, root + [m[1:]], visited, references)
911
+ references[jm._id] = gref
912
+ # log.debug(f"{self._id}: glob rwt m={m} jm={jm._id} gref={gref}")
913
+ if not self._defs.ghas(m):
914
+ # log.debug(f"{self._id}: glob rwt gmap {m} -> {gref} for {self._defs._id}")
915
+ self._defs.gset(m, gref)
916
+ # if not jm._defs.ghas(gref): # also accept global references?
917
+ # jm._defs.gset(gref, gref)
918
+ elif self._isUrlRef(m):
919
+ if m not in symbols:
920
+ symbols[m] = self.resolveRef(m, p + [m])
921
+ if not self._defs.ghas(m):
922
+ self._defs.gset(m, m)
923
+ return m
924
+
925
+ self._model = recModel(self._model, allFlt, globRwt, True)
926
+
927
+ #
928
+ # Rename and Rewrite Transformations
929
+ #
930
+ def rename(self, model: ModelType, path: ModelPath = [], root: bool = False) -> ModelType:
931
+ """Apply keyword renaming."""
932
+
933
+ # FIXME should check that all are ".…" are replaced?!
934
+ if root and not self._name:
935
+ return model
936
+
937
+ def rnFlt(m: ModelType, path: ModelPath) -> bool:
938
+ if isinstance(m, dict):
939
+ remove, added = set(), {}
940
+ for k, v in m.items():
941
+ assert isinstance(k, str)
942
+ if k in self._name:
943
+ added[self._name[k]] = v
944
+ remove.add(k)
945
+ for k in remove:
946
+ del m[k]
947
+ for k in added.keys():
948
+ if k in m:
949
+ raise ModelError(f"rename cannot overwrite existing {k}")
950
+ m.update(**added)
951
+ return True
952
+
953
+ return recModel(model, rnFlt, noRwt)
954
+
955
+ # FIXME parsing should conform to JSON Path
956
+ # TODO think transformation path spec
957
+ def _parsePath(self, tpath: str, path: ModelPath) -> tuple[JsonModel, ModelPath]:
958
+ """Parse "$Foo.foo.0.bla" reference and simple json path."""
959
+ if self._debug:
960
+ log.debug(f"{self._id}: parsePath at {path}: {tpath}")
961
+ assert tpath and tpath[0] == "$", f"tpath must be a reference: {tpath}"
962
+ if "." in tpath:
963
+ name, jpath = tpath.split(".", 1)
964
+ if jpath == "":
965
+ raise ModelError(f"bad transformation path at {path}: {tpath}")
966
+ xpath = [int(i) if re.match(r"\d+$", i) else i for i in jpath.split(".")]
967
+ else:
968
+ name, xpath = tpath, []
969
+ log.debug(f"{self._id}: parsePath name={name} xpath={xpath}")
970
+ return (self.resolveRef(name, path, True), xpath)
971
+
972
+ def _isTrafo(self, trafo: ModelTrafo):
973
+ return isinstance(trafo, dict) and set(trafo.keys()).issubset({"#", "/", "*"})
974
+
975
+ def _applyTrafo(self, j: Jsonable, trafo: ModelTrafo, path: ModelPath):
976
+ """Apply this transformation on j."""
977
+
978
+ if not isinstance(trafo, dict) or "/" not in trafo and "*" not in trafo:
979
+ return trafo
980
+ assert self._isTrafo(trafo)
981
+ assert isinstance(trafo, dict) # pyright hint
982
+ if self._debug:
983
+ log.debug(f"{self._id}: applyTrafo trafo={trafo} on j={j} [{path}]")
984
+
985
+ if "/" in trafo:
986
+ sub = trafo["/"]
987
+ # handle scalars
988
+ if sub is None or isinstance(sub, (bool, int, float, str)):
989
+ sub = [sub]
990
+ if isinstance(sub, list):
991
+ if isinstance(j, list):
992
+ for i in sub:
993
+ if i not in j:
994
+ raise ModelError(f"cannot remove item {i} from object at {path}")
995
+ j.remove(i)
996
+ elif isinstance(j, dict):
997
+ for i in sub:
998
+ if i not in j:
999
+ raise ModelError(f"cannot remove item {i} from object at {path}")
1000
+ del j[i]
1001
+ else:
1002
+ raise ModelError(f"cannot remove list from {tname(j)}")
1003
+ else:
1004
+ raise ModelError("expecting a remove list")
1005
+
1006
+ if "*" in trafo:
1007
+ add = trafo["*"]
1008
+ if isinstance(add, list):
1009
+ if isinstance(j, list):
1010
+ j.extend(add)
1011
+ else:
1012
+ raise ModelError(f"cannot add list to {tname(j)} at {path}")
1013
+ elif isinstance(add, dict):
1014
+ if isinstance(j, dict):
1015
+ for k, v in add.items():
1016
+ if k in j:
1017
+ # raise ModelError(f"cannot overwrite property {k} at {path}, remove first")
1018
+ log.warning(f"overwriting property {k} at {path}")
1019
+ j[k] = v
1020
+ else:
1021
+ raise ModelError(f"cannot add object to {tname(j)} at {path}")
1022
+ else:
1023
+ raise ModelError(f"unexpected add type at {path}")
1024
+
1025
+ return j
1026
+
1027
+ def _applyTrafoAtPath(self, jm: JsonModel, tpath: ModelPath,
1028
+ trafo: ModelTrafo, path: ModelPath):
1029
+ """Apply a transformation into a JSON Model."""
1030
+
1031
+ if self._debug:
1032
+ log.debug(f"{jm._id}: trafo at {path}: {tpath}")
1033
+
1034
+ j = jm._model
1035
+
1036
+ # if tpath == ["$"]:
1037
+ # log.warning("TODO add/remove definitions ?!")
1038
+ # if "/" in trafo:
1039
+ # assert isinstance(trafo["/"], list)
1040
+ # for name in trafo["/"]:
1041
+ # assert isinstance(name, str)
1042
+ # if name in jm._defs:
1043
+ # del jm._defs[name]
1044
+ # else:
1045
+ # log.warning(f"cannot remove definition for {name}")
1046
+ # assert "*" not in trafo, f"not implemented yet"
1047
+ # return
1048
+
1049
+ # follow the JSON path
1050
+ for i, p in enumerate(tpath):
1051
+ assert isinstance(j, (list, dict))
1052
+ last = i == len(tpath) - 1
1053
+ if isinstance(p, str):
1054
+ if not isinstance(j, dict):
1055
+ raise ModelError(f"invalid transformation path at {path}: {tpath}")
1056
+ if p not in j:
1057
+ raise ModelError(f"cannot find at {path}: {p} in {tpath}")
1058
+ else:
1059
+ assert isinstance(p, int)
1060
+ if not isinstance(j, list):
1061
+ raise ModelError(f"invalid transformation path at {path}: {tpath}")
1062
+ if not 0 <= p < len(j):
1063
+ raise ModelError(f"invalid index at {path}: {p} in {tpath}")
1064
+ if last: # apply!
1065
+ log.debug(f"{jm._id}: applying on p={p} in j={j} trafo={trafo}")
1066
+ j[p] = self._applyTrafo(j[p], trafo, path) # type: ignore
1067
+ if self._debug >= 3:
1068
+ log.debug(f"{self._id}: after trafo j[p] = {j[p]}") # pyright: ignore
1069
+ else: # move forward
1070
+ log.debug(f"{jm._id}: moving forward on p={p}")
1071
+ j = j[p] # type: ignore
1072
+ if not tpath:
1073
+ log.debug(f"{jm._id}: empty tpath on {jm._model}")
1074
+ jm._model = self._applyTrafo(jm._model, trafo, path)
1075
+
1076
+ def rewrite(self):
1077
+ """Apply model rewriting to current JSON Model."""
1078
+
1079
+ # NOTE transformation specs may be empty
1080
+ for tpath, trafo in self._rewrite.items():
1081
+ lpath = ["$", "%", tpath] # FIXME
1082
+ # typing issue, cannot assign list[str] to list[str|int] !?
1083
+ jm, path = self._parsePath(tpath, lpath) # type: ignore
1084
+ self._applyTrafoAtPath(jm, path, trafo, lpath) # type: ignore