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/utils.py ADDED
@@ -0,0 +1,623 @@
1
+ #
2
+ # Common model utilities
3
+ #
4
+ import sys
5
+ import re
6
+ from importlib.metadata import version as pkg_version
7
+ import logging
8
+ from .mtypes import ModelType, ModelPath, ModelError, ModelObject
9
+ from .mtypes import Jsonable, JsonObject, ValueType, Symbols
10
+
11
+ __version__ = pkg_version("json_model_compiler")
12
+
13
+ log = logging.getLogger("json-model")
14
+ # log.setLevel(logging.DEBUG)
15
+
16
+ MODEL_PREDEFS = {
17
+ "$ANY", "$NONE", "$NULL", "$BOOL", "$BOOLEAN",
18
+ "$INT", "$INTEGER", "$I32", "$I64", "$U32", "$U64",
19
+ "$FLOAT", "$F32", "$F64", "$NUMBER",
20
+ "$STRING", "$DATE", "$TIME", "$DATETIME",
21
+ "$URL", "$REGEX", "$EXREG", "$UUID",
22
+ "$URI", "$EMAIL",
23
+ # TODO $URI-REF, $DOMAIN…
24
+ }
25
+
26
+ ANY_STR_RE = r"(?s).*"
27
+ WEAK_DATE_RE = r"\d{4}-(0?[1-9]|1[012])-(0?[1-9]|[12]\d|3[01])"
28
+ WEAK_TIME_RE = r"([01]?[0-9]|2[0-4]):[0-5]?[0-9]:[0-5]?[0-9](\.\d+)?"
29
+ TZ_RE = r"(Z|[-+]\d+)?"
30
+ UUID_RE = r"(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
31
+ CONST_RE = r"^=(null|true|false|-?\d+(\.\d+)?([eE]-?\d+)?)$"
32
+ JSKW_RE = r"^([#~$%@|&+^/*=]|[<>!]=?)$"
33
+ URL_RE = r"((https?|file)://.*|\..*)"
34
+ EMAIL_RE = r"[-_a-zA-Z0-9.]+@[-_a-zA-Z0-9.]+"
35
+
36
+ # (approximate) regular expressions for some predefs
37
+ PREDEF_RE = {
38
+ "$STRING": ANY_STR_RE,
39
+ "$DATE": WEAK_DATE_RE,
40
+ "$TIME": WEAK_TIME_RE,
41
+ "$DATETIME": WEAK_DATE_RE + "[ T]" + WEAK_TIME_RE + TZ_RE,
42
+ "$UUID": UUID_RE,
43
+ "$REGEX": ANY_STR_RE,
44
+ "$EXREG": ANY_STR_RE,
45
+ "$URL": URL_RE,
46
+ "$URI": URL_RE,
47
+ "$EMAIL": EMAIL_RE,
48
+ }
49
+
50
+ def tname(m) -> str:
51
+ return type(m).__name__ if m is not None else "null"
52
+
53
+ def is_regex(s: ValueType, p: str = "") -> bool:
54
+ if isinstance(s, str):
55
+ try:
56
+ re.compile(s)
57
+ return True
58
+ except Exception as e:
59
+ # probably only "simple" re should be accepted, see JSON Schema approach
60
+ # \c ControlLetter (ECMA 262 v13 - 22.2.1 p. 552)
61
+ # \p{UnicodePropertyValueExpression} (same p. 553)
62
+ good_anyway = re.search(r"\\[Pp]\{", s) or re.search(r"\\c[a-zA-Z]", s)
63
+ if not good_anyway:
64
+ log.warning(f"invalid /{s}/ at {p}: {e}")
65
+ return good_anyway is not None
66
+ else:
67
+ return False
68
+
69
+ def is_cst(s: Jsonable) -> bool:
70
+ return s is None or isinstance(s, str) and s != "" and s[0] not in ("$", "/")
71
+
72
+ def cst(s: str|None) -> None|bool|int|float|str: # JsonScalar
73
+ if s is None:
74
+ return None
75
+ elif s[0] == "_":
76
+ return s[1:]
77
+ elif s[0] == "=":
78
+ if s == "=null":
79
+ return None
80
+ elif s == "=true":
81
+ return True
82
+ elif s == "=false":
83
+ return False
84
+ elif "." in s or "e" in s or "E" in s:
85
+ return float(s[1:])
86
+ else:
87
+ return int(s[1:])
88
+ else:
89
+ return s
90
+
91
+ def distinct_values(val: Jsonable) -> bool:
92
+ # stupid implementation because True == 1
93
+ if isinstance(val, (list, tuple, str)):
94
+ seen = []
95
+ for i in val:
96
+ if any(map(lambda v: type(v) is type(i) and v == i, seen)):
97
+ return False
98
+ seen.append(i)
99
+ return True
100
+
101
+ def one(lb) -> bool:
102
+ """Tell if only one from an iterable is True."""
103
+ seen = False
104
+ for b in lb:
105
+ if b:
106
+ if seen:
107
+ return False # second
108
+ seen = True # first
109
+ return seen
110
+
111
+ def model_eq(m1: ModelType, m2: ModelType) -> bool:
112
+ """Recursively compare two models…"""
113
+ # TODO resolve @ and $
114
+ t1, t2 = type(m1), type(m2)
115
+ if t1 is not t2:
116
+ return False
117
+ elif t1 is type(None):
118
+ return True
119
+ elif t1 in (bool, int, float, str):
120
+ return m1 == m2
121
+ elif t1 is list:
122
+ assert isinstance(m1, list) and isinstance(m2, list) # type hint
123
+ if len(m1) != len(m2):
124
+ return False
125
+ else: # same size, recurse
126
+ return all(model_eq(i1, i2) for i1, i2 in zip(m1, m2))
127
+ elif t1 is dict: # compare contents but # $ %
128
+ # check m1 ⊂ m2
129
+ assert isinstance(m1, dict) and isinstance(m2, dict) # type hint helper
130
+ for p in m1.keys():
131
+ if p not in ("#", "%", "$"):
132
+ if p not in m2:
133
+ return False
134
+ if not model_eq(m1[p], m2[p]):
135
+ return False
136
+ # check m2 ⊂ m1
137
+ for p in m2.keys():
138
+ if p not in ("#", "%", "$") and p not in m1:
139
+ return False
140
+ # m1 == m2
141
+ return True
142
+ else:
143
+ raise ModelError(f"unexpected model element type ({t1.__name__})")
144
+
145
+ # TODO maybe we should accept some simple type inclusions
146
+ def same_model(m1: ModelType, m2: ModelType) -> bool:
147
+ """Compare models…"""
148
+ # beware that True == 1 and False == 0
149
+ # return type(m1) == type(m2) and m1 == m2
150
+ return model_eq(m1, m2)
151
+
152
+ def model_in_models(m: ModelType, lm: list[ModelType]) -> bool:
153
+ for i in lm:
154
+ if model_eq(i, m):
155
+ return True
156
+ return False
157
+
158
+ def split_object(model: JsonObject, path: ModelPath) -> \
159
+ tuple[JsonObject, JsonObject, JsonObject, JsonObject, JsonObject]:
160
+ """Split properties in must/may/refs/regs/other cases."""
161
+
162
+ if not isinstance(model, dict):
163
+ raise ModelError(f"unexpected + model: {model} {path}")
164
+
165
+ if "@" in model or "|" in model or "^" in model or "+" in model or "&" in model:
166
+ raise ModelError(f"unexpected + model: {model} {path}")
167
+
168
+ # FIXME should it be lists to keep the initial order?
169
+ must, may, refs, regs, others = {}, {}, {}, {}, {"": model[""]} if "" in model else {}
170
+
171
+ # put each property in the expected set
172
+ for key, val in model.items():
173
+
174
+ if not isinstance(key, str):
175
+ raise ModelError(f"object proprety name must be a str: {tname(key)} {path + [key]}")
176
+
177
+ # some (late) sanity check
178
+ if key in ("$", "%", "#", ""):
179
+ if key == "%" and not isinstance(val, dict):
180
+ raise ModelError(f"{key} value must be an object: {tname(key)} {path + [key]}")
181
+ if key == "#" and not isinstance(val, (str, dict)):
182
+ raise ModelError(
183
+ f"{key} value must be string or object: {tname(key)} {path + [key]}"
184
+ )
185
+ if key == "$" and not isinstance(val, str):
186
+ raise ModelError(f"{key} value must be string: {tname(key)} {path + [key]}")
187
+ # ignore anyway
188
+ continue
189
+
190
+ c, name = key[0], key[1:]
191
+
192
+ if c in ("_", "!", "?") and (name in must or name in may):
193
+ raise ModelError(f"multiply defined property: {name} {path + [key]}")
194
+
195
+ if c == "_" or c == "!":
196
+ must[name] = val
197
+ elif c == "?":
198
+ may[name] = val
199
+ elif c == "$":
200
+ refs[name] = val
201
+ elif c == "/":
202
+ # FIXME /i support on keys
203
+ assert key.endswith("/"), f"bad key: {key}"
204
+ regs[name[:-1]] = val
205
+ else:
206
+ if key in must or key in may:
207
+ raise ModelError(f"multiply defined property: {name} {path + [key]}")
208
+ must[key] = val
209
+
210
+ return must, may, refs, regs, others
211
+
212
+ def _bang(s):
213
+ return s if re.match(r"[A-Za-z0-9]", s) else f"!{s}"
214
+
215
+ def unsplit_object(must: JsonObject, may: JsonObject, refs: JsonObject,
216
+ regs: JsonObject, others: JsonObject) -> JsonObject:
217
+ """Regenerate an object from separated properties."""
218
+ return {
219
+ **{_bang(k): v for k, v in must.items()},
220
+ **{f"?{k}": v for k, v in may.items()},
221
+ **{f"${k}": v for k, v in refs.items()},
222
+ # FIXME /i support?
223
+ **{f"/{k}/": v for k, v in regs.items()},
224
+ **others
225
+ }
226
+
227
+ def is_constructed(model: ModelType):
228
+ """Tell whether model is constructed, i.e. uses some combinator or indirection.
229
+
230
+ NOTE references are assumed to be resolved beforehand.
231
+ """
232
+ return isinstance(model, dict) and \
233
+ ("|" in model or "&" in model or "^" in model or "+" in model or "@" in model)
234
+
235
+ def constant_value(m: ModelType, mpath: ModelPath) -> tuple[bool, ValueType]:
236
+ if m is None:
237
+ return True, None
238
+ elif isinstance(m, str):
239
+ char = m[0] if m else ""
240
+ if char == "=":
241
+ val = m[1:]
242
+ if val == "null":
243
+ return True, None
244
+ elif val == "true":
245
+ return True, True
246
+ elif val == "false":
247
+ return True, False
248
+ elif re.search(r"^-?[0-9]+$", val):
249
+ return True, int(val)
250
+ else: # float?
251
+ try:
252
+ return True, float(val)
253
+ except Exception:
254
+ raise ModelError(f"unexpected float value {val} [{mpath}]")
255
+ elif char == "_":
256
+ return True, m[1:]
257
+ elif char == "/":
258
+ return False, None
259
+ elif char == "$":
260
+ return False, None
261
+ elif len(m) > 0:
262
+ return True, m
263
+ else:
264
+ return False, None
265
+ else:
266
+ return False, None
267
+
268
+ def all_model_type(models: list[ModelType], mpath: ModelPath) -> tuple[bool, type|None]:
269
+ first, current_type = True, None
270
+ for i, m in enumerate(models):
271
+ is_known, has_type = model_type(m, mpath + [i])
272
+ if is_known:
273
+ if first:
274
+ current_type = has_type
275
+ first = False
276
+ elif current_type != has_type:
277
+ return False, None
278
+ else:
279
+ return False, None
280
+ if first:
281
+ # empty list
282
+ return False, None
283
+ else:
284
+ return True, current_type
285
+
286
+ def model_type(model: ModelType, mpath: ModelPath) -> tuple[bool, type|None]:
287
+ """Tell the type of the model, if known."""
288
+ match model:
289
+ case None:
290
+ return True, None
291
+ case bool():
292
+ return True, bool
293
+ case int():
294
+ return True, int
295
+ case float():
296
+ return True, float
297
+ case str():
298
+ if model in ("", "$STRING"):
299
+ return True, str
300
+ elif model[0] in ("_", "/"):
301
+ return True, str
302
+ elif model == "$BOOL":
303
+ return True, bool
304
+ elif model == "$NULL":
305
+ return True, None
306
+ elif model in ("$INTEGER", "$I32", "$U32", "$I64", "$U64"):
307
+ return True, int
308
+ elif model in ("$FLOAT", "$F32", "$F64"):
309
+ return True, float
310
+ elif model[0] == "$":
311
+ # how to access definitions?
312
+ return False, None
313
+ elif model[0] == "=":
314
+ # handle constants
315
+ a_cst, val = constant_value(model, mpath)
316
+ if a_cst:
317
+ return True, type(val)
318
+ else:
319
+ return False, None
320
+ else:
321
+ return True, str
322
+ case list():
323
+ return True, list
324
+ case dict():
325
+ if "@" in model:
326
+ return model_type(model["@"], mpath + ["@"])
327
+ elif "|" in model:
328
+ models = model["|"]
329
+ assert isinstance(models, list)
330
+ return all_model_type(models, mpath + ["|"])
331
+ elif "&" in model:
332
+ models = model["&"]
333
+ assert isinstance(models, list)
334
+ return all_model_type(models, mpath + ["&"])
335
+ elif "^" in model:
336
+ models = model["^"]
337
+ assert isinstance(models, list)
338
+ return all_model_type(models, mpath + ["^"])
339
+ elif "+" in model:
340
+ return True, dict
341
+ else: # simple object!
342
+ return True, dict
343
+ case _:
344
+ raise ModelError(f"unexpected model: {model} ({tname(model)})")
345
+
346
+ def resolve_model(m: ModelType, defs: Symbols) -> ModelType:
347
+ """Follow definitions and @ to find the underlying type, if possible."""
348
+ changed, resolved = True, set()
349
+ while changed:
350
+ # FIXME possible infinite recursion?
351
+ changed = False
352
+ if isinstance(m, str) and m != "" and m[0] == "$":
353
+ name = m[1:]
354
+ if name not in resolved and name in defs:
355
+ m, changed = defs[name]._model, True # pyright: ignore
356
+ resolved.add(name)
357
+ if isinstance(m, dict) and "@" in m:
358
+ m, changed = m["@"], True
359
+ return m
360
+
361
+ def openfiles(args: list[str] = []):
362
+ if not args: # empty list is same as stdin
363
+ args = ["-"]
364
+ for fn in args:
365
+ if fn == "-":
366
+ yield fn, sys.stdin
367
+ else:
368
+ with open(fn) as fh:
369
+ yield fn, fh
370
+
371
+ def _dedup_models(models: list[ModelType]) -> list[ModelType]:
372
+ dedups = []
373
+ for m in models:
374
+ if not model_in_models(m, dedups):
375
+ dedups.append(m)
376
+ return dedups
377
+
378
+ # FIXME consistency with _structurally_distinct_models…
379
+ def _distinct_models(m1: ModelType, m2: ModelType, defs: Symbols, mpath: ModelPath) -> bool:
380
+ """Whether m1 and m2 are provably distinct, i.e. do not have values in common."""
381
+ m1, m2 = resolve_model(m1, defs), resolve_model(m2, defs)
382
+ # log.warning(f"m1={m1} m2={m2}")
383
+ # type
384
+ if isinstance(m1, str) and m1 and m1[0] == "$": # unresolved reference
385
+ return m1 == "$NONE" # special case for none which interact with nothing
386
+ if isinstance(m2, str) and m2 and m2[0] == "$": # unresolved reference
387
+ return m2 == "$NONE"
388
+ if is_constructed(m1) or is_constructed(m2):
389
+ return False
390
+ if type(m1) is not type(m2):
391
+ # log.warning("distinct!")
392
+ return True
393
+ # else same type… try value
394
+ c1, v1 = constant_value(m1, mpath)
395
+ c2, v2 = constant_value(m2, mpath)
396
+ # log.warning(f"{c1} {v1} / {c2} {v2}")
397
+ if c1 and c2 and (type(v1) is not type(v2) or v1 != v2):
398
+ return True
399
+ return False
400
+
401
+
402
+ class _Object:
403
+ """Internal representation of an object model."""
404
+
405
+ def __init__(self, model: ModelType, gdefs: Symbols, mpath: ModelPath):
406
+ assert isinstance(model, dict)
407
+ must, may, defs, regs, oth = split_object(model, mpath)
408
+ self._must = must
409
+ self._may = may
410
+ self._defs = defs
411
+ self._regs = regs
412
+ self._oth = oth
413
+ self._global_defs = gdefs
414
+ self._mpath = mpath
415
+
416
+ def __contains__(self, o):
417
+ """Whether o may be included in self (safe).
418
+
419
+ That is all mandatory properties of o may be accepted by self.
420
+ We could do a better job by checking model target incompatibility.
421
+ """
422
+ if not isinstance(o, _Object):
423
+ raise ModelError("Only objects can be compared")
424
+ if self._defs:
425
+ # FIXME improve?
426
+ log.debug("$-reference keys are not handled")
427
+ return True
428
+ # we look for mandatory one property in o which allows to discriminate
429
+ for p, m in o._must.items():
430
+ if p in self._must:
431
+ if _distinct_models(m, self._must[p], self._global_defs, self._mpath):
432
+ return False
433
+ # o.p does not discriminate with self
434
+ continue
435
+ elif p in self._may:
436
+ if _distinct_models(m, self._may[p], self._global_defs, self._mpath):
437
+ return False
438
+ continue
439
+ for reg, model in self._regs.items():
440
+ if re.search(reg, p):
441
+ # TODO catch more $NONE cases?
442
+ if model == "$NONE":
443
+ return False
444
+ # else try model resolution… this may depend on the execution order?
445
+ resolved = resolve_model(model, self._global_defs)
446
+ if resolved == "$NONE":
447
+ return False
448
+ if _distinct_models(m, model, self._global_defs, self._mpath):
449
+ return False
450
+ # else o.p does not discrimate
451
+ continue
452
+ if "" in self._oth:
453
+ if _distinct_models(m, self._oth[""], self._global_defs, self._mpath):
454
+ return False
455
+ # self is open so would accept p
456
+ continue
457
+ # else: p is not must nor may nor re nor others!
458
+ return False
459
+ # we did not found any sure discrimination on this way
460
+ return True
461
+
462
+
463
+ def merge_objects(models: list[ModelObject], path: ModelPath) -> JsonObject|str:
464
+ """Merge a list of simple object models."""
465
+
466
+ assert isinstance(models, list) and len(models) > 0
467
+
468
+ m0 = models[0]
469
+ must, may, refs, regs, others = split_object(m0, path + [0])
470
+
471
+ for i, m in enumerate(models[1:]):
472
+
473
+ lpath = path + [i + 1]
474
+ mu, ma, rf, rg, ot = split_object(m, lpath)
475
+
476
+ # combine all properties
477
+ # merge MUST
478
+ for prop, mod in mu.items():
479
+ lppath = path + [prop]
480
+ if prop in must:
481
+ mumod = must[prop]
482
+ if mumod != "$ANY" and mod != "$ANY" and not same_model(mod, mumod):
483
+ raise ModelError(f"incompatible must property {prop} while merging: "
484
+ f"{m0} / {m} {lppath}")
485
+ # else keep best
486
+ if mod != "$ANY" and mumod == "$ANY":
487
+ must[prop] = mod
488
+ elif prop in may:
489
+ mamod = may[prop]
490
+ if mamod != "$ANY" and mod != "$ANY" and not same_model(mod, mamod):
491
+ raise ModelError(f"incompatible must property {prop} while merging: "
492
+ f"{m0} / {m} {lppath}")
493
+ must[prop] = mod if mod != "$ANY" else mamod
494
+ del may[prop]
495
+ else: # new mandatory property
496
+ must[prop] = mod
497
+
498
+ # merge MAY
499
+ for prop, mod in ma.items():
500
+ lppath = path + [prop]
501
+ if prop in must:
502
+ mumod = must[prop]
503
+ if mod != "$ANY" and "mumod" != "$ANY" and not same_model(mod, must[prop]): # ???
504
+ raise ModelError(f"incompatible may property {prop} while merging: "
505
+ f"{m0} / {m} {lppath}")
506
+ # else keep best
507
+ if mod != "$ANY" and mumod == "$ANY":
508
+ must[prop] = mod
509
+ elif prop in may:
510
+ mamod = may[prop]
511
+ if mod != "$ANY" and mamod != "$ANY" and not same_model(mod, mamod):
512
+ raise ModelError(f"incompatible may property {prop} while merging: "
513
+ f"{m0} / {m} {lppath}")
514
+ # else keep best
515
+ if mod != "$ANY" and mamod == "$ANY":
516
+ may[prop] = mod
517
+ else: # new optional property
518
+ may[prop] = mod
519
+
520
+ # merge MAYBE
521
+ def mergeMaybe(dst, src, cat: str, path: ModelPath):
522
+ for prop, mod in src.items():
523
+ lppath = path + [prop]
524
+ if prop in dst:
525
+ dstmod = dst[prop]
526
+ if mod != "$ANY" and dstmod != "$ANY" and not same_model(mod, dstmod):
527
+ raise ModelError(f"incompatible {cat} property {prop} while merging:"
528
+ f"{m0} / {m} {lppath}")
529
+ # else keep best
530
+ if mod != "$ANY" and dstmod == "$ANY":
531
+ dst[prop] = mod
532
+ else: # new property
533
+ dst[prop] = mod
534
+
535
+ mergeMaybe(refs, rf, "refs", path)
536
+ mergeMaybe(regs, rg, "regs", path)
537
+
538
+ # merge OTHERS
539
+ if "" in ot:
540
+ mod = ot[""]
541
+ if "" in others:
542
+ omod = others[""]
543
+ if mod != "$ANY" and omod != "$ANY" and not same_model(mod, omod):
544
+ raise ModelError("incompatible catchall while merging: "
545
+ f"{m0} / {m} [{lpath}.'']")
546
+ # else keep best
547
+ if mod != "$ANY" and omod == "$ANY":
548
+ others[""] = mod
549
+ else: # new catchall
550
+ others = ot
551
+
552
+ return unsplit_object(must, may, refs, regs, others)
553
+
554
+
555
+ def _structurally_distinct_models(lm: list[ModelType], defs: Symbols, mpath: ModelPath) -> bool:
556
+ """Whether all models are structurally distinct.
557
+
558
+ This ensures that values in these are distinct.
559
+ """
560
+ log.debug(f"distinct on {lm}")
561
+ # TODO add other constant values?
562
+ types, objects, strings = set(), [], set()
563
+ for m in lm:
564
+ m = resolve_model(m, defs)
565
+ mt = type(m)
566
+ # special str preprocessing
567
+ if isinstance(m, str):
568
+ if m.startswith("$"): # unresolved reference
569
+ log.debug("- unresolved $-reference")
570
+ return False
571
+ elif m.startswith("="):
572
+ c, v = constant_value(m, mpath)
573
+ assert c
574
+ m, mt = v, type(v)
575
+ # else: empty or re or str constant
576
+
577
+ if mt in (type(None), bool, int, float, list):
578
+ if mt in types:
579
+ log.debug(f"- multiple type {mt.__name__}")
580
+ return False
581
+ types.add(mt)
582
+ elif isinstance(m, str):
583
+ if m == "" or m[0] == "/": # generic string
584
+ if str in types or strings:
585
+ log.debug("- multiple strings")
586
+ return False
587
+ types.add(str)
588
+ else: # constant string
589
+ if str in types:
590
+ log.debug("- constant strings")
591
+ return False
592
+ if m[0] == "_":
593
+ m = m[1:]
594
+ # ???
595
+ if m in strings:
596
+ log.warning(f"repeated constant: {m} {mpath}")
597
+ log.debug("- repeated constant strings")
598
+ return False
599
+ strings.add(m)
600
+ elif isinstance(m, dict):
601
+ if "+" in m: # may try later, after merging
602
+ return False
603
+ assert "@" not in m # should have been resolved!
604
+ # assert "+" not in m # should have been merged!
605
+ if is_constructed(m):
606
+ log.debug(f"- constructed model: {m}")
607
+ return False
608
+ # else dict is a model for an object
609
+ obj = _Object(m, defs, mpath)
610
+ # distinguishable objects?
611
+ # - each object has a mandatory prop which cannot exists in others objects
612
+ # possibly with one exception
613
+ if not objects: # first encounted object
614
+ objects.append(obj)
615
+ else:
616
+ for o in objects:
617
+ if o in obj and obj in o:
618
+ log.debug("- conflicting objects")
619
+ return False
620
+ objects.append(obj)
621
+ else:
622
+ raise ModelError(f"unexpected model type ({mt.__name__}) {mpath}")
623
+ return True