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.
- json_model/README.md +32 -0
- json_model/__init__.py +18 -0
- json_model/analyze.py +409 -0
- json_model/clang.py +563 -0
- json_model/convert.py +430 -0
- json_model/data/clang_entry.c +21 -0
- json_model/data/clang_free.c +10 -0
- json_model/data/clang_init.c +11 -0
- json_model/data/clang_pcre2_fun.c +6 -0
- json_model/data/clang_re2_fun.c +5 -0
- json_model/data/javascript_exe.js +4 -0
- json_model/data/javascript_foot.js +9 -0
- json_model/data/javascript_free.js +9 -0
- json_model/data/javascript_head.js +1 -0
- json_model/data/javascript_init.js +11 -0
- json_model/data/javascript_main.js +5 -0
- json_model/data/plpgsql_entry.sql +16 -0
- json_model/data/python_entry.py +11 -0
- json_model/data/python_exe.py +1 -0
- json_model/data/python_free.py +6 -0
- json_model/data/python_init.py +9 -0
- json_model/data/python_main.py +4 -0
- json_model/javascript.py +310 -0
- json_model/language.py +748 -0
- json_model/model.py +1084 -0
- json_model/mtypes.py +42 -0
- json_model/objmerge.py +165 -0
- json_model/optim.py +486 -0
- json_model/plpgsql.py +422 -0
- json_model/python.py +269 -0
- json_model/recurse.py +127 -0
- json_model/resolver.py +106 -0
- json_model/runtime/META.json +30 -0
- json_model/runtime/Makefile +21 -0
- json_model/runtime/__init__.py +32 -0
- json_model/runtime/json-model.c +1054 -0
- json_model/runtime/json-model.h +183 -0
- json_model/runtime/json_model--2.0.sql +261 -0
- json_model/runtime/json_model.control +2 -0
- json_model/runtime/main.c +473 -0
- json_model/runtime/support.py +485 -0
- json_model/runtime/types.py +16 -0
- json_model/script.py +585 -0
- json_model/url_cache.py +82 -0
- json_model/utils.py +623 -0
- json_model/xstatic.py +1444 -0
- json_model_compiler-2.0b0.dist-info/METADATA +201 -0
- json_model_compiler-2.0b0.dist-info/RECORD +51 -0
- json_model_compiler-2.0b0.dist-info/WHEEL +5 -0
- json_model_compiler-2.0b0.dist-info/entry_points.txt +2 -0
- json_model_compiler-2.0b0.dist-info/top_level.txt +1 -0
json_model/mtypes.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import typing
|
|
2
|
+
|
|
3
|
+
# JSON types
|
|
4
|
+
type Number = int|float
|
|
5
|
+
type JsonScalar = None|bool|int|float|str
|
|
6
|
+
type Jsonable = JsonScalar|list[Jsonable]|dict[str, Jsonable]
|
|
7
|
+
type JsonObject = dict[str, Jsonable]
|
|
8
|
+
type JsonArray = list[Jsonable]
|
|
9
|
+
type JsonPath = list[int|str]
|
|
10
|
+
|
|
11
|
+
type ValueType = Jsonable
|
|
12
|
+
|
|
13
|
+
# JSON Model Types
|
|
14
|
+
type ModelType = Jsonable
|
|
15
|
+
type ModelArray = JsonArray
|
|
16
|
+
type ModelObject = JsonObject
|
|
17
|
+
type ModelPath = JsonPath
|
|
18
|
+
type ModelDefs = dict[str, ModelType]
|
|
19
|
+
type ModelTrafo = ModelType
|
|
20
|
+
type ModelRename = dict[str, str]
|
|
21
|
+
type ModelFilter = typing.Callable[[ModelType, ModelPath], bool]
|
|
22
|
+
type ModelRewrite = typing.Callable[[ModelType, ModelPath], ModelType]
|
|
23
|
+
|
|
24
|
+
type CheckFun = typing.Callable[[ValueType, str], bool]
|
|
25
|
+
type KeyCheckFun = typing.Callable[[str, ValueType, str], bool|None]
|
|
26
|
+
# FIXME remove None
|
|
27
|
+
type Compiler = typing.Callable[[ModelType, str], CheckFun|None]
|
|
28
|
+
|
|
29
|
+
type ModelCheckFun = typing.Callable[[ValueType, JsonPath], bool]
|
|
30
|
+
|
|
31
|
+
JsonModel = typing.NewType("JsonModel", None)
|
|
32
|
+
type Symbols = typing.MutableMapping[str, JsonModel]
|
|
33
|
+
type JsonSchema = bool|dict[str, Jsonable]
|
|
34
|
+
# del JsonModel
|
|
35
|
+
|
|
36
|
+
class ModelError(BaseException):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# remove if not needed!
|
|
41
|
+
class UnknownModel:
|
|
42
|
+
pass
|
json_model/objmerge.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Merging
|
|
3
|
+
#
|
|
4
|
+
import copy
|
|
5
|
+
|
|
6
|
+
from .mtypes import ModelType, ModelPath
|
|
7
|
+
from .utils import log, tname, merge_objects
|
|
8
|
+
from .recurse import recModel, allFlt, builtFlt, noRwt
|
|
9
|
+
from .model import JsonModel
|
|
10
|
+
from . import analyze
|
|
11
|
+
|
|
12
|
+
# - inline defs inside +
|
|
13
|
+
# - distribute + over | and ^
|
|
14
|
+
# - merge objects, removing all +
|
|
15
|
+
#
|
|
16
|
+
def _mergeInlining(jm: JsonModel):
|
|
17
|
+
|
|
18
|
+
changes = 0
|
|
19
|
+
|
|
20
|
+
def miFlt(model: ModelType, path: ModelPath) -> bool:
|
|
21
|
+
|
|
22
|
+
def inline(m: ModelType, p: ModelPath):
|
|
23
|
+
nonlocal changes
|
|
24
|
+
if isinstance(m, str): # actual inlining
|
|
25
|
+
assert m and m[0] == "$"
|
|
26
|
+
if jm._isPredef(m):
|
|
27
|
+
return m
|
|
28
|
+
changes += 1
|
|
29
|
+
jmr = jm.resolveRef(m, p)
|
|
30
|
+
mo = copy.deepcopy(jmr._model)
|
|
31
|
+
log.debug(f"{jm._id} inline from {jmr._id}")
|
|
32
|
+
if jm._defs._id != jmr._defs._id: # if not in same name space
|
|
33
|
+
if jm._loose_int != jmr._loose_int or jm._loose_float != jmr._loose_float:
|
|
34
|
+
log.warning("should not combine models with distinct int/float looseness: "
|
|
35
|
+
f"{jm._url} and {jmr._url}")
|
|
36
|
+
# substitute local references
|
|
37
|
+
def subRefRwt(m, p):
|
|
38
|
+
return jmr._defs.gget(m) if jmr._isRef(m) else m
|
|
39
|
+
return recModel(mo, allFlt, subRefRwt, True)
|
|
40
|
+
else: # keep as is
|
|
41
|
+
return mo
|
|
42
|
+
else:
|
|
43
|
+
assert isinstance(m, dict)
|
|
44
|
+
return m
|
|
45
|
+
|
|
46
|
+
if isinstance(model, dict) and "+" in model:
|
|
47
|
+
plus = model["+"]
|
|
48
|
+
assert isinstance(plus, list) # pyright hint
|
|
49
|
+
model["+"] = [inline(n, path + ["+", i]) for i, n in enumerate(plus)]
|
|
50
|
+
|
|
51
|
+
return True
|
|
52
|
+
|
|
53
|
+
jm._model = recModel(jm._model, miFlt, noRwt, True)
|
|
54
|
+
|
|
55
|
+
log.debug(f"{jm._id}: merge inline {changes}")
|
|
56
|
+
|
|
57
|
+
return changes > 0
|
|
58
|
+
|
|
59
|
+
def _mergeDistribute(jm: JsonModel):
|
|
60
|
+
|
|
61
|
+
changes = 0
|
|
62
|
+
|
|
63
|
+
def isAlt(m: ModelType) -> bool:
|
|
64
|
+
return isinstance(m, dict) and ("|" in m or "^" in m)
|
|
65
|
+
|
|
66
|
+
def mdFlt(model: ModelType, path: ModelPath) -> bool:
|
|
67
|
+
# +( |(A B) C ) -> |( +(A C) +(B C) )
|
|
68
|
+
nonlocal changes
|
|
69
|
+
|
|
70
|
+
dive = builtFlt(model, path)
|
|
71
|
+
|
|
72
|
+
if not isinstance(model, dict) or "+" not in model: # no merge here
|
|
73
|
+
return dive
|
|
74
|
+
|
|
75
|
+
plus, is_xor = model["+"], False
|
|
76
|
+
assert isinstance(plus, list), f"+ type: {tname(plus)}"
|
|
77
|
+
|
|
78
|
+
if not any(map(isAlt, plus)): # nothing to distribute
|
|
79
|
+
return dive
|
|
80
|
+
|
|
81
|
+
# actual distribution
|
|
82
|
+
changes += 1
|
|
83
|
+
|
|
84
|
+
lmodels: list[list[ModelType]] = [[]]
|
|
85
|
+
for m in plus:
|
|
86
|
+
assert isinstance(m, dict) # pyright hint
|
|
87
|
+
if isAlt(m):
|
|
88
|
+
alts = m["|"] if "|" in m else m["^"]
|
|
89
|
+
is_xor |= "^" in m
|
|
90
|
+
assert isinstance(alts, list)
|
|
91
|
+
lmodels = [
|
|
92
|
+
copy.deepcopy(lm) + [n]
|
|
93
|
+
for lm in lmodels
|
|
94
|
+
for n in alts
|
|
95
|
+
]
|
|
96
|
+
else:
|
|
97
|
+
for lm in lmodels:
|
|
98
|
+
lm.append(m)
|
|
99
|
+
|
|
100
|
+
# substitute + by ^ or | in place
|
|
101
|
+
model["^" if is_xor else "|"] = [{"+": lo} for lo in lmodels]
|
|
102
|
+
del model["+"]
|
|
103
|
+
|
|
104
|
+
return dive
|
|
105
|
+
|
|
106
|
+
jm._model = recModel(jm._model, mdFlt, noRwt)
|
|
107
|
+
|
|
108
|
+
log.debug(f"{jm._id}: merge distribute {changes}")
|
|
109
|
+
|
|
110
|
+
return changes > 0
|
|
111
|
+
|
|
112
|
+
def _mergeObjects(jm: JsonModel):
|
|
113
|
+
"""Actually compute and remove operator "+"."""
|
|
114
|
+
|
|
115
|
+
changes = 0
|
|
116
|
+
|
|
117
|
+
def moRwt(model: ModelType, path: ModelPath) -> ModelType:
|
|
118
|
+
nonlocal changes
|
|
119
|
+
if not isinstance(model, dict) or "+" not in model:
|
|
120
|
+
return model
|
|
121
|
+
changes += 1
|
|
122
|
+
plus = model["+"]
|
|
123
|
+
assert isinstance(plus, list) # pyright hint
|
|
124
|
+
merged = merge_objects(plus, path + ["+"]) # pyright: ignore
|
|
125
|
+
del model["+"]
|
|
126
|
+
if len(model) > 0:
|
|
127
|
+
model["@"] = merged
|
|
128
|
+
else:
|
|
129
|
+
assert isinstance(merged, dict) # pyright hint
|
|
130
|
+
model.update(merged)
|
|
131
|
+
return model
|
|
132
|
+
|
|
133
|
+
jm._model = recModel(jm._model, builtFlt, moRwt)
|
|
134
|
+
|
|
135
|
+
log.debug(f"{jm._id}: merge objects {changes}")
|
|
136
|
+
|
|
137
|
+
return changes > 0
|
|
138
|
+
|
|
139
|
+
def merge(jm: JsonModel):
|
|
140
|
+
|
|
141
|
+
# NOTE after distribution, more inlining may be required
|
|
142
|
+
# +( |( $A, {.1.} ), {.2.} ) -> |( +( $A, {.2.} ), +( {.1.}, {.2.} ) )
|
|
143
|
+
|
|
144
|
+
updated = True
|
|
145
|
+
while updated:
|
|
146
|
+
_mergeInlining(jm)
|
|
147
|
+
updated = _mergeDistribute(jm)
|
|
148
|
+
|
|
149
|
+
if jm._debug: # check merge precondition
|
|
150
|
+
|
|
151
|
+
def is_object(m: ModelType) -> bool: # NOTE "+" is allowed
|
|
152
|
+
return isinstance(m, dict) and not ("@" in m or "|" in m or "^" in m or "&" in m)
|
|
153
|
+
|
|
154
|
+
def merge_on_objects(model: ModelType, path: ModelPath) -> bool:
|
|
155
|
+
if isinstance(model, dict) and "+" in model:
|
|
156
|
+
assert isinstance(plus := model["+"], list) # sanity
|
|
157
|
+
return all(map(is_object, plus))
|
|
158
|
+
return True
|
|
159
|
+
|
|
160
|
+
assert analyze.check(jm, merge_on_objects, "only objects under +")
|
|
161
|
+
|
|
162
|
+
_mergeObjects(jm)
|
|
163
|
+
|
|
164
|
+
if jm._debug:
|
|
165
|
+
assert analyze.check(jm, lambda m, _: not isinstance(m, dict) or "+" not in m)
|
json_model/optim.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Model Optimizations
|
|
3
|
+
#
|
|
4
|
+
from .mtypes import ModelPath, ModelType
|
|
5
|
+
from .utils import log, is_cst, _structurally_distinct_models, constant_value, same_model
|
|
6
|
+
from .recurse import recModel, allFlt, builtFlt
|
|
7
|
+
from .model import JsonModel
|
|
8
|
+
from .analyze import ultimate_type
|
|
9
|
+
from .runtime import ConstSet
|
|
10
|
+
|
|
11
|
+
def real_equal(i, j) -> bool: # avoid True == 1 and 0.0 == 0…
|
|
12
|
+
return type(i) is type(j) and i == j
|
|
13
|
+
|
|
14
|
+
def minl(model: ModelType, models: list[ModelType]) -> bool:
|
|
15
|
+
return any(map(lambda m: real_equal(m, model), models))
|
|
16
|
+
|
|
17
|
+
# remove one occurence from list of models
|
|
18
|
+
def mdell(model: ModelType, models: list[ModelType]) -> bool:
|
|
19
|
+
index = -1
|
|
20
|
+
for i, m in enumerate(models):
|
|
21
|
+
if real_equal(m, model):
|
|
22
|
+
index = i
|
|
23
|
+
if index != -1:
|
|
24
|
+
del models[index]
|
|
25
|
+
return index != -1
|
|
26
|
+
|
|
27
|
+
def normalizeModels(models: list[ModelType]) -> int:
|
|
28
|
+
"""Replace model predefs in the list with their canonic form."""
|
|
29
|
+
IGNORE = object()
|
|
30
|
+
changes = 0
|
|
31
|
+
|
|
32
|
+
for idx, model in enumerate(models):
|
|
33
|
+
nmodel = IGNORE
|
|
34
|
+
if isinstance(model, str):
|
|
35
|
+
if model == "$STRING":
|
|
36
|
+
nmodel = ""
|
|
37
|
+
elif model in ("$INT", "$INTEGER", "$I32", "$I64"):
|
|
38
|
+
nmodel = -1
|
|
39
|
+
elif model in ("$U32", "$U64"):
|
|
40
|
+
nmodel = 0
|
|
41
|
+
elif model in ("$FLOAT", "$F32", "$F64"):
|
|
42
|
+
nmodel = -1.0
|
|
43
|
+
elif model in ("$BOOL", "$BOOLEAN"):
|
|
44
|
+
nmodel = True
|
|
45
|
+
elif model in ("$NULL", "=null"):
|
|
46
|
+
nmodel = None
|
|
47
|
+
if nmodel != IGNORE:
|
|
48
|
+
changes += 1
|
|
49
|
+
models[idx] = nmodel # type: ignore
|
|
50
|
+
|
|
51
|
+
return changes
|
|
52
|
+
|
|
53
|
+
def xor_to_or(jm: JsonModel):
|
|
54
|
+
"""Change xor to less coslty or if possible."""
|
|
55
|
+
|
|
56
|
+
changes = 0
|
|
57
|
+
|
|
58
|
+
def x2oRwt(model: ModelType, path: ModelPath) -> ModelType:
|
|
59
|
+
nonlocal changes
|
|
60
|
+
if isinstance(model, dict) and "^" in model:
|
|
61
|
+
xor = model["^"]
|
|
62
|
+
lpath = path + ["^"]
|
|
63
|
+
assert isinstance(xor, list) and "|" not in model
|
|
64
|
+
|
|
65
|
+
consts = [constant_value(m, lpath + [i]) for i, m in enumerate(xor)]
|
|
66
|
+
|
|
67
|
+
# constant-only enum case
|
|
68
|
+
if all(consts[i][0] for i in range(len(xor))):
|
|
69
|
+
if len(ConstSet([consts[i][1] for i in range(len(xor))])) == len(xor): # type: ignore
|
|
70
|
+
changes += 1
|
|
71
|
+
del model["^"]
|
|
72
|
+
model["|"] = xor
|
|
73
|
+
# else some constants are repeated thus excluded by "^"
|
|
74
|
+
elif _structurally_distinct_models(xor, jm._defs, lpath): # pyright: ignore
|
|
75
|
+
changes += 1
|
|
76
|
+
del model["^"]
|
|
77
|
+
model["|"] = xor
|
|
78
|
+
|
|
79
|
+
return model
|
|
80
|
+
|
|
81
|
+
jm._model = recModel(jm._model, builtFlt, x2oRwt)
|
|
82
|
+
|
|
83
|
+
log.debug(f"{jm._id}: x2o {changes}")
|
|
84
|
+
|
|
85
|
+
return changes > 0
|
|
86
|
+
|
|
87
|
+
def flatten(jm: JsonModel):
|
|
88
|
+
"""Flatten or, xor, and and merge operators."""
|
|
89
|
+
|
|
90
|
+
changes = 0
|
|
91
|
+
|
|
92
|
+
def flatRwt(model: ModelType, path: ModelPath) -> ModelType:
|
|
93
|
+
nonlocal changes
|
|
94
|
+
for op in ("|", "&", "^", "+"):
|
|
95
|
+
if isinstance(model, dict) and op in model:
|
|
96
|
+
models, updated = model[op], False
|
|
97
|
+
assert isinstance(models, list)
|
|
98
|
+
nmodels = []
|
|
99
|
+
# NOTE empty lists are handled in eval
|
|
100
|
+
if len(models) == 1:
|
|
101
|
+
changes += 1
|
|
102
|
+
return models[0]
|
|
103
|
+
for m in models:
|
|
104
|
+
if isinstance(m, dict) and op in m:
|
|
105
|
+
changes += 1
|
|
106
|
+
updated = True
|
|
107
|
+
lm = m[op]
|
|
108
|
+
assert isinstance(lm, list)
|
|
109
|
+
nmodels.extend(lm)
|
|
110
|
+
else:
|
|
111
|
+
nmodels.append(m)
|
|
112
|
+
if updated:
|
|
113
|
+
model[op] = nmodels
|
|
114
|
+
return model
|
|
115
|
+
|
|
116
|
+
jm._model = recModel(jm._model, builtFlt, flatRwt)
|
|
117
|
+
|
|
118
|
+
log.debug(f"{jm._id}: flatten {changes}")
|
|
119
|
+
|
|
120
|
+
return changes > 0
|
|
121
|
+
|
|
122
|
+
def const_prop(jm: JsonModel):
|
|
123
|
+
"""Propagate constants and predefs to their references."""
|
|
124
|
+
|
|
125
|
+
changes = 0
|
|
126
|
+
|
|
127
|
+
def cpRwt(model: ModelType, path: ModelPath) -> ModelType:
|
|
128
|
+
nonlocal changes
|
|
129
|
+
if jm._isRef(model):
|
|
130
|
+
jmp = jm.resolveRef(model, path)
|
|
131
|
+
if jm._isPredef(jmp._model):
|
|
132
|
+
changes += 1
|
|
133
|
+
return jmp._model
|
|
134
|
+
elif is_cst(jmp._model):
|
|
135
|
+
changes += 1
|
|
136
|
+
return jmp._model
|
|
137
|
+
return model
|
|
138
|
+
|
|
139
|
+
jm._model = recModel(jm._model, allFlt, cpRwt, True)
|
|
140
|
+
|
|
141
|
+
log.debug(f"{jm._id}: constant propagation {changes}")
|
|
142
|
+
|
|
143
|
+
return changes > 0
|
|
144
|
+
|
|
145
|
+
def partial_eval(jm: JsonModel):
|
|
146
|
+
"""Model partial evaluation."""
|
|
147
|
+
|
|
148
|
+
changes = 0
|
|
149
|
+
|
|
150
|
+
# helpers
|
|
151
|
+
def empty_obj(o):
|
|
152
|
+
return isinstance(o, dict) and (len(o) == 0 or len(o) == 1 and "#" in o)
|
|
153
|
+
|
|
154
|
+
def deduplicate(lv):
|
|
155
|
+
# return list(set(l)) # too easy: {True, 1} == {True}
|
|
156
|
+
# TODO use an extended ConstSet?
|
|
157
|
+
n = []
|
|
158
|
+
for i in lv:
|
|
159
|
+
if not any(map(lambda x: real_equal(x, i), n)):
|
|
160
|
+
n.append(i)
|
|
161
|
+
return n
|
|
162
|
+
|
|
163
|
+
def evalRwt(model: ModelType, path: ModelPath) -> ModelType:
|
|
164
|
+
nonlocal changes
|
|
165
|
+
if isinstance(model, str) and jm._isRef(model):
|
|
166
|
+
jms = jm.resolveRef(model, path)
|
|
167
|
+
if isinstance(jms._model, str) and jms._isPredef(jm._model):
|
|
168
|
+
changes += 1
|
|
169
|
+
return jms._model
|
|
170
|
+
|
|
171
|
+
elif isinstance(model, dict):
|
|
172
|
+
|
|
173
|
+
if "|" in model: # optimize OR
|
|
174
|
+
lor = model["|"]
|
|
175
|
+
assert isinstance(lor, list)
|
|
176
|
+
changes += normalizeModels(lor)
|
|
177
|
+
|
|
178
|
+
# int type inclusions
|
|
179
|
+
if minl(1, lor) and (minl(0, lor) or minl(-1, lor)):
|
|
180
|
+
changes += 1
|
|
181
|
+
mdell(1, lor)
|
|
182
|
+
if minl(0, lor) and minl(-1, lor):
|
|
183
|
+
changes += 1
|
|
184
|
+
mdell(0, lor)
|
|
185
|
+
|
|
186
|
+
# float type inclusions
|
|
187
|
+
if minl(1.0, lor) and (minl(0.0, lor) or minl(-1.0, lor)):
|
|
188
|
+
changes += 1
|
|
189
|
+
mdell(1.0, lor)
|
|
190
|
+
if minl(0.0, lor) and minl(-1.0, lor):
|
|
191
|
+
changes += 1
|
|
192
|
+
mdell(0.0, lor)
|
|
193
|
+
if minl("", lor) and minl("$STRING", lor):
|
|
194
|
+
changes += 1
|
|
195
|
+
mdell("$STRING", lor)
|
|
196
|
+
|
|
197
|
+
# others
|
|
198
|
+
if len(lor) == 0:
|
|
199
|
+
changes += 1
|
|
200
|
+
return "$NONE"
|
|
201
|
+
elif "$ANY" in lor:
|
|
202
|
+
changes += 1
|
|
203
|
+
return "$ANY"
|
|
204
|
+
elif "$NONE" in lor:
|
|
205
|
+
changes += 1
|
|
206
|
+
model["|"] = lor = list(filter(lambda m: m != "$NONE", lor))
|
|
207
|
+
elif len(lv := deduplicate(lor)) != len(lor):
|
|
208
|
+
changes += 1
|
|
209
|
+
model["|"] = lor = lv
|
|
210
|
+
|
|
211
|
+
if len(lor) == 1:
|
|
212
|
+
changes += 1
|
|
213
|
+
return lor[0]
|
|
214
|
+
|
|
215
|
+
elif "&" in model: # optimize AND
|
|
216
|
+
land = model["&"]
|
|
217
|
+
assert isinstance(land, list)
|
|
218
|
+
changes += normalizeModels(land)
|
|
219
|
+
|
|
220
|
+
# manage simple type inclusions on ints
|
|
221
|
+
if minl(-1, land) and (minl(0, land) or minl(1, land)):
|
|
222
|
+
mdell(-1, land)
|
|
223
|
+
if minl(0, land) and minl(1, land):
|
|
224
|
+
mdell(0, land)
|
|
225
|
+
|
|
226
|
+
# idem on floats
|
|
227
|
+
if minl(-1.0, land) and (minl(0.0, land) or minl(1.0, land)):
|
|
228
|
+
mdell(-1.0, land)
|
|
229
|
+
if minl(0.0, land) and minl(1.0, land):
|
|
230
|
+
mdell(0.0, land)
|
|
231
|
+
|
|
232
|
+
# other optimizations
|
|
233
|
+
if len(land) == 0:
|
|
234
|
+
changes += 1
|
|
235
|
+
return "$ANY"
|
|
236
|
+
elif "$NONE" in land:
|
|
237
|
+
changes += 1
|
|
238
|
+
return "$NONE"
|
|
239
|
+
elif len(lv := deduplicate(land)) != len(land):
|
|
240
|
+
changes += 1
|
|
241
|
+
model["&"] = land = lv
|
|
242
|
+
if len(land) == 1:
|
|
243
|
+
changes += 1
|
|
244
|
+
return land[0]
|
|
245
|
+
# if ultimates types are distinct, no value can match
|
|
246
|
+
utypes = set(ultimate_type(jm, m) for m in land)
|
|
247
|
+
if None not in utypes and len(utypes) > 1 or None in utypes and len(utypes) > 2:
|
|
248
|
+
return "$NONE"
|
|
249
|
+
|
|
250
|
+
elif "^" in model: # optimize XOR
|
|
251
|
+
lxor = model["^"]
|
|
252
|
+
assert isinstance(lxor, list)
|
|
253
|
+
changes += normalizeModels(lxor)
|
|
254
|
+
if len(lxor) == 2:
|
|
255
|
+
if same_model(lxor[0], lxor[1]):
|
|
256
|
+
return "$NONE"
|
|
257
|
+
if len(lxor) == 0:
|
|
258
|
+
changes += 1
|
|
259
|
+
return "$NONE"
|
|
260
|
+
elif len(lxor) == 1:
|
|
261
|
+
changes += 1
|
|
262
|
+
return lxor[0]
|
|
263
|
+
elif "$NONE" in lxor:
|
|
264
|
+
changes += 1
|
|
265
|
+
model["^"] = list(filter(lambda m: m != "$NONE", lxor))
|
|
266
|
+
elif len(list(filter(lambda m: m == "$ANY", lxor))) >= 2:
|
|
267
|
+
changes += 1
|
|
268
|
+
return "$NONE"
|
|
269
|
+
# TODO more cleanups
|
|
270
|
+
# ^(A A ...) = ^(...) ? not so, depends on inclusions?
|
|
271
|
+
|
|
272
|
+
elif "+" in model: # optimize MERGE
|
|
273
|
+
plus = model["+"]
|
|
274
|
+
assert isinstance(plus, list)
|
|
275
|
+
if len(plus) == 0: # {"+": []} == {}
|
|
276
|
+
changes += 1
|
|
277
|
+
del model["+"]
|
|
278
|
+
elif len(plus) == 1:
|
|
279
|
+
changes += 1
|
|
280
|
+
return plus[0]
|
|
281
|
+
elif any(map(empty_obj, plus)):
|
|
282
|
+
changes += 1
|
|
283
|
+
model["+"] = list(filter(lambda o: not empty_obj(o), plus))
|
|
284
|
+
# TODO more cleanup? could I remove $NONE? $ANY?
|
|
285
|
+
|
|
286
|
+
elif "@" in model:
|
|
287
|
+
|
|
288
|
+
# "!": false is the default, so is not needed
|
|
289
|
+
if "!" in model and not model["!"]:
|
|
290
|
+
changes += 1
|
|
291
|
+
del model["!"]
|
|
292
|
+
# constraint without actual constraints
|
|
293
|
+
if not (set(model.keys()) - {"#", "~", "$", "%", "@"}):
|
|
294
|
+
# keep directives
|
|
295
|
+
if path == [] and "#" in model:
|
|
296
|
+
assert isinstance(model["#"], str)
|
|
297
|
+
if "JSON_MODEL_" in model["#"]:
|
|
298
|
+
return model
|
|
299
|
+
changes += 1
|
|
300
|
+
return model["@"]
|
|
301
|
+
# some non-feasable numerical cases
|
|
302
|
+
lev, gev = None, None
|
|
303
|
+
# add type information
|
|
304
|
+
if isinstance(model["@"], float):
|
|
305
|
+
if model["@"] in (0.0, 1.0):
|
|
306
|
+
gev = 0.0
|
|
307
|
+
elif isinstance(model["@"], int):
|
|
308
|
+
if model["@"] == 0:
|
|
309
|
+
gev = 0.0
|
|
310
|
+
elif model["@"] == 1:
|
|
311
|
+
gev = 1.0
|
|
312
|
+
# map < and <= together for now
|
|
313
|
+
if "<" in model:
|
|
314
|
+
if isinstance(model["<"], (int, float)):
|
|
315
|
+
lev = float(model["<"])
|
|
316
|
+
if "<=" in model:
|
|
317
|
+
if isinstance(model["<="], (int, float)):
|
|
318
|
+
v = float(model["<="])
|
|
319
|
+
lev = v if lev is None else min(lev, v)
|
|
320
|
+
# idem > and >=
|
|
321
|
+
if ">" in model:
|
|
322
|
+
if isinstance(model[">"], (int, float)):
|
|
323
|
+
gev = float(model[">"])
|
|
324
|
+
if ">=" in model:
|
|
325
|
+
if isinstance(model[">="], (int, float)):
|
|
326
|
+
v = float(model[">="])
|
|
327
|
+
gev = v if gev is None else max(gev, v)
|
|
328
|
+
# map = to <= and >=
|
|
329
|
+
if "=" in model:
|
|
330
|
+
if isinstance(model["="], (int, float)):
|
|
331
|
+
v = float(model["="])
|
|
332
|
+
lev = v if lev is None else min(lev, v)
|
|
333
|
+
gev = v if gev is None else max(gev, v)
|
|
334
|
+
# conclude for < <= = > >=
|
|
335
|
+
if gev is not None and lev is not None and gev > lev:
|
|
336
|
+
changes += 1
|
|
337
|
+
return "$NONE"
|
|
338
|
+
# cleanup redundant !=
|
|
339
|
+
if "!=" in model:
|
|
340
|
+
if isinstance(model["!="], (int, float)):
|
|
341
|
+
nev = float(model["!="])
|
|
342
|
+
if gev is not None and nev < gev or lev is not None and lev < nev:
|
|
343
|
+
changes += 1
|
|
344
|
+
del model["!="]
|
|
345
|
+
# TODO could do other cases about str?
|
|
346
|
+
return model
|
|
347
|
+
|
|
348
|
+
jm._model = recModel(jm._model, allFlt, evalRwt)
|
|
349
|
+
|
|
350
|
+
log.debug(f"{jm._id}: eval {changes}")
|
|
351
|
+
|
|
352
|
+
return changes > 0
|
|
353
|
+
|
|
354
|
+
def simplify(jm: JsonModel):
|
|
355
|
+
"""Simplify properties and constraints in some case."""
|
|
356
|
+
|
|
357
|
+
changes: int = 0
|
|
358
|
+
|
|
359
|
+
def simpRwt(model: ModelType, path: ModelPath) -> ModelType:
|
|
360
|
+
nonlocal changes
|
|
361
|
+
if isinstance(model, dict):
|
|
362
|
+
for old, new in [ ("//", ""), ("/^$/", "?")]:
|
|
363
|
+
# FIXME in some corner case the simplification may be wrong…
|
|
364
|
+
if old in model and new not in model:
|
|
365
|
+
model[new] = model[old]
|
|
366
|
+
del model[old]
|
|
367
|
+
if "@" in model:
|
|
368
|
+
ultimate = ultimate_type(jm, model)
|
|
369
|
+
if ultimate in (None, float): # keep safe
|
|
370
|
+
return model
|
|
371
|
+
# else keep int, str, list, dict
|
|
372
|
+
# detect redundant or infeasible int constraints
|
|
373
|
+
le = None if "<=" not in model or not isinstance(model["<="], int) else model["<="]
|
|
374
|
+
lt = None if "<" not in model or not isinstance(model["<"], int) else model["<"]
|
|
375
|
+
eq = None if "=" not in model or not isinstance(model["="], int) else model["="]
|
|
376
|
+
ne = None if "!=" not in model or not isinstance(model["!="], int) else model["!="]
|
|
377
|
+
ge = None if ">=" not in model or not isinstance(model[">="], int) else model[">="]
|
|
378
|
+
gt = None if ">" not in model or not isinstance(model[">"], int) else model[">"]
|
|
379
|
+
# replace gt/lt by ge/le
|
|
380
|
+
if lt is not None:
|
|
381
|
+
le = lt - 1 if le is None or le >= lt else le
|
|
382
|
+
lt = None
|
|
383
|
+
del model["<"]
|
|
384
|
+
changes += 1
|
|
385
|
+
if gt is not None:
|
|
386
|
+
ge = gt + 1 if ge is None or ge <= gt else ge
|
|
387
|
+
gt = None
|
|
388
|
+
del model[">"]
|
|
389
|
+
changes += 1
|
|
390
|
+
# boolean and null cannot have int comparisons
|
|
391
|
+
if ultimate in (type(None), bool) and \
|
|
392
|
+
(ge is not None or le is not None or eq is not None or ne is not None):
|
|
393
|
+
changes += 1
|
|
394
|
+
return "$NONE"
|
|
395
|
+
# ge/le consistency and simplification
|
|
396
|
+
if ge is not None and le is not None:
|
|
397
|
+
if le < ge:
|
|
398
|
+
changes += 1
|
|
399
|
+
return "$NONE"
|
|
400
|
+
if le == ge:
|
|
401
|
+
changes += 1
|
|
402
|
+
eq, le, ge = le, None, None
|
|
403
|
+
# eq consistency and redundancy
|
|
404
|
+
if eq is not None:
|
|
405
|
+
if le is not None:
|
|
406
|
+
if eq > le:
|
|
407
|
+
changes += 1
|
|
408
|
+
return "$NONE"
|
|
409
|
+
le = None
|
|
410
|
+
del model["<="]
|
|
411
|
+
changes += 1
|
|
412
|
+
if ge is not None:
|
|
413
|
+
if eq < ge:
|
|
414
|
+
changes += 1
|
|
415
|
+
return "$NONE"
|
|
416
|
+
ge = None
|
|
417
|
+
del model[">="]
|
|
418
|
+
changes += 1
|
|
419
|
+
if ne is not None:
|
|
420
|
+
if eq == ne:
|
|
421
|
+
changes += 1
|
|
422
|
+
return "$NONE"
|
|
423
|
+
ne = None
|
|
424
|
+
del model["!="]
|
|
425
|
+
changes += 1
|
|
426
|
+
# ne redundancy
|
|
427
|
+
if ne is not None:
|
|
428
|
+
if le is not None:
|
|
429
|
+
if ne > le: # type: ignore
|
|
430
|
+
changes += 1
|
|
431
|
+
ne = None
|
|
432
|
+
del model["!="]
|
|
433
|
+
if ge is not None:
|
|
434
|
+
if ne < ge: # type: ignore
|
|
435
|
+
changes += 1
|
|
436
|
+
ne = None
|
|
437
|
+
del model["!="]
|
|
438
|
+
# integer target
|
|
439
|
+
if isinstance(model["@"], str) and model["@"] in ("$INT", "$INTEGER"):
|
|
440
|
+
changes += 1
|
|
441
|
+
model["@"] = -1
|
|
442
|
+
if isinstance(model["@"], int):
|
|
443
|
+
target = model["@"]
|
|
444
|
+
if eq is not None:
|
|
445
|
+
changes += 1
|
|
446
|
+
if eq < target:
|
|
447
|
+
return "$NONE"
|
|
448
|
+
else:
|
|
449
|
+
return f"={eq}"
|
|
450
|
+
if ge is not None:
|
|
451
|
+
if ge == 1 and target != 1:
|
|
452
|
+
changes += 1
|
|
453
|
+
model["@"] = 1
|
|
454
|
+
ge = None
|
|
455
|
+
elif ge == 0 and target == -1:
|
|
456
|
+
changes += 1
|
|
457
|
+
model["@"] = 0
|
|
458
|
+
ge = None
|
|
459
|
+
if le is not None:
|
|
460
|
+
if target >= 0 and target > le:
|
|
461
|
+
changes += 1
|
|
462
|
+
return "$NONE"
|
|
463
|
+
# update possibly changed values
|
|
464
|
+
if le is not None:
|
|
465
|
+
model["<="] = le
|
|
466
|
+
elif "<=" in model:
|
|
467
|
+
del model["<="]
|
|
468
|
+
if ge is not None:
|
|
469
|
+
model[">="] = ge
|
|
470
|
+
elif ">=" in model:
|
|
471
|
+
del model[">="]
|
|
472
|
+
return model
|
|
473
|
+
|
|
474
|
+
jm._model = recModel(jm._model, allFlt, simpRwt)
|
|
475
|
+
|
|
476
|
+
return changes > 0
|
|
477
|
+
|
|
478
|
+
def optimize(jm: JsonModel):
|
|
479
|
+
changed = True
|
|
480
|
+
while changed:
|
|
481
|
+
changed = False
|
|
482
|
+
changed |= const_prop(jm)
|
|
483
|
+
changed |= simplify(jm)
|
|
484
|
+
changed |= partial_eval(jm)
|
|
485
|
+
changed |= flatten(jm)
|
|
486
|
+
changed |= xor_to_or(jm)
|