jumbl 0.2.1.dev1__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.
jumbl/_fstring.py ADDED
@@ -0,0 +1,238 @@
1
+ # jumbl/_fstring.py
2
+ import re
3
+ from typing import Dict, Any, Optional
4
+
5
+ from ._utils import unquote
6
+ from ._eval import safe_eval
7
+
8
+ # ────────────────────────────────────────────────────────────────────────────
9
+ # Helpers
10
+ # ────────────────────────────────────────────────────────────────────────────
11
+
12
+ from collections.abc import Mapping # NEW import ⬅️
13
+
14
+ _VAR_RE = re.compile(r"([@%\$])?\{([^}]+)\}")
15
+
16
+
17
+ def _lookup(path: str, *envs: Optional[Dict[str, Any]]) -> Optional[Any]:
18
+ print(f"[DEBUG _fstring._lookup] path {path}")
19
+ """
20
+ Walk the dotted *path* (e.g. ``"a.b.c"``) through each mapping / object
21
+ supplied in *envs*, returning the first successful hit.
22
+
23
+ • Works with plain dicts, pydantic models, dataclass instances, etc.
24
+ • If the current object on the walk implements ``evaluate()``, that is
25
+ called so nested AST nodes or inline-table nodes unwrap cleanly.
26
+ """
27
+ parts = path.split(".")
28
+
29
+ def _dig(cur: Any, key: str) -> Any:
30
+ # Unwrap AST-style nodes
31
+ if hasattr(cur, "evaluate"):
32
+ try:
33
+ cur = cur.evaluate()
34
+ except Exception:
35
+ pass
36
+
37
+ # Mapping lookup
38
+ if isinstance(cur, Mapping) and key in cur:
39
+ return cur[key]
40
+
41
+ # Attribute lookup
42
+ if hasattr(cur, key):
43
+ return getattr(cur, key)
44
+
45
+ return None
46
+
47
+ for env in envs:
48
+ if env is None:
49
+ continue
50
+
51
+ cur: Any = env
52
+ for part in parts:
53
+ cur = _dig(cur, part)
54
+ if cur is None:
55
+ break # this env failed, try the next one
56
+ else:
57
+ # completed the for-loop ⇒ success
58
+ return cur
59
+
60
+ return None
61
+
62
+
63
+ # utils.py
64
+
65
+
66
+ # ─────────────────────────────────────────────────────────────────────────────
67
+ # ① expand global- and local-scope f-strings
68
+ def _eval_fstrings(mapping: Dict[str, Any], global_data=None):
69
+ if global_data is None:
70
+ global_data = mapping
71
+ for key, val in list(mapping.items()):
72
+ if isinstance(val, str) and (
73
+ val.startswith('f"') or val.startswith("f'")
74
+ ):
75
+ # Skip context-scoped placeholders (${…}), only expand static
76
+ # f-strings
77
+ if "${" not in val:
78
+ mapping[key] = _evaluate_f_string(
79
+ val,
80
+ global_data=global_data,
81
+ local_data=mapping,
82
+ context={},
83
+ )
84
+ elif isinstance(val, dict):
85
+ _eval_fstrings(val, global_data)
86
+
87
+
88
+ # ────────────────────────────────────────────────────────────────────────────
89
+ # Public entry‑point
90
+ # ────────────────────────────────────────────────────────────────────────────
91
+
92
+
93
+ def _evaluate_f_string(
94
+ f_str: str,
95
+ global_data: Dict,
96
+ local_data: Dict,
97
+ context: Optional[Dict] = None,
98
+ ) -> str:
99
+ """
100
+ Expand JAM‑style f‑strings.
101
+
102
+ Marker semantics
103
+ ────────────────
104
+ • ``@{var}`` → search *only* the global/root mapping
105
+ • ``%{var}`` → start at *local_data* (section scope), fall back to
106
+ *global_data*
107
+ • ``{expr}`` → same lookup as ``%{}``; if unresolved, try
108
+ ``safe_eval(expr)``
109
+ • ``${var}`` → search the caller‑supplied *context*, then local, then
110
+ global
111
+
112
+ Unresolved placeholders are returned verbatim so round‑trip fidelity is
113
+ preserved.
114
+ """
115
+ print("[DEBUG _fstring._evaluate_f_string] Original f-string:", f_str)
116
+
117
+ # Must begin with f"… or f'…
118
+ if not (f_str.startswith('f"') or f_str.startswith("f'")):
119
+ print(
120
+ (
121
+ "[DEBUG _fstring._evaluate_f_string] Not an f-string; "
122
+ "returning as‑is."
123
+ )
124
+ )
125
+ return f_str
126
+
127
+ # Strip leading f and its surrounding quotes
128
+ inner = f_str[1:].lstrip()
129
+ if inner:
130
+ quote_char = inner[0]
131
+ inner = inner[1:-1] if inner.endswith(quote_char) else inner[1:]
132
+ print(
133
+ (
134
+ "[DEBUG _fstring._evaluate_f_string] After removing f prefix and"
135
+ " quotes, inner:"
136
+ ),
137
+ inner,
138
+ )
139
+
140
+ # ───────────────────────────────────────────────────────── placeholder
141
+ # pass
142
+ def repl(match: "re.Match[str]") -> str:
143
+ scope_marker, content = match.groups()
144
+ content = content.strip()
145
+ print(
146
+ "[DEBUG _fstring._evaluate_f_string] Processing content:",
147
+ content,
148
+ "marker:",
149
+ scope_marker,
150
+ )
151
+
152
+ # ${...} → context‑scoped (render‑time)
153
+ if scope_marker == "$":
154
+ # If no context was supplied (e.g. during resolve‑time) leave it
155
+ # untouched so it can be handled later.
156
+ if context is None:
157
+ return match.group(0)
158
+
159
+ value = _lookup(content, context, local_data, global_data)
160
+ if value is None:
161
+ print(
162
+ (
163
+ "[DEBUG _fstring._evaluate_f_string] Context lookup "
164
+ "failed for"
165
+ ),
166
+ content,
167
+ )
168
+ return match.group(0)
169
+
170
+ if hasattr(value, "value"):
171
+ return unquote(value.value)
172
+ if isinstance(value, str):
173
+ return unquote(value)
174
+ return str(value)
175
+
176
+ # Determine lookup order for @{…}, %{…}, and bare {…}
177
+ if scope_marker == "@": # global‑only
178
+ value = _lookup(content, global_data)
179
+ else: # '%' or bare
180
+ value = _lookup(content, local_data, global_data)
181
+
182
+ # For bare {expr} try evaluating an expression if lookup failed
183
+ if value is None and scope_marker not in ("@", "%"):
184
+ try:
185
+ value = safe_eval(content, local_env=local_data)
186
+ print(
187
+ (
188
+ "[DEBUG _fstring._evaluate_f_string] Evaluated "
189
+ "expression:"
190
+ ),
191
+ content,
192
+ "to:",
193
+ value,
194
+ )
195
+ except Exception as exc:
196
+ print(
197
+ (
198
+ "[DEBUG _fstring._evaluate_f_string] Expression "
199
+ "evaluation failed:"
200
+ ),
201
+ exc,
202
+ )
203
+ return match.group(0)
204
+
205
+ if value is None:
206
+ print(
207
+ "[DEBUG _fstring._evaluate_f_string] Content unresolved:",
208
+ match.group(0),
209
+ )
210
+ return match.group(0)
211
+
212
+ # Collapse AST nodes or quoted literals
213
+ if hasattr(value, "value"):
214
+ return unquote(value.value)
215
+ if isinstance(value, str):
216
+ return unquote(value)
217
+ return str(value)
218
+
219
+ substituted = _VAR_RE.sub(repl, inner)
220
+ print(
221
+ "[DEBUG _fstring._evaluate_f_string] After substitution:", substituted
222
+ )
223
+
224
+ # If the whole string now looks like a simple literal/expression, eval it
225
+ if re.fullmatch(
226
+ r"[\d\s+\-*/().]+|true|false|null", substituted, flags=re.I
227
+ ):
228
+ try:
229
+ evaluated = safe_eval(substituted, local_env=local_data)
230
+ print(
231
+ "[DEBUG _fstring._evaluate_f_string] safe_eval result:",
232
+ evaluated,
233
+ )
234
+ return str(evaluated)
235
+ except Exception as exc:
236
+ print("[DEBUG _fstring._evaluate_f_string] safe_eval failed:", exc)
237
+
238
+ return substituted
jumbl/_lark_parser.py ADDED
@@ -0,0 +1,12 @@
1
+ from importlib.resources import files
2
+ from lark import Lark
3
+ import jumbl
4
+
5
+ # Read the grammar file from the package.
6
+ grammar = files(jumbl).joinpath("grammar.lark").read_text()
7
+ parser = Lark(
8
+ grammar,
9
+ parser="earley",
10
+ lexer="dynamic_complete",
11
+ propagate_positions=True,
12
+ )
jumbl/_legacy.py ADDED
@@ -0,0 +1,93 @@
1
+ """Render the deferred expression syntax supported by the original JAML API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import json
7
+ import re
8
+
9
+ from ._eval import safe_eval
10
+
11
+ EXPRESSION = (
12
+ r"~(?:\((?:[^()]|\([^()]*\))*\)|\[(?:[^\[\]]|\[[^\[\]]*\])*\])|\{\^.*?\^\}"
13
+ )
14
+ QUOTED = (
15
+ r'''""".*?"""|\x27\x27\x27.*?\x27\x27\x27'''
16
+ r"""|"(?:\\.|[^"\\])*"|\x27(?:\\.|[^\x27\\])*\x27"""
17
+ )
18
+ SCOPED = r"([@$%])(?:\{([^}]+)\}|([A-Za-z_]\w*(?:\.\w+)*))"
19
+
20
+
21
+ def _lookup(path, *environments):
22
+ for environment in environments:
23
+ value = environment
24
+ for part in path.split("."):
25
+ if not isinstance(value, dict) or part not in value:
26
+ break
27
+ value = value[part]
28
+ else:
29
+ return value
30
+ raise KeyError(path)
31
+
32
+
33
+ def _literal(value):
34
+ if isinstance(value, dict):
35
+ return (
36
+ "{"
37
+ + ", ".join(f"{k} = {_literal(v)}" for k, v in value.items())
38
+ + "}"
39
+ )
40
+ return json.dumps(value, ensure_ascii=False)
41
+
42
+
43
+ class _StringConcatenation(ast.NodeTransformer):
44
+ def visit_BinOp(self, node):
45
+ node = self.generic_visit(node)
46
+ if (
47
+ isinstance(node.op, ast.Add)
48
+ and isinstance(node.left, ast.Constant)
49
+ and isinstance(node.right, ast.Constant)
50
+ and (
51
+ isinstance(node.left.value, str)
52
+ or isinstance(node.right.value, str)
53
+ )
54
+ ):
55
+ return ast.copy_location(
56
+ ast.Constant(str(node.left.value) + str(node.right.value)),
57
+ node,
58
+ )
59
+ return node
60
+
61
+
62
+ def render_source(source, context, globals):
63
+ """Replace deferred expressions without discarding annotations or
64
+ layout.
65
+ """
66
+ tokens = re.compile(f"(?:{QUOTED})|(?:{EXPRESSION})", re.S)
67
+ references = re.compile(f"(?:{QUOTED})|(?:{SCOPED})", re.S)
68
+
69
+ def replace_expression(match):
70
+ raw = match.group()
71
+ if not raw.startswith(("~", "{^")):
72
+ return raw
73
+ headers = list(
74
+ re.finditer(r"^\s*\[([^\[\]\n]+)\]", source[: match.start()], re.M)
75
+ )
76
+ local = _lookup(headers[-1][1], globals) if headers else globals
77
+
78
+ def replace_reference(reference):
79
+ marker, braced, dotted = reference.groups()
80
+ if marker is None:
81
+ return reference.group()
82
+ environments = (
83
+ (context,) if marker == "$" else (local, globals, context)
84
+ )
85
+ return repr(_lookup(braced or dotted, *environments))
86
+
87
+ inner = raw[2:-2] if raw.startswith("{^") else raw[1:]
88
+ expression = references.sub(replace_reference, inner).strip()
89
+ tree = _StringConcatenation().visit(ast.parse(expression, mode="eval"))
90
+ value = safe_eval(ast.unparse(ast.fix_missing_locations(tree)), {})
91
+ return _literal(value)
92
+
93
+ return tokens.sub(replace_expression, source)
jumbl/_make_static.py ADDED
@@ -0,0 +1,86 @@
1
+ # jumbl/_helpers.py (new small util module)
2
+ from __future__ import annotations
3
+ from typing import Dict, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from ._ast_nodes import TableArraySectionNode, SectionNode
7
+
8
+
9
+ def make_static_table_array(
10
+ header_str: str, scope: Dict
11
+ ) -> "TableArraySectionNode":
12
+ from ._ast_nodes import TableArraySectionNode, TableArrayHeaderNode
13
+
14
+ ta = TableArraySectionNode()
15
+ ta.header = TableArrayHeaderNode(origin=header_str, value=header_str)
16
+ ta.body = [] # no inline assignments in the header-only form
17
+ ta.value = scope
18
+ return ta
19
+
20
+
21
+ def make_static_section(header: str, scope: Dict) -> "SectionNode":
22
+ from ._ast_nodes import (
23
+ SectionNode,
24
+ SectionNameNode,
25
+ AssignmentNode,
26
+ SingleQuotedStringNode,
27
+ IntegerNode,
28
+ FloatNode,
29
+ BooleanNode,
30
+ NullNode,
31
+ )
32
+
33
+ """
34
+ Build a *static* SectionNode (no comprehensions) from a header string
35
+ and a dict of key‑value pairs that are already evaluated.
36
+ """
37
+ sec = SectionNode()
38
+
39
+ # header
40
+ sn = SectionNameNode()
41
+ sn.parts = [type("Tok", (), {"value": header})] # fake IDENTIFIER token
42
+ sn.value = header
43
+ sn.origin = header
44
+ sec.header = sn
45
+ sec.lbrack = type("Tok", (), {"value": "["})
46
+ sec.rbrack = type("Tok", (), {"value": "]"})
47
+
48
+ # body lines
49
+ for k, v in scope.items():
50
+ a = AssignmentNode()
51
+ tok_id = type("Tok", (), {"value": k})
52
+ a.identifier = tok_id
53
+ a.equals = type("Tok", (), {"value": "="})
54
+
55
+ def wrap_scalar(val):
56
+ if isinstance(val, str):
57
+ s = SingleQuotedStringNode()
58
+ s.value = val
59
+ s.origin = f'"{val}"'
60
+ return s
61
+ if isinstance(val, bool):
62
+ b = BooleanNode()
63
+ b.value = "true" if val else "false"
64
+ b.resolved = val
65
+ return b
66
+ if isinstance(val, int):
67
+ n = IntegerNode()
68
+ n.value = str(val)
69
+ n.resolved = val
70
+ return n
71
+ if isinstance(val, float):
72
+ f = FloatNode()
73
+ f.value = str(val)
74
+ f.resolved = val
75
+ return f
76
+ if val is None:
77
+ n = NullNode()
78
+ n.value = "null"
79
+ return n
80
+ return val # already a node or complex obj
81
+
82
+ a.value = wrap_scalar(v)
83
+ a.resolved = v
84
+ sec.contents.append(a)
85
+
86
+ return sec
jumbl/_substitute.py ADDED
@@ -0,0 +1,52 @@
1
+ import re
2
+ from typing import Optional
3
+
4
+
5
+ def _substitute_vars(
6
+ expr: str,
7
+ global_env: dict,
8
+ local_env: dict,
9
+ context: Optional[dict] = None,
10
+ quote_strings: bool = True,
11
+ ) -> str:
12
+ context = context or {}
13
+
14
+ def repl_local(m):
15
+ var = m.group(1).strip()
16
+ if local_env and var in local_env:
17
+ value = local_env[var]
18
+ if quote_strings and isinstance(value, str):
19
+ return repr(value)
20
+ return str(value)
21
+ return f"%{{{var}}}"
22
+
23
+ def repl_global(m):
24
+ var = m.group(1).strip()
25
+ if "." in var:
26
+ section, key = var.split(".", 1)
27
+ sect_val = global_env.get(section)
28
+ if isinstance(sect_val, dict) and key in sect_val:
29
+ value = sect_val[key]
30
+ if quote_strings and isinstance(value, str):
31
+ return repr(value)
32
+ return str(value)
33
+ if var in global_env:
34
+ value = global_env[var]
35
+ if quote_strings and isinstance(value, str):
36
+ return repr(value)
37
+ return str(value)
38
+ return f"@{{{var}}}"
39
+
40
+ def repl_context(m):
41
+ var = m.group(1).strip()
42
+ if var in context:
43
+ value = context[var]
44
+ if quote_strings and isinstance(value, str):
45
+ return repr(value)
46
+ return str(value)
47
+ return f"${{{var}}}"
48
+
49
+ tmp = re.sub(r"%\{([^}]+)\}", repl_local, expr)
50
+ tmp = re.sub(r"@\{([^}]+)\}", repl_global, tmp)
51
+ tmp = re.sub(r"\$\{([^}]+)\}", repl_context, tmp)
52
+ return tmp