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/language.py ADDED
@@ -0,0 +1,748 @@
1
+ import re
2
+ from importlib.resources import files as data_files
3
+ from .mtypes import Jsonable, JsonScalar, Number
4
+ from .utils import log, __version__
5
+
6
+ # name
7
+ type Var = str
8
+
9
+ # typed expressions
10
+ type JsonExpr = str
11
+ type BoolExpr = str|bool
12
+ type IntExpr = str|int
13
+ type FloatExpr = str
14
+ type NumExpr = str|int
15
+ type StrExpr = str
16
+ type PathExpr = Var|str
17
+ # all value expressions
18
+ type Expr = JsonExpr|BoolExpr|IntExpr|FloatExpr|NumExpr|StrExpr
19
+
20
+ # actual code
21
+ type Block = list[str]
22
+
23
+ # must or may property name -> corresponding check function
24
+ type PropMap = dict[str, str]
25
+ type ConstList = list[None|bool|int|float|str]
26
+ type ConstMap = dict[JsonScalar, str]
27
+ type RegMap = dict[str, str]
28
+
29
+ class Language:
30
+ """Dumb abstraction of an imperative language to manipulate JSON data.
31
+
32
+ TODO reduce #funcs, eg var/val with type parameter.
33
+ TODO move non generic methods to Python, to avoid generating python if unimplemented
34
+ """
35
+
36
+ def __init__(self,
37
+ name: str, *,
38
+ debug: bool = False,
39
+ # operators and separators
40
+ eq: str = "==", ne: str = "!=",
41
+ ge: str = ">=", gt: str = ">", le: str = "<=", lt: str = "<",
42
+ not_op: str = "not", and_op: str = "and", or_op: str = "or",
43
+ eoi: str = "", isep: str = "\n", indent: str = " ",
44
+ lcom: str = "#", relib: str = "re2",
45
+ true: str = "True", false: str = "False", null: str = "None",
46
+ check_t: str = "CheckFun", json_t: str = "Jsonable", path_t: str = "Path",
47
+ match_t: str|None = None,
48
+ float_t: str = "float", int_t: str = "int", bool_t: str = "bool", str_t: str = "str",
49
+ # options
50
+ with_path: bool = True, with_report: bool = True,
51
+ with_comment: bool = True, set_caps: tuple[type] = (str,),
52
+ ):
53
+
54
+ # parameter consistency
55
+ if with_path and not with_report:
56
+ log.warning("path collection but no reporting, removing path")
57
+ with_path = False
58
+
59
+ # keep parameters
60
+ self._name = name # language name
61
+ self._debug = debug
62
+ self._with_path = with_path and with_report
63
+ self._with_report = with_report
64
+ self._with_comment = with_comment
65
+
66
+ # comparison operators
67
+ self._eq = eq
68
+ self._ne = ne
69
+ self._ge = ge
70
+ self._gt = gt
71
+ self._le = le
72
+ self._lt = lt
73
+ # logical operators
74
+ self._not = not_op
75
+ self._and = and_op
76
+ self._or = or_op
77
+ # instructions and blocks
78
+ self._eoi = eoi
79
+ self._isep = isep
80
+ self._indent = indent
81
+ self._lcom = lcom
82
+ self._relib = relib
83
+ # constants
84
+ self._true = true
85
+ self._false = false
86
+ self._null = null
87
+ self._check_t = check_t
88
+ self._json_t = json_t
89
+ self._path_t = path_t
90
+ self._match_t = match_t
91
+ self._bool_t = bool_t
92
+ self._int_t = int_t
93
+ self._float_t = float_t
94
+ self._str_t = str_t
95
+
96
+ # other stuff
97
+ self._version = __version__
98
+ self._idcounts: dict[str, int] = {} # per-prefix ident count for unicity
99
+ self._re_used: bool = False # whether regular expressions are used
100
+ self.set_caps = tuple(set_caps) # constant types in a set
101
+
102
+ #
103
+ # variables
104
+ #
105
+ def ident(self, prefix: str) -> Var:
106
+ """Return a new identifier using prefix."""
107
+ if prefix not in self._idcounts:
108
+ self._idcounts[prefix] = 0
109
+ ident = prefix + "_" + str(self._idcounts[prefix])
110
+ self._idcounts[prefix] += 1
111
+ return ident
112
+
113
+ #
114
+ # SOURCE FILE MANAGEMENT
115
+ #
116
+ def file_load(self, fn: str) -> Block:
117
+ """Load a source file."""
118
+ code = data_files("json_model.data").joinpath(fn).read_text().split("\n")
119
+ # remove empty trailing lines
120
+ while code and re.match(r"^\s*$", code[-1]):
121
+ code = code[:-1]
122
+ return code
123
+
124
+ def file_subs(self, fname: str, block: Block) -> Block:
125
+ """Load a file with a code block substitution."""
126
+ code: Block = self.file_load(fname)
127
+ body = self.indent(self.indent(block, False), False)
128
+ bidx = code.index("CODE_BLOCK")
129
+ assert bidx >= 0, "CODE_BLOCK marker found in file"
130
+ code = code[:bidx] + body + code[bidx+1:]
131
+ return code
132
+
133
+ def file_header(self, exe: bool = True) -> Block:
134
+ """File header."""
135
+ return (
136
+ self.lcom() +
137
+ self.lcom(f"Generated by JSON Model Compiler version {self._version}") +
138
+ self.lcom("see https://github.com/clairey-zx81/json-model") +
139
+ self.lcom()
140
+ )
141
+
142
+ def file_footer(self, exe: bool = True) -> Block:
143
+ """File footer."""
144
+ return []
145
+
146
+ #
147
+ # type tests
148
+ #
149
+ def is_num(self, var: Var) -> BoolExpr:
150
+ """Is JSON variable a number?"""
151
+ raise NotImplementedError("is_num")
152
+
153
+ def is_def(self, var: Var) -> BoolExpr:
154
+ """Is JSON variable defined?"""
155
+ raise NotImplementedError("is_def")
156
+
157
+ def is_scalar(self, var: Var) -> BoolExpr:
158
+ """Is JSON variable a scalar?"""
159
+ raise NotImplementedError("is_scalar")
160
+
161
+ def is_a(self, var: Var, tval: type|None, loose: bool|None = None) -> BoolExpr:
162
+ """Is JSON variable of this type?"""
163
+ raise NotImplementedError("is_a")
164
+
165
+ #
166
+ # predefs
167
+ #
168
+ # FIXME loose vs strict
169
+ #
170
+ def predef(self, var: Var, name: str, path: Var, is_str: bool = False) -> BoolExpr:
171
+ """Compile a predef."""
172
+ # shortcut if the variable value is known to be a string
173
+ if is_str:
174
+ if name in { "$NULL", "$BOOL", "$BOOLEAN",
175
+ "$INT", "$INTEGER", "$I32", "$I64", "$U32", "$U64",
176
+ "$FLOAT", "$F32", "$F64", "$NUMBER" }:
177
+ name = "$NONE"
178
+ elif name == "$STRING":
179
+ name = "$ANY"
180
+ # else full type checks
181
+ if name == "$ANY":
182
+ return self.true()
183
+ elif name == "$NONE":
184
+ return self.false()
185
+ elif name == "$NULL":
186
+ return self.is_a(var, None)
187
+ elif name in ("$BOOL", "$BOOLEAN"):
188
+ return self.is_a(var, bool)
189
+ elif name in ("$INT", "$INTEGER", "$I32", "$I64"):
190
+ return self.is_a(var, int)
191
+ elif name in ("$U32", "$U64"):
192
+ return self.and_op(self.is_a(var, int),
193
+ self.num_cmp(self.value(var, int), ">=", self.const(0)))
194
+ elif name in ("$FLOAT", "$F32", "$F64"):
195
+ return self.is_a(var, float)
196
+ elif name == "$NUMBER":
197
+ return self.is_a(var, Number) # type: ignore
198
+ elif name == "$STRING":
199
+ return self.is_a(var, str)
200
+ elif name in ("$DATE", "$TIME", "$DATETIME", "$URL",
201
+ "$REGEX", "$EXREG", "$UUID", "$URI", "$EMAIL"):
202
+ raise NotImplementedError(f"predef: {name}")
203
+ else:
204
+ raise NotImplementedError(f"unexpected predef {name}")
205
+
206
+ #
207
+ # constants
208
+ #
209
+ def const(self, c: Jsonable) -> Expr:
210
+ """Build a constant expression for a value."""
211
+ if c is None:
212
+ return self._null
213
+ elif isinstance(c, bool):
214
+ return self._true if c else self._false
215
+ elif isinstance(c, str):
216
+ return self.esc(c)
217
+ else:
218
+ return str(c)
219
+
220
+ def true(self) -> BoolExpr:
221
+ return self.const(True) # pyright: ignore
222
+
223
+ def false(self) -> BoolExpr:
224
+ return self.const(False) # pyright: ignore
225
+
226
+ #
227
+ # inline json scalar value extraction
228
+ #
229
+ def value(self, var: Var, tvar: type) -> Expr:
230
+ """Extract a type from JSON var."""
231
+ if tvar in (bool, int, float, Number, str):
232
+ return var
233
+ else:
234
+ raise Exception(f"unexpected type for value extraction: {tvar.__name__}")
235
+
236
+ def arr_item_val(self, arr: Var, idx: IntExpr) -> JsonExpr:
237
+ """Get array item for an index."""
238
+ return f"{arr}[{idx}]"
239
+
240
+ def obj_prop_val(self, obj: Var, prop: Var, is_var: bool = False) -> JsonExpr:
241
+ """Get object property value."""
242
+ raise NotImplementedError("obj_prop_val")
243
+
244
+ def has_prop(self, obj: Var, prop: str) -> BoolExpr:
245
+ """Tell whether an object as a property."""
246
+ raise NotImplementedError("has_prop")
247
+
248
+ #
249
+ # inlined length computation
250
+ #
251
+ def any_len(self, var: Var) -> IntExpr:
252
+ """Get length of variable."""
253
+ raise NotImplementedError("any_len")
254
+
255
+ def obj_len(self, var: Var) -> IntExpr:
256
+ """Get number of properties of an object."""
257
+ return self.any_len(var)
258
+
259
+ def arr_len(self, var: Var) -> IntExpr:
260
+ """Get number of items of an array."""
261
+ return self.any_len(var)
262
+
263
+ def str_len(self, var: Var) -> IntExpr:
264
+ """Get length of a string."""
265
+ return self.any_len(var)
266
+
267
+ def str_start(self, val: str, start: str) -> BoolExpr:
268
+ raise NotImplementedError("str_start")
269
+
270
+ def str_end(self, val: str, end: str) -> BoolExpr:
271
+ raise NotImplementedError("str_end")
272
+
273
+ def any_int_val(self, val: JsonExpr, tval: type) -> IntExpr:
274
+ """Known type int extraction for constraints."""
275
+ if tval is int:
276
+ return self.value(val, int)
277
+ elif tval is str:
278
+ return self.str_len(self.value(val, str)) # type: ignore
279
+ elif tval is list:
280
+ return self.arr_len(val)
281
+ elif tval is dict:
282
+ return self.obj_len(val)
283
+ else:
284
+ raise Exception(f"unexpected type for any_int_val: {tval.__name__}")
285
+
286
+ #
287
+ # boolean expression
288
+ #
289
+ def str_check_call(self, name: str, val: StrExpr, path: Var) -> BoolExpr:
290
+ """Model check call for a string value."""
291
+ return f"{name}({val}, {path}, rep)"
292
+
293
+ def check_call(self, name: Var, val: JsonExpr, path: Var, *,
294
+ is_ptr: bool = False, is_raw: bool = False) -> BoolExpr:
295
+ """Model check call for a JSON value.
296
+
297
+ is_ptr: the name is a function pointer, not a direct function
298
+ is_raw: value is a raw (string) value, not a json
299
+ """
300
+ return f"{name}({val}, {path}, rep)"
301
+
302
+ def check_unique(self, val: JsonExpr, path: Var) -> BoolExpr:
303
+ """Check uniqueness."""
304
+ raise NotImplementedError("check_unique")
305
+
306
+ def check_constraint(self, op: str, vop: int|float|str, val: JsonExpr, path: Var) -> BoolExpr:
307
+ """Check constraint."""
308
+ raise NotImplementedError("check_constraint")
309
+
310
+ #
311
+ # logical expressions
312
+ #
313
+ def not_op(self, e: BoolExpr) -> BoolExpr:
314
+ """Not logical operator."""
315
+ e = self.paren(e) if "=" in e or self._and in e or self._or in e else e # type: ignore
316
+ return f"{self._not} {e}"
317
+
318
+ def and_op(self, *exprs: BoolExpr) -> BoolExpr:
319
+ """And logical operator."""
320
+ return f" {self._and} ".join(self.paren(e) if self._or in e else e # type: ignore
321
+ for e in exprs)
322
+
323
+ def or_op(self, *exprs: BoolExpr) -> BoolExpr:
324
+ """Or logical operator."""
325
+ return f" {self._or} ".join(exprs) # type: ignore
326
+
327
+ def paren(self, e: Expr) -> Expr:
328
+ """Parenthesize an expression."""
329
+ return f"({e})"
330
+
331
+ #
332
+ # inline comparison expressions for numbers
333
+ #
334
+ def num_cmp(self, e1: NumExpr, op: str, e2: NumExpr) -> BoolExpr:
335
+ """Numerical comparison."""
336
+ assert op in ("=", "!=", "<", "<=", ">=", ">")
337
+ if op == "=":
338
+ return f"{e1} {self._eq} {e2}"
339
+ elif op == "!=":
340
+ return f"{e1} {self._ne} {e2}"
341
+ elif op == "<":
342
+ return f"{e1} {self._lt} {e2}"
343
+ elif op == "<=":
344
+ return f"{e1} {self._le} {e2}"
345
+ elif op == ">=":
346
+ return f"{e1} {self._ge} {e2}"
347
+ elif op == ">":
348
+ return f"{e1} {self._gt} {e2}"
349
+ else:
350
+ raise Exception(f"num_cmp unexpected op {op}")
351
+
352
+ #
353
+ # inline comparison expressions for strings
354
+ #
355
+ def str_cmp(self, e1: StrExpr, op: str, e2: StrExpr) -> BoolExpr:
356
+ """String comparison."""
357
+ return self.num_cmp(e1, op, e2)
358
+
359
+ def assign_expr(self) -> bool:
360
+ """Whether there is an assign expression in the language."""
361
+ return True
362
+
363
+ def assign_prop_fun(self, fun: str, prop: str, mapname: str) -> BoolExpr:
364
+ """Get check value fonction for a property and tell whether it got one."""
365
+ raise NotImplementedError("prop_fun with assign expression")
366
+
367
+ def has_prop_fun(self, prop: str, mapname: str) -> BoolExpr:
368
+ """Whether property has a check function in the map."""
369
+ raise NotImplementedError("has_prop_fun")
370
+
371
+ def get_prop_fun(self, prop: str, mapname: str) -> Expr:
372
+ """get check function for property."""
373
+ raise NotImplementedError("has_prop_fun")
374
+
375
+ #
376
+ # for JSON values
377
+ #
378
+ def json_eq(self, e1: Expr, e2: Expr) -> BoolExpr:
379
+ """Compare JSON values."""
380
+ return f"{e1} {self._eq} {e2}"
381
+
382
+ def json_ne(self, e1: Expr, e2: Expr) -> BoolExpr:
383
+ """Compare JSON values."""
384
+ return f"{e1} {self._ne} {e2}"
385
+
386
+ #
387
+ # simple instructions
388
+ #
389
+ def nope(self) -> Block:
390
+ """Do nothing."""
391
+ raise NotImplementedError("var")
392
+
393
+ def lcom(self, text: str = "") -> Block:
394
+ """Generate a line comment."""
395
+ if self._with_comment:
396
+ return [ f"{self._lcom} {text}" if text else self._lcom ]
397
+ else:
398
+ return []
399
+
400
+ def var(self, var: Var, val: Expr|None, tname: str|None) -> Block:
401
+ """Declare and/or assign a variable with a type."""
402
+ raise NotImplementedError("var")
403
+
404
+ def json_var(self, var: Var, val: JsonExpr|None = None, declare: bool = False) -> Block:
405
+ """Declare a JSON variable."""
406
+ return self.var(var, val, self._json_t if declare else None)
407
+
408
+ def bool_var(self, var: Var, val: BoolExpr|None = None, declare: bool = False) -> Block:
409
+ """Declare a boolean variable."""
410
+ return self.var(var, val, self._bool_t if declare else None)
411
+
412
+ def int_var(self, var: Var, val: IntExpr|None = None, declare: bool = False) -> Block:
413
+ """Declare and assign to int variable."""
414
+ return self.var(var, val, self._int_t if declare else None)
415
+
416
+ def str_var(self, var: Var, val: IntExpr|None = None, declare: bool = False) -> Block:
417
+ """Declare and assign to str variable."""
418
+ return self.var(var, val, self._str_t if declare else None)
419
+
420
+ def flt_var(self, var: Var, val: IntExpr|None = None, declare: bool = False) -> Block:
421
+ """Declare and assign to str variable."""
422
+ return self.var(var, val, self._float_t if declare else None)
423
+
424
+ def fun_var(self, var: Var, val: Expr|None = None, declare: bool = False) -> Block:
425
+ """Declare a check function variable pointer."""
426
+ # FIXME should guard for scalar?
427
+ return self.var(var, val, self._check_t if declare else None)
428
+
429
+ def path_var(self, pvar: Var, val: PathExpr|None = None, declare: bool = False) -> Block:
430
+ """Assign and possibly declare a value to a path variable."""
431
+ return self.var(pvar, val, self._path_t if declare else None) if self._with_path else []
432
+
433
+ def match_var(self, var: Var, val: Expr|None = None, declare: bool = False) -> Block:
434
+ """Assign and possibly declare a match result variable."""
435
+ return self.var(var, val, self._match_t if declare else None)
436
+
437
+ def match_ko(self, var: Var) -> BoolExpr:
438
+ return self.not_op(var)
439
+
440
+ def match_str_var(self, rname: str, var: str, val: str, declare: bool = False) -> Block:
441
+ """Declare a variable for a matching result extracted from val."""
442
+ # the value is just as a length helper
443
+ return self.str_var(var, None, declare)
444
+
445
+ def iand_op(self, res: Var, e: BoolExpr) -> Block:
446
+ """And-update boolean variable."""
447
+ return [ "{var} &= {e}{self.eoi}" ]
448
+
449
+ def inc_var(self, var: Var) -> Block:
450
+ """Increment integer variable."""
451
+ return [ f"{var} += 1{self._eoi}" ]
452
+
453
+ def ret(self, res: BoolExpr) -> Block:
454
+ """Return boolean result."""
455
+ return [ f"return {res}{self._eoi}" ]
456
+
457
+ def brk(self) -> Block:
458
+ """Break from surrounding loop."""
459
+ return [ f"break{self._eoi}" ]
460
+
461
+ def esc(self, s: str) -> StrExpr:
462
+ """Escape string, with double quotes."""
463
+ return '"' + s.replace("\\", "\\\\").replace('"', r'\"') + '"'
464
+
465
+ #
466
+ # paths:
467
+ #
468
+ # fun(path: Path)
469
+ # lpath: Path = path + [ segment ] # if path is not None, else None !
470
+ # checker(val, lpath, ...)
471
+ #
472
+ # fun(Path* path)
473
+ # Path lpath = (Path) { ..., path }
474
+ # checker(val, path ? &lpath : NULL, ...)
475
+ #
476
+ # TODO consider merging path_var and path_val?
477
+ #
478
+ def path_val(self, pvar: Var, pseg: str|int, is_prop: bool) -> PathExpr:
479
+ """Append a segment variable/value to path."""
480
+ raise NotImplementedError("see derived classes")
481
+
482
+ def path_lvar(self, lvar: Var, rvar: Var) -> PathExpr:
483
+ # avoid nested if expressions
484
+ raise NotImplementedError("see derived classes")
485
+
486
+ #
487
+ # blocks
488
+ #
489
+ def is_reporting(self) -> BoolExpr:
490
+ """Test whether run is generating a report."""
491
+ raise NotImplementedError("see derived classes")
492
+
493
+ def report(self, msg: str, path: Var) -> Block:
494
+ """Add a a report entry."""
495
+ raise NotImplementedError("see derived classes")
496
+
497
+ def clean_report(self) -> Block:
498
+ raise NotImplementedError("see derived classes")
499
+
500
+ def indent(self, block: Block, sep: bool = True) -> Block:
501
+ """Indent a block."""
502
+ return [ (self._indent + line) for line in filter(lambda s: s is not None, block) ]
503
+
504
+ def int_loop(self, idx: Var, start: IntExpr, end: IntExpr, body: Block) -> Block:
505
+ """Loop over integers from start to end (excluded)."""
506
+ raise NotImplementedError("int_loop")
507
+
508
+ def arr_loop(self, arr: Var, idx: Var, val: Var, body: Block) -> Block:
509
+ """Loop over all items of an array."""
510
+ raise NotImplementedError("arr_loop")
511
+
512
+ def obj_loop(self, obj: Var, key: Var, val: Var, body: Block) -> Block:
513
+ """Loop over all property-values pairs of an object."""
514
+ raise NotImplementedError("obj_loop")
515
+
516
+ def if_stmt(self, cond: BoolExpr, true: Block, false: Block = []) -> Block:
517
+ """Generate a if-then[-else] statement."""
518
+ raise NotImplementedError("if_stmt")
519
+
520
+ def mif_stmt(self, cond_true: list[tuple[BoolExpr, Block]], false: Block = []) -> Block:
521
+ """Generate a multi-if[-else] statement."""
522
+ raise NotImplementedError("mif_stmt")
523
+
524
+ #
525
+ # PROPERTY MAPPING : property value (constant string) to check function
526
+ #
527
+ def def_pmap(self, name: str, pmap: PropMap, public: bool) -> Block:
528
+ """Define a new (property) map."""
529
+ return []
530
+
531
+ def sub_pmap(self, name: str, pmap: PropMap, public: bool) -> Block:
532
+ """Generate a subroutine for the property map."""
533
+ return []
534
+
535
+ def ini_pmap(self, name: str, pmap: PropMap, public: bool) -> Block:
536
+ """Initialize a map."""
537
+ return []
538
+
539
+ def del_pmap(self, name: str, pmap: PropMap, public: bool) -> Block:
540
+ """Remove initial stuff for a property map."""
541
+ return []
542
+
543
+ #
544
+ # CONSTANT SET FOR ENUM OPTIMIZATION
545
+ #
546
+ def def_cset(self, name: str, constants: ConstList) -> Block:
547
+ """Declare a constant set."""
548
+ return []
549
+
550
+ def ini_cset(self, name: str, constants: ConstList) -> Block:
551
+ """Initialize a constant set with constants."""
552
+ return []
553
+
554
+ def in_cset(self, name: str, var: Var, constants: ConstList) -> BoolExpr:
555
+ """Test whether variable value belongs to constant set."""
556
+ raise NotImplementedError("see derived classes")
557
+
558
+ def del_cset(self, name: str, constants: ConstList) -> Block:
559
+ """Remove stuff for constant set."""
560
+ return []
561
+
562
+ def sub_cset(self, name: str, constants: ConstList) -> Block:
563
+ """Generate support function for constant set check."""
564
+ return []
565
+
566
+ #
567
+ # CHECK FUNCTION SIGNATURE
568
+ #
569
+ def def_fun(self, name: str) -> Block:
570
+ """Define a function."""
571
+ return []
572
+
573
+ def sub_fun(self, name: str, body: Block) -> Block:
574
+ """Generate a check function."""
575
+ raise NotImplementedError("see derived classes")
576
+
577
+ def def_strfun(self, name: str) -> Block:
578
+ """Define a string check function."""
579
+ return []
580
+
581
+ def sub_strfun(self, name: str, body: Block) -> Block:
582
+ raise NotImplementedError("see derived classes")
583
+
584
+ #
585
+ # REGULAR EXPRESSION PRECOMPILATION
586
+ #
587
+ def regroup(self, name: str, pattern: str = ".*") -> str:
588
+ """Name a group in a regular expression."""
589
+ return f"(?<{name}>{pattern})"
590
+
591
+ def sub_re(self, name: str, regex: str, opts: str) -> Block:
592
+ """Generate a regex check function."""
593
+ return []
594
+
595
+ def def_re(self, name: str, regex: str, opts: str) -> Block:
596
+ """Define a new (static) regex."""
597
+ return []
598
+
599
+ def ini_re(self, name: str, regex: str, opts: str) -> Block:
600
+ """Initialize a regex."""
601
+ return []
602
+
603
+ def del_re(self, name: str, regex: str, opts: str) -> Block:
604
+ """Free a regex."""
605
+ return []
606
+
607
+ def match_re(self, name: str, var: str, regex: str, opts: str) -> BoolExpr:
608
+ """Get a match result for string variable var value."""
609
+ raise NotImplementedError("see derived classes")
610
+
611
+ def match_val(self, mname: str, rname: str, sname: str, dname: str) -> Block:
612
+ """Assign match "name" to variable sname."""
613
+ raise NotImplementedError("see derived classes")
614
+
615
+ #
616
+ # CONSTANT MAPPING FOR DISCRIMINANT OPTIMIZATION
617
+ # constant value to check function
618
+ #
619
+ def _str_map(self, mapping: dict[JsonScalar, str]) -> bool:
620
+ return all(isinstance(k, str) for k in mapping.keys())
621
+
622
+ def get_cmap(self, name: str, tag: Var, ttag: type) -> Expr:
623
+ """Return the function associated to the tag value if any."""
624
+ raise NotImplementedError("see derived classes")
625
+
626
+ def def_cmap(self, name: str, mapping: dict[JsonScalar, str]) -> Block:
627
+ """Declare a new constant map."""
628
+ return []
629
+
630
+ def ini_cmap(self, name: str, mapping: dict[JsonScalar, str]) -> Block:
631
+ """Initialize constant mapping."""
632
+ return []
633
+
634
+ def sub_cmap(self, name: str, mapping: dict[JsonScalar, str]) -> Block:
635
+ """Generate support function for mapping."""
636
+ return []
637
+
638
+ def del_cmap(self, name: str, mapping: dict[JsonScalar, str]) -> Block:
639
+ """Remove stuff for mapping."""
640
+ return []
641
+
642
+ #
643
+ # FUNCTIONS
644
+ #
645
+ def gen_init(self, init: Block) -> Block:
646
+ """Generate the initialization function."""
647
+ raise NotImplementedError("gen_init")
648
+
649
+ def gen_free(self, free: Block) -> Block:
650
+ """Generate the deallocation function."""
651
+ raise NotImplementedError("gen_free")
652
+
653
+
654
+ class Code:
655
+ """Hold generated source code for a .
656
+
657
+ - `language`: language generator
658
+ - `entry`: name of the entry function
659
+ """
660
+
661
+ def __init__(self, lang: Language, entry: str = "check_model", executable: bool = True):
662
+ self._lang = lang # generated language abstraction
663
+ self._entry = entry # entry function name/prefix
664
+ self._executable = executable # executable (shebang, main) vs module
665
+ self._defs: Block = [] # definitions and declarations
666
+ self._inis: Block = [] # initialization code
667
+ self._dels: Block = [] # deallocation code
668
+ self._subs: Block = [] # actual subroutines
669
+
670
+ #
671
+ # add blocks
672
+ #
673
+ def defs(self, b: Block = [""]):
674
+ """Add lines to definitions."""
675
+ self._defs += b
676
+
677
+ def subs(self, b: Block = [""]):
678
+ """Add lines to subroutines."""
679
+ if self._subs:
680
+ self._subs.append("")
681
+ self._subs += b
682
+
683
+ def inis(self, b: Block = [""]):
684
+ """Add lines to initialization code."""
685
+ self._inis += b
686
+
687
+ def dels(self, b: Block = [""]):
688
+ """Add lines to cleanup code."""
689
+ self._dels += b
690
+
691
+ # TODO rename!
692
+ def sub(self, name: str, body: Block, *, comment: str = ""):
693
+ """Add a function definition with a comment."""
694
+ self.defs(self._lang.def_fun(name))
695
+ fun = self._lang.lcom(comment) if comment else []
696
+ fun += self._lang.sub_fun(name, body)
697
+ self.subs(fun)
698
+
699
+ def pmap(self, name: str, mapping: PropMap, public: bool = False):
700
+ """Add a (property/name) mapping."""
701
+ self.defs(self._lang.def_pmap(name, mapping, public))
702
+ self.inis(self._lang.ini_pmap(name, mapping, public))
703
+ self.dels(self._lang.del_pmap(name, mapping, public))
704
+ self.subs(self._lang.sub_pmap(name, mapping, public))
705
+
706
+ def cset(self, name: str, constants: ConstList):
707
+ """Add a constant set."""
708
+ self.defs(self._lang.def_cset(name, constants))
709
+ self.inis(self._lang.ini_cset(name, constants))
710
+ self.dels(self._lang.del_cset(name, constants))
711
+ self.subs(self._lang.sub_cset(name, constants))
712
+
713
+ def cmap(self, name: str, mapping: ConstMap):
714
+ """Add a constant value mapping."""
715
+ self.defs(self._lang.def_cmap(name, mapping))
716
+ self.inis(self._lang.ini_cmap(name, mapping))
717
+ self.dels(self._lang.del_cmap(name, mapping))
718
+ self.subs(self._lang.sub_cmap(name, mapping))
719
+
720
+ def regex(self, name: str, regex: str, opts: str):
721
+ """Add a regex."""
722
+ self.defs(self._lang.def_re(name, regex, opts))
723
+ self.inis(self._lang.ini_re(name, regex, opts))
724
+ self.dels(self._lang.del_re(name, regex, opts))
725
+ self.subs(self._lang.sub_re(name, regex, opts))
726
+
727
+ def strfun(self, name: str, body: Block):
728
+ self.defs(self._lang.def_strfun(name))
729
+ self.subs(self._lang.sub_strfun(name, body))
730
+
731
+ def __str__(self):
732
+ """Gather everything to generate the full source code."""
733
+
734
+ # compute init first as predefs may trigger more imports
735
+ inis = self._lang.gen_init(self._inis)
736
+ dels = self._lang.gen_free(self._dels)
737
+
738
+ # reduce with empty lines between parts
739
+ code: Block = []
740
+ for block in (self._lang.file_header(self._executable), self._defs,
741
+ self._subs, inis, dels, self._lang.file_footer(self._executable)):
742
+ if code and block:
743
+ code += [""]
744
+ code += [ line.replace("CHECK_FUNCTION_NAME", self._entry)
745
+ for line in block ]
746
+
747
+ # generate source code, skipping none instructions if any
748
+ return self._lang._isep.join(filter(lambda s: s is not None, code)) + "\n"