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/clang.py
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from .language import Language, Block, Var, PropMap, ConstList
|
|
3
|
+
from .language import JsonExpr, BoolExpr, IntExpr, StrExpr, PathExpr, Expr
|
|
4
|
+
from .mtypes import Jsonable, JsonScalar, Number
|
|
5
|
+
|
|
6
|
+
_ESC_TABLE = { '"': r'\"', "\\": "\\\\" }
|
|
7
|
+
|
|
8
|
+
class CLangJansson(Language):
|
|
9
|
+
"""Generate JSON value checker in C with Jansson and PCRE2.
|
|
10
|
+
|
|
11
|
+
This implementation relies on inheritance for many methods, thanks to the root
|
|
12
|
+
class heavy parameterization about operators, end-of-instruction and the like.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, *,
|
|
16
|
+
debug: bool = False,
|
|
17
|
+
with_path: bool = True, with_report: bool = True, with_comment: bool = True,
|
|
18
|
+
relib: str = "pcre2", int_t: str = "int64_t"):
|
|
19
|
+
|
|
20
|
+
super().__init__(
|
|
21
|
+
"C",
|
|
22
|
+
with_path=with_path, with_report=with_report, with_comment=with_comment,
|
|
23
|
+
not_op="!", and_op="&&", or_op="||", lcom="//",
|
|
24
|
+
true="true", false="false", null="NULL", check_t="jm_check_fun_t", json_t="json_t *",
|
|
25
|
+
path_t="jm_path_t", float_t="double", str_t="char *",
|
|
26
|
+
match_t="bool" if relib == "pcre2" else "int",
|
|
27
|
+
eoi=";", relib=relib, debug=debug,
|
|
28
|
+
set_caps=(type(None), bool, int, float, str)) # type: ignore
|
|
29
|
+
|
|
30
|
+
assert relib in ("pcre2", "re2"), f"regex engine {relib} is not supported, try: pcre2/re2"
|
|
31
|
+
|
|
32
|
+
# we keep 2 ints: "int64_t" and "int"
|
|
33
|
+
self._int: str = int_t
|
|
34
|
+
self._json_esc_table = str.maketrans(_ESC_TABLE)
|
|
35
|
+
|
|
36
|
+
#
|
|
37
|
+
# file
|
|
38
|
+
#
|
|
39
|
+
def file_header(self, exe: bool = True) -> Block:
|
|
40
|
+
code: Block = super().file_header(exe)
|
|
41
|
+
code += [ "", "// regular expression engine" ]
|
|
42
|
+
if self._relib == "pcre2":
|
|
43
|
+
code += [
|
|
44
|
+
"#define PCRE2_CODE_UNIT_WIDTH 8",
|
|
45
|
+
"#include <pcre2.h>",
|
|
46
|
+
]
|
|
47
|
+
else:
|
|
48
|
+
code += [
|
|
49
|
+
"#include <stddef.h>",
|
|
50
|
+
"#include <cre2.h>",
|
|
51
|
+
]
|
|
52
|
+
code += [
|
|
53
|
+
"",
|
|
54
|
+
r"#include <json-model.h>",
|
|
55
|
+
f"#define JSON_MODEL_VERSION {self.esc(self._version)}"
|
|
56
|
+
]
|
|
57
|
+
return code
|
|
58
|
+
|
|
59
|
+
def file_footer(self, exe: bool = True) -> Block:
|
|
60
|
+
return [""] + self.file_load("clang_entry.c")
|
|
61
|
+
|
|
62
|
+
#
|
|
63
|
+
# inlined type test expressions about JSON data
|
|
64
|
+
#
|
|
65
|
+
def is_num(self, var: Var) -> BoolExpr:
|
|
66
|
+
return f"json_is_number({var})"
|
|
67
|
+
|
|
68
|
+
def is_scalar(self, var: Var) -> BoolExpr:
|
|
69
|
+
return f"jm_json_is_scalar({var})"
|
|
70
|
+
|
|
71
|
+
def is_def(self, var: Var) -> BoolExpr:
|
|
72
|
+
return f"{var} != NULL"
|
|
73
|
+
|
|
74
|
+
def is_a(self, var: Var, tval: type|None, loose: bool|None = None) -> BoolExpr:
|
|
75
|
+
assert loose is None or tval in (int, float, Number)
|
|
76
|
+
if tval is None or tval is type(None):
|
|
77
|
+
return f"json_is_null({var})"
|
|
78
|
+
elif tval is bool:
|
|
79
|
+
return f"json_is_boolean({var})"
|
|
80
|
+
elif tval is int:
|
|
81
|
+
is_an_int = f"json_is_integer({var})"
|
|
82
|
+
if loose:
|
|
83
|
+
is_an_int = (
|
|
84
|
+
"(" + is_an_int + " || " +
|
|
85
|
+
f"(json_is_real({var}) && "
|
|
86
|
+
f"json_real_value({var}) == (({self._int}) json_real_value({var}))))")
|
|
87
|
+
return is_an_int
|
|
88
|
+
elif tval is float:
|
|
89
|
+
return self.is_num(var) if loose else f"json_is_real({var})"
|
|
90
|
+
elif tval is Number:
|
|
91
|
+
return self.is_num(var)
|
|
92
|
+
elif tval is str:
|
|
93
|
+
return f"json_is_string({var})"
|
|
94
|
+
elif tval is list:
|
|
95
|
+
return f"json_is_array({var})"
|
|
96
|
+
elif tval is dict:
|
|
97
|
+
return f"json_is_object({var})"
|
|
98
|
+
else:
|
|
99
|
+
raise Exception(f"unexpected type for json: {tval.__name__}")
|
|
100
|
+
|
|
101
|
+
def _json_str(self, j) -> str:
|
|
102
|
+
return '"' + json.dumps(j).translate(self._json_esc_table) + '"'
|
|
103
|
+
|
|
104
|
+
def json_cst(self, j: Jsonable) -> JsonExpr:
|
|
105
|
+
return f"json_loads({self._json_str(j)}, JSON_DECODE_ANY|JSON_ALLOW_NUL, NULL)"
|
|
106
|
+
|
|
107
|
+
def const(self, c: Jsonable) -> Expr:
|
|
108
|
+
if isinstance(c, (list, dict)):
|
|
109
|
+
return self.json_cst(c)
|
|
110
|
+
else:
|
|
111
|
+
return super().const(c)
|
|
112
|
+
|
|
113
|
+
def has_prop(self, obj: Var, prop: str) -> BoolExpr:
|
|
114
|
+
return f"json_object_get({obj}, {self.esc(prop)}) != NULL"
|
|
115
|
+
|
|
116
|
+
# FIXME path? reporting?
|
|
117
|
+
def predef(self, var: Var, name: str, path: Var, is_str: bool = False) -> BoolExpr:
|
|
118
|
+
val = var if is_str else f"json_string_value({var})"
|
|
119
|
+
if name == "$UUID":
|
|
120
|
+
return f"jm_is_valid_uuid({val}, {path}, rep)"
|
|
121
|
+
elif name == "$DATE":
|
|
122
|
+
return f"jm_is_valid_date({val}, {path}, rep)"
|
|
123
|
+
elif name == "$TIME":
|
|
124
|
+
return f"jm_is_valid_time({val}, {path}, rep)"
|
|
125
|
+
elif name == "$DATETIME":
|
|
126
|
+
return f"jm_is_valid_datetime({val}, {path}, rep)"
|
|
127
|
+
elif name == "$REGEX":
|
|
128
|
+
return f"jm_is_valid_regex({val}, false, {path}, rep)"
|
|
129
|
+
elif name == "$EXREG":
|
|
130
|
+
return f"jm_is_valid_regex({val}, true, {path}, rep)"
|
|
131
|
+
elif name in ("$URL", "$URI"):
|
|
132
|
+
return f"jm_is_valid_url({val}, {path}, rep)"
|
|
133
|
+
elif name == "$EMAIL":
|
|
134
|
+
return f"jm_is_valid_email({val}, {path}, rep)"
|
|
135
|
+
else:
|
|
136
|
+
return super().predef(var, name, path, is_str)
|
|
137
|
+
|
|
138
|
+
def value(self, var: Var, tvar: type) -> Expr:
|
|
139
|
+
"""Known type value extraction."""
|
|
140
|
+
if tvar is type(None):
|
|
141
|
+
return "NULL"
|
|
142
|
+
elif tvar is bool:
|
|
143
|
+
return f"json_boolean_value({var})"
|
|
144
|
+
elif tvar is int:
|
|
145
|
+
return f"json_integer_value({var})"
|
|
146
|
+
elif tvar is float:
|
|
147
|
+
return f"json_real_value({var})"
|
|
148
|
+
elif tvar is Number: # NOTE this cast from int if necessary
|
|
149
|
+
return f"json_number_value({var})"
|
|
150
|
+
elif tvar is str:
|
|
151
|
+
return f"json_string_value({var})"
|
|
152
|
+
else:
|
|
153
|
+
raise Exception(f"unexpected type for value extraction: {tvar.__name__}")
|
|
154
|
+
|
|
155
|
+
def arr_item_val(self, arr: Var, idx: IntExpr) -> JsonExpr:
|
|
156
|
+
return f"json_array_get({arr}, {idx})"
|
|
157
|
+
|
|
158
|
+
def obj_prop_val(self, obj: Var, prop: Expr, is_var: bool = False) -> JsonExpr:
|
|
159
|
+
return f"json_object_get({obj}, {prop})" if is_var else \
|
|
160
|
+
f"json_object_get({obj}, {self.esc(prop)})" # type: ignore
|
|
161
|
+
|
|
162
|
+
#
|
|
163
|
+
# inlined length computation
|
|
164
|
+
#
|
|
165
|
+
def obj_len(self, var: Var) -> IntExpr:
|
|
166
|
+
return f"json_object_size({var})"
|
|
167
|
+
|
|
168
|
+
def arr_len(self, var: Var) -> IntExpr:
|
|
169
|
+
return f"json_array_size({var})"
|
|
170
|
+
|
|
171
|
+
def str_len(self, var: Var) -> IntExpr:
|
|
172
|
+
return f"mbstowcs(NULL, {var}, 0)"
|
|
173
|
+
|
|
174
|
+
def any_len(self, var: Var) -> IntExpr:
|
|
175
|
+
return f"_any_len({var})"
|
|
176
|
+
|
|
177
|
+
#
|
|
178
|
+
# misc expressions
|
|
179
|
+
#
|
|
180
|
+
def assign_prop_fun(self, fun: str, prop: str, mapname: str) -> BoolExpr:
|
|
181
|
+
return f"({fun} = {mapname}({prop}))"
|
|
182
|
+
|
|
183
|
+
def str_start(self, val: str, start: str) -> BoolExpr:
|
|
184
|
+
return f"strncmp({val}, {self.esc(start)}, strlen({self.esc(start)})) == 0"
|
|
185
|
+
|
|
186
|
+
def str_end(self, val: str, end: str) -> BoolExpr:
|
|
187
|
+
sstr = self.esc(end)
|
|
188
|
+
return f"strlen({val}) >= strlen({sstr}) && " \
|
|
189
|
+
f"strcmp({val} + strlen({val}) - strlen({sstr}), {sstr}) == 0"
|
|
190
|
+
|
|
191
|
+
def check_call(self, name: str, val: Expr, path: Var, *,
|
|
192
|
+
is_ptr: bool = False, is_raw: bool = False) -> BoolExpr:
|
|
193
|
+
if is_raw:
|
|
194
|
+
return f"jm_check_fun_string({name}, {val}, {path}, rep)"
|
|
195
|
+
else:
|
|
196
|
+
return super().check_call(name, val, path, is_ptr=is_ptr, is_raw=is_raw) # type: ignore
|
|
197
|
+
|
|
198
|
+
def check_unique(self, val: JsonExpr, path: Var) -> BoolExpr:
|
|
199
|
+
return f"jm_array_is_unique({val}, {path}, rep)"
|
|
200
|
+
|
|
201
|
+
def check_constraint(self, op: str, vop: int|float|str, val: JsonExpr, path: Var) -> BoolExpr:
|
|
202
|
+
"""Call inefficient type-unaware constraint check."""
|
|
203
|
+
OPS = {
|
|
204
|
+
"!=": "op_ne", "=": "op_eq",
|
|
205
|
+
"<=": "op_le", "<": "op_lt",
|
|
206
|
+
">=": "op_ge", ">": "op_gt"
|
|
207
|
+
}
|
|
208
|
+
return f"jm_check_constraint({val}, {OPS[op]}, &{self._cst(vop)}, {path}, rep)"
|
|
209
|
+
|
|
210
|
+
#
|
|
211
|
+
# inline comparison expressions for strings
|
|
212
|
+
# this is locale-unaware
|
|
213
|
+
#
|
|
214
|
+
def str_cmp(self, e1: StrExpr, op: str, e2: StrExpr) -> BoolExpr:
|
|
215
|
+
assert op in ("=", "!=", "<", "<=", ">=", ">")
|
|
216
|
+
if op == "=":
|
|
217
|
+
return f"strcmp({e1}, {e2}) == 0"
|
|
218
|
+
elif op == "!=":
|
|
219
|
+
return f"strcmp({e1}, {e2}) != 0"
|
|
220
|
+
elif op == ">=":
|
|
221
|
+
return f"strcmp({e1}, {e2}) >= 0"
|
|
222
|
+
elif op == ">":
|
|
223
|
+
return f"strcmp({e1}, {e2}) > 0"
|
|
224
|
+
elif op == "<=":
|
|
225
|
+
return f"strcmp({e1}, {e2}) <= 0"
|
|
226
|
+
elif op == "<":
|
|
227
|
+
return f"strcmp({e1}, {e2}) < 0"
|
|
228
|
+
else:
|
|
229
|
+
raise Exception(f"str_cmp unexpected operator {op}")
|
|
230
|
+
|
|
231
|
+
#
|
|
232
|
+
# simple instructions
|
|
233
|
+
#
|
|
234
|
+
def nope(self) -> Block:
|
|
235
|
+
return []
|
|
236
|
+
|
|
237
|
+
def var(self, var: Var, val: Expr|None, tname: str|None) -> Block:
|
|
238
|
+
assign = f" = {val}" if val else ""
|
|
239
|
+
decl = f"{tname} " if tname else ""
|
|
240
|
+
return [ f"{decl}{var}{assign}{self._eoi}" ]
|
|
241
|
+
|
|
242
|
+
def int_var(self, var: Var, val: IntExpr|None = None, declare: bool = False) -> Block:
|
|
243
|
+
return self.var(var, val, self._int if declare else None)
|
|
244
|
+
|
|
245
|
+
#
|
|
246
|
+
# reporting
|
|
247
|
+
#
|
|
248
|
+
def is_reporting(self) -> BoolExpr:
|
|
249
|
+
return "rep != NULL"
|
|
250
|
+
|
|
251
|
+
def report(self, msg: str, path: Var) -> Block:
|
|
252
|
+
return ([ f"if (rep) jm_report_add_entry(rep, {self.esc(msg)}, {path});" ]
|
|
253
|
+
if self._with_report else [])
|
|
254
|
+
|
|
255
|
+
def clean_report(self) -> Block:
|
|
256
|
+
return [ "if (rep) jm_report_free_entries(rep);" ]
|
|
257
|
+
|
|
258
|
+
#
|
|
259
|
+
# path management
|
|
260
|
+
#
|
|
261
|
+
def path_val(self, pvar: Var, pseg: str|int, is_prop: bool) -> PathExpr:
|
|
262
|
+
# note: segment is a variable name for a prop or an integer
|
|
263
|
+
if self._with_path:
|
|
264
|
+
return (f"(jm_path_t) {{ {pseg}, 0, {pvar}, NULL }}" if is_prop else
|
|
265
|
+
f"(jm_path_t) {{ NULL, {pseg}, {pvar}, NULL }}")
|
|
266
|
+
else:
|
|
267
|
+
return "NULL"
|
|
268
|
+
|
|
269
|
+
def path_lvar(self, lvar: Var, rvar: Var) -> PathExpr:
|
|
270
|
+
return f"({rvar} ? &{lvar} : NULL)" if self._with_path else "NULL"
|
|
271
|
+
|
|
272
|
+
#
|
|
273
|
+
# blocks
|
|
274
|
+
#
|
|
275
|
+
def indent(self, block: Block, sep: bool = True) -> Block:
|
|
276
|
+
indented = super().indent(block, sep)
|
|
277
|
+
return ([ "{" ] + indented + [ "}" ]) if sep else indented
|
|
278
|
+
|
|
279
|
+
def arr_loop(self, arr: Var, idx: Var, val: Var, body: Block) -> Block:
|
|
280
|
+
return [
|
|
281
|
+
f"size_t {idx};",
|
|
282
|
+
f"json_t *{val};",
|
|
283
|
+
f"json_array_foreach({arr}, {idx}, {val})"
|
|
284
|
+
] + self.indent(body)
|
|
285
|
+
|
|
286
|
+
def obj_loop(self, obj: Var, key: Var, val: Var, body: Block) -> Block:
|
|
287
|
+
return [
|
|
288
|
+
f"const char *{key};",
|
|
289
|
+
f"json_t *{val};",
|
|
290
|
+
f"json_object_foreach((json_t *) {obj}, {key}, {val})"
|
|
291
|
+
] + self.indent(body)
|
|
292
|
+
|
|
293
|
+
def int_loop(self, idx: Var, start: IntExpr, end: IntExpr, body: Block) -> Block:
|
|
294
|
+
return [
|
|
295
|
+
f"for ({self._int} {idx} = {start}; {idx} < {end}; {idx}++)"
|
|
296
|
+
] + self.indent(body)
|
|
297
|
+
|
|
298
|
+
def if_stmt(self, cond: BoolExpr, true: Block, false: Block = []) -> Block:
|
|
299
|
+
if true and false:
|
|
300
|
+
return [ f"if ({cond})" ] + self.indent(true) + ["else"] + self.indent(false)
|
|
301
|
+
elif true:
|
|
302
|
+
return [ f"if ({cond})" ] + self.indent(true)
|
|
303
|
+
else:
|
|
304
|
+
return [ f"if (!({cond}))" ] + self.indent(false)
|
|
305
|
+
|
|
306
|
+
def mif_stmt(self, cond_true: list[tuple[BoolExpr, Block]], false: Block = []) -> Block:
|
|
307
|
+
code, op = [], "if"
|
|
308
|
+
for cond, true in cond_true:
|
|
309
|
+
code += [ f"{op} ({cond})" ]
|
|
310
|
+
code += self.indent(true)
|
|
311
|
+
op = "else if"
|
|
312
|
+
if false:
|
|
313
|
+
if op != "if":
|
|
314
|
+
code += [ "else" ]
|
|
315
|
+
code += self.indent(false)
|
|
316
|
+
else:
|
|
317
|
+
code += false
|
|
318
|
+
return code
|
|
319
|
+
|
|
320
|
+
#
|
|
321
|
+
# (Extended) Regular Expressions
|
|
322
|
+
#
|
|
323
|
+
def regroup(self, name: str, pattern: str = ".*") -> str:
|
|
324
|
+
return f"(?P<{name}>{pattern})" if self._relib == "re2" else super().regroup(name, pattern)
|
|
325
|
+
|
|
326
|
+
def def_re(self, name: str, regex: str, opts: str) -> Block:
|
|
327
|
+
if self._relib == "pcre2":
|
|
328
|
+
return [
|
|
329
|
+
f"static pcre2_code *{name}_code = NULL;",
|
|
330
|
+
f"static pcre2_match_data *{name}_data = NULL;",
|
|
331
|
+
f"static bool {name}(const char *s, jm_path_t *path, jm_report_t *rep);",
|
|
332
|
+
]
|
|
333
|
+
else:
|
|
334
|
+
return [
|
|
335
|
+
f"static cre2_regexp_t *{name}_re2 = NULL;",
|
|
336
|
+
f"static int {name}_nn = 0;",
|
|
337
|
+
f"static bool {name}(const char *s, jm_path_t *path, jm_report_t *rep);",
|
|
338
|
+
]
|
|
339
|
+
|
|
340
|
+
def sub_re(self, name: str, regex: str, opts: str) -> Block:
|
|
341
|
+
code = self.file_load(f"clang_{self._relib}_fun.c")
|
|
342
|
+
return [ c.replace("FUNCTION_NAME", name) for c in code ]
|
|
343
|
+
|
|
344
|
+
def ini_re(self, name: str, regex: str, opts: str) -> Block:
|
|
345
|
+
# declare once
|
|
346
|
+
code = [] if self._re_used or self._relib != "pcre2" else [
|
|
347
|
+
"int err_code;",
|
|
348
|
+
"PCRE2_SIZE err_offset;",
|
|
349
|
+
"static PCRE2_UCHAR err_message[1024];",
|
|
350
|
+
]
|
|
351
|
+
self._re_used = True
|
|
352
|
+
sregex = self.esc((f"(?{opts})" if opts else "") + regex)
|
|
353
|
+
if self._relib == "pcre2":
|
|
354
|
+
code += [
|
|
355
|
+
f"{name}_code = pcre2_compile((PCRE2_SPTR) {sregex},"
|
|
356
|
+
" PCRE2_ZERO_TERMINATED, PCRE2_UCP|PCRE2_UTF, &err_code, &err_offset, NULL);",
|
|
357
|
+
f"if ({name}_code == NULL)",
|
|
358
|
+
r"{",
|
|
359
|
+
r" (void) pcre2_get_error_message(err_code, err_message, 1024);",
|
|
360
|
+
r" return (const char *) err_message;",
|
|
361
|
+
r"}",
|
|
362
|
+
f"{name}_data = pcre2_match_data_create_from_pattern({name}_code, NULL);"
|
|
363
|
+
]
|
|
364
|
+
else:
|
|
365
|
+
code += [
|
|
366
|
+
f"{name}_re2 = cre2_new({sregex}, strlen({sregex}), NULL);",
|
|
367
|
+
f"if (cre2_error_code({name}_re2))",
|
|
368
|
+
f" return cre2_error_string({name}_re2);",
|
|
369
|
+
f"{name}_nn = cre2_num_capturing_groups({name}_re2) + 1;", # why?
|
|
370
|
+
]
|
|
371
|
+
return code
|
|
372
|
+
|
|
373
|
+
def del_re(self, name: str, regex: str, opts: str) -> Block:
|
|
374
|
+
if self._relib == "pcre2":
|
|
375
|
+
return [
|
|
376
|
+
f"pcre2_match_data_free({name}_data);",
|
|
377
|
+
f"pcre2_code_free({name}_code);",
|
|
378
|
+
]
|
|
379
|
+
else:
|
|
380
|
+
return [
|
|
381
|
+
f"cre2_delete({name}_re2);",
|
|
382
|
+
f"{name}_re2 = NULL;",
|
|
383
|
+
f"{name}_nn = 0;",
|
|
384
|
+
]
|
|
385
|
+
|
|
386
|
+
# TODO add rname
|
|
387
|
+
def match_str_var(self, rname: str, var: str, val: str, declare: bool = False) -> Block:
|
|
388
|
+
assert declare
|
|
389
|
+
if self._relib == "pcre2":
|
|
390
|
+
return [
|
|
391
|
+
f"const PCRE2_SIZE {var}_size = strlen({val});",
|
|
392
|
+
f"char {var}[{var}_size];",
|
|
393
|
+
f"PCRE2_SIZE {var}_len;",
|
|
394
|
+
r"int rc;"
|
|
395
|
+
]
|
|
396
|
+
else: # var is dname
|
|
397
|
+
return [
|
|
398
|
+
f"size_t {var}_size = strlen({val}) + 1;",
|
|
399
|
+
f"char {var}[{var}_size];",
|
|
400
|
+
r"int match_index;",
|
|
401
|
+
f"cre2_string_t matches[{rname}_nn];",
|
|
402
|
+
]
|
|
403
|
+
|
|
404
|
+
def match_re(self, name: str, var: str, regex: str, opts: str) -> BoolExpr:
|
|
405
|
+
if self._relib == "pcre2":
|
|
406
|
+
return f"pcre2_match({name}_code, (PCRE2_SPTR) {var}, PCRE2_ZERO_TERMINATED," \
|
|
407
|
+
f" 0, 0, {name}_data, NULL) != 0"
|
|
408
|
+
else:
|
|
409
|
+
return f"cre2_match({name}_re2, {var}, strlen({var}), 0, strlen({var}), " \
|
|
410
|
+
f"CRE2_UNANCHORED, matches, {name}_nn) != 0"
|
|
411
|
+
|
|
412
|
+
def match_val(self, mname: str, rname: str, sname: str, dname: str) -> Block:
|
|
413
|
+
if self._relib == "pcre2":
|
|
414
|
+
return [
|
|
415
|
+
f"{dname}_len = {dname}_size;",
|
|
416
|
+
f"rc = pcre2_substring_copy_byname({rname}_data, (PCRE2_SPTR) {self.esc(sname)}," \
|
|
417
|
+
f" (PCRE2_UCHAR *) {dname}, &{dname}_len);",
|
|
418
|
+
r"if (rc != 0)",
|
|
419
|
+
r" return false;",
|
|
420
|
+
]
|
|
421
|
+
else:
|
|
422
|
+
return [
|
|
423
|
+
f"match_index = cre2_find_named_capturing_groups({rname}_re2, {self.esc(sname)});",
|
|
424
|
+
f"strncpy({dname}, matches[match_index].data, matches[match_index].length);",
|
|
425
|
+
f"{dname}[matches[match_index].length] = '\\0';",
|
|
426
|
+
]
|
|
427
|
+
|
|
428
|
+
def def_strfun(self, name: str) -> Block:
|
|
429
|
+
return [ f"static bool {name}(const char *, jm_path_t *, jm_report_t *);" ]
|
|
430
|
+
|
|
431
|
+
def sub_strfun(self, name: str, body: Block) -> Block:
|
|
432
|
+
return [ f"static bool {name}(const char *val, jm_path_t *path, jm_report_t *rep)" ] + \
|
|
433
|
+
self.indent(body)
|
|
434
|
+
|
|
435
|
+
#
|
|
436
|
+
# Property Map
|
|
437
|
+
#
|
|
438
|
+
def def_pmap(self, name: str, pmap: PropMap, public: bool) -> Block:
|
|
439
|
+
code = [ f"{'' if public else 'static '}jm_propmap_t {name}_tab[{len(pmap)}];" ]
|
|
440
|
+
if public:
|
|
441
|
+
# add size accessor to public maps
|
|
442
|
+
code += [ f"const size_t {name}_size = {len(pmap)};" ]
|
|
443
|
+
return code
|
|
444
|
+
|
|
445
|
+
def ini_pmap(self, name: str, pmap: PropMap, public: bool) -> Block:
|
|
446
|
+
init = []
|
|
447
|
+
for i, (p, f) in enumerate(pmap.items()):
|
|
448
|
+
init += [ f"{name}_tab[{i}] = (jm_propmap_t) {{ {self.esc(p)}, {f} }};" ]
|
|
449
|
+
init += [ f"jm_sort_propmap({name}_tab, {len(pmap)});" ]
|
|
450
|
+
return init
|
|
451
|
+
|
|
452
|
+
def sub_pmap(self, name: str, pmap: PropMap, public: bool) -> Block:
|
|
453
|
+
return [
|
|
454
|
+
f"{'' if public else 'static '}jm_check_fun_t {name}(const char *pname)",
|
|
455
|
+
r"{",
|
|
456
|
+
f" return jm_search_propmap(pname, {name}_tab, {len(pmap)});",
|
|
457
|
+
r"}",
|
|
458
|
+
]
|
|
459
|
+
|
|
460
|
+
def def_cset(self, name: str, constants: ConstList) -> Block:
|
|
461
|
+
types = set(type(c) for c in constants)
|
|
462
|
+
code = []
|
|
463
|
+
if len(types) > 1:
|
|
464
|
+
code += [ f"static bool {name}_test(const json_t *);" ]
|
|
465
|
+
return code + [ f"static jm_constant_t {name}[{len(constants)}];" ]
|
|
466
|
+
|
|
467
|
+
def sub_cset(self, name: str, constants: ConstList) -> Block:
|
|
468
|
+
types = set(type(c) for c in constants)
|
|
469
|
+
code = []
|
|
470
|
+
if len(types) > 1:
|
|
471
|
+
code += [
|
|
472
|
+
f"static bool {name}_test(const json_t *val)",
|
|
473
|
+
r"{",
|
|
474
|
+
r" jm_constant_t cst;",
|
|
475
|
+
r" jm_set_cst(&cst, val);",
|
|
476
|
+
f" return jm_search_cst(&cst, {name}, {len(constants)});",
|
|
477
|
+
r"}"
|
|
478
|
+
]
|
|
479
|
+
return code
|
|
480
|
+
|
|
481
|
+
def _var_cst(self, var: Var, vtype: type|None) -> Expr:
|
|
482
|
+
if vtype is None or vtype is type(None):
|
|
483
|
+
return "(jm_constant_t) { cst_is_null, { .s = NULL } }"
|
|
484
|
+
elif vtype is bool:
|
|
485
|
+
return f"(jm_constant_t) {{ cst_is_bool, {{ .b = {self.value(var, bool)} }} }}"
|
|
486
|
+
elif vtype is int:
|
|
487
|
+
return f"(jm_constant_t) {{ cst_is_integer, {{ .i = {self.value(var, int)} }} }}"
|
|
488
|
+
elif vtype is float:
|
|
489
|
+
return f"(jm_constant_t) {{ cst_is_float, {{ .f = {self.value(var, float)} }} }}"
|
|
490
|
+
elif vtype is str:
|
|
491
|
+
return f"(jm_constant_t) {{ cst_is_string, {{ .s = {self.value(var, str)} }} }}"
|
|
492
|
+
else:
|
|
493
|
+
raise NotImplementedError(f"type {vtype}")
|
|
494
|
+
|
|
495
|
+
def in_cset(self, name: str, var: Var, constants: ConstList) -> BoolExpr:
|
|
496
|
+
"""Tell whether JSON variable var value of potential types is in set name."""
|
|
497
|
+
types = set(type(c) for c in constants)
|
|
498
|
+
if len(types) == 1:
|
|
499
|
+
tcs = types.pop()
|
|
500
|
+
val = self._var_cst(var, tcs)
|
|
501
|
+
return f"{self.is_a(var, tcs)} && jm_search_cst(&{val}, {name}, {len(constants)});"
|
|
502
|
+
else: # multi type managed in a generated function
|
|
503
|
+
return f"{name}_test({var})"
|
|
504
|
+
|
|
505
|
+
def _cst(self, value: Jsonable) -> str:
|
|
506
|
+
match value:
|
|
507
|
+
case None:
|
|
508
|
+
return "(jm_constant_t) { cst_is_null, { .s = NULL } }"
|
|
509
|
+
case bool(b):
|
|
510
|
+
return f"(jm_constant_t) {{ cst_is_bool, {{ .b = {self.const(b)} }} }}"
|
|
511
|
+
case int(i):
|
|
512
|
+
return f"(jm_constant_t) {{ cst_is_integer, {{ .i = {i} }} }}"
|
|
513
|
+
case float(f):
|
|
514
|
+
return f"(jm_constant_t) {{ cst_is_float, {{ .f = {f} }} }}"
|
|
515
|
+
case str(s):
|
|
516
|
+
return f"(jm_constant_t) {{ cst_is_string, {{ .s = {self.esc(s)} }} }}"
|
|
517
|
+
case _:
|
|
518
|
+
raise Exception(f"unexpected constant value: {value}")
|
|
519
|
+
|
|
520
|
+
def ini_cset(self, name: str, constants: ConstList) -> Block:
|
|
521
|
+
code = self.lcom(f"initialize sorted set {name}")
|
|
522
|
+
for i, cst in enumerate(constants):
|
|
523
|
+
code.append(f"{name}[{i}] = {self._cst(cst)};")
|
|
524
|
+
code.append(f"jm_sort_cst({name}, {len(constants)});")
|
|
525
|
+
return code
|
|
526
|
+
|
|
527
|
+
def _fun(self, name: str) -> str:
|
|
528
|
+
return f"static bool {name}(const json_t *val, jm_path_t *path, jm_report_t *rep)"
|
|
529
|
+
|
|
530
|
+
def def_fun(self, name: str) -> Block:
|
|
531
|
+
return [ self._fun(name) + ";" ]
|
|
532
|
+
|
|
533
|
+
def sub_fun(self, name: str, body: Block) -> Block:
|
|
534
|
+
return [ self._fun(name) ] + self.indent(body)
|
|
535
|
+
|
|
536
|
+
def def_cmap(self, name: str, mapping: dict[JsonScalar, str]) -> Block:
|
|
537
|
+
return [ f"static jm_constmap_t {name}_tab[{len(mapping)}];" ]
|
|
538
|
+
|
|
539
|
+
def sub_cmap(self, name: str, mapping: dict[JsonScalar, str]) -> Block:
|
|
540
|
+
return [
|
|
541
|
+
f"static jm_check_fun_t {name}(json_t *val)",
|
|
542
|
+
r"{",
|
|
543
|
+
r" jm_constant_t cst;",
|
|
544
|
+
r" jm_set_cst(&cst, val);",
|
|
545
|
+
f" return jm_search_constmap(&cst, {name}_tab, {len(mapping)});",
|
|
546
|
+
r"}",
|
|
547
|
+
]
|
|
548
|
+
|
|
549
|
+
def ini_cmap(self, name: str, mapping: dict[JsonScalar, str]) -> Block:
|
|
550
|
+
code = []
|
|
551
|
+
for i, (k, v) in enumerate(list(mapping.items())):
|
|
552
|
+
code += [ f"{name}_tab[{i}] = (jm_constmap_t) {{ {self._cst(k)}, {v} }};" ]
|
|
553
|
+
code += [ f"jm_sort_constmap({name}_tab, {len(mapping)});" ]
|
|
554
|
+
return code
|
|
555
|
+
|
|
556
|
+
def get_cmap(self, name: str, tag: Var, ttag: type) -> Expr:
|
|
557
|
+
return f"{name}({tag})"
|
|
558
|
+
|
|
559
|
+
def gen_init(self, init: Block) -> Block:
|
|
560
|
+
return self.file_subs("clang_init.c", ["jm_version_string = JSON_MODEL_VERSION;"] + init)
|
|
561
|
+
|
|
562
|
+
def gen_free(self, free: Block) -> Block:
|
|
563
|
+
return self.file_subs("clang_free.c", free)
|