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/_eval.py ADDED
@@ -0,0 +1,249 @@
1
+ # jumbl/_eval.py
2
+ from typing import Dict, Any
3
+ import ast
4
+ import operator as op
5
+ import logging
6
+
7
+ logger = logging.getLogger(__name__)
8
+ logger.setLevel(logging.DEBUG) # caller can override
9
+
10
+
11
+ def safe_eval(expr: str, local_env: Dict[str, Any] | None = None) -> Any:
12
+ """
13
+ Safely evaluate a restricted Python expression.
14
+
15
+ Supported:
16
+ • arithmetic + boolean ops
17
+ • comparisons
18
+ • literals (list / tuple / set / dict)
19
+ • list-, set- & generator-comprehensions ◀ NEW
20
+ • ternary expressions (a if cond else b)
21
+ • calls to a small allow-list of built-ins
22
+ """
23
+ local_env = local_env or {}
24
+
25
+ # ── allow-lists ────────────────────────────────────────────────────
26
+ _ops = {
27
+ ast.Add: op.add,
28
+ ast.Sub: op.sub,
29
+ ast.Mult: op.mul,
30
+ ast.Div: op.truediv,
31
+ ast.FloorDiv: op.floordiv,
32
+ ast.Mod: op.mod,
33
+ ast.Pow: op.pow,
34
+ }
35
+ _boolops = {ast.And, ast.Or}
36
+ _cmpops = {
37
+ ast.Eq,
38
+ ast.NotEq,
39
+ ast.Lt,
40
+ ast.LtE,
41
+ ast.Gt,
42
+ ast.GtE,
43
+ ast.In,
44
+ ast.NotIn,
45
+ ast.Is,
46
+ ast.IsNot,
47
+ }
48
+ _funcs = {
49
+ "enumerate": enumerate,
50
+ "false": False,
51
+ "true": True,
52
+ "null": None,
53
+ }
54
+
55
+ # ── helpers ───────────────────────────────────────────────────────
56
+ def _eval(node: ast.AST):
57
+ # ── NEW: f-string nodes ───────────────────────────────────────────
58
+ if isinstance(node, ast.JoinedStr): # complete f-string
59
+ parts = []
60
+ for piece in node.values:
61
+ parts.append(_eval(piece))
62
+ return "".join(parts)
63
+
64
+ if isinstance(node, ast.FormattedValue): # an {expr[:spec]!c} piece
65
+ val = _eval(node.value)
66
+ # handle !s / !r / !a conversions
67
+ if node.conversion == -1:
68
+ pass
69
+ elif node.conversion == ord("s"):
70
+ val = str(val)
71
+ elif node.conversion == ord("r"):
72
+ val = repr(val)
73
+ elif node.conversion == ord("a"):
74
+ val = ascii(val)
75
+ else:
76
+ raise ValueError("Unsupported f-string conversion")
77
+
78
+ # handle optional format spec
79
+ if node.format_spec is not None:
80
+ spec = _eval(node.format_spec)
81
+ val = format(val, spec)
82
+ return str(val)
83
+
84
+ # ── NEW: attribute access (obj.attr or mapping-style) ──────────────
85
+ if isinstance(node, ast.Attribute):
86
+ obj = _eval(node.value)
87
+ attr = node.attr
88
+ if attr.startswith("_"):
89
+ raise ValueError(
90
+ "Access to private/protected attributes is disallowed"
91
+ )
92
+ # Treat dict-like objects as attribute-accessible by key
93
+ if isinstance(obj, dict):
94
+ if attr in obj:
95
+ return obj[attr]
96
+ raise ValueError(f"Key '{attr}' not found in mapping")
97
+ if hasattr(obj, attr):
98
+ return getattr(obj, attr)
99
+ raise ValueError(f"Attribute '{attr}' not found")
100
+
101
+ # literals / names ------------------------------------------------
102
+ if isinstance(node, ast.Expression):
103
+ return _eval(node.body)
104
+ if isinstance(node, ast.Constant):
105
+ return node.value
106
+ if isinstance(node, ast.Name):
107
+ if node.id in local_env:
108
+ return local_env[node.id]
109
+ if node.id in _funcs:
110
+ return _funcs[node.id]
111
+ raise ValueError(f"Name not allowed: {node.id}")
112
+
113
+ # arithmetic / unary ops -----------------------------------------
114
+ if isinstance(node, ast.BinOp):
115
+ if type(node.op) not in _ops:
116
+ raise ValueError(
117
+ f"Unsupported operator: {type(node.op).__name__}"
118
+ )
119
+ return _ops[type(node.op)](_eval(node.left), _eval(node.right))
120
+ if isinstance(node, ast.UnaryOp):
121
+ operand = _eval(node.operand)
122
+ if isinstance(node.op, ast.UAdd):
123
+ return +operand
124
+ if isinstance(node.op, ast.USub):
125
+ return -operand
126
+ raise ValueError(
127
+ f"Unsupported unary operator: {type(node.op).__name__}"
128
+ )
129
+
130
+ # boolean ops -----------------------------------------------------
131
+ if isinstance(node, ast.BoolOp):
132
+ if type(node.op) not in _boolops:
133
+ raise ValueError(
134
+ f"Unsupported boolean operator: {type(node.op).__name__}"
135
+ )
136
+ vals = [_eval(v) for v in node.values]
137
+ return all(vals) if isinstance(node.op, ast.And) else any(vals)
138
+
139
+ # ternary ---------------------------------------------------------
140
+ if isinstance(node, ast.IfExp):
141
+ return _eval(node.body) if _eval(node.test) else _eval(node.orelse)
142
+
143
+ # comparisons -----------------------------------------------------
144
+ if isinstance(node, ast.Compare):
145
+ left = _eval(node.left)
146
+ for op_node, comp in zip(node.ops, node.comparators):
147
+ cmp = _eval(comp)
148
+ t = type(op_node)
149
+ if t not in _cmpops:
150
+ raise ValueError(
151
+ f"Unsupported comparison operator: {t.__name__}"
152
+ )
153
+ ok = (
154
+ (t is ast.Eq and left == cmp)
155
+ or (t is ast.NotEq and left != cmp)
156
+ or (t is ast.Lt and left < cmp)
157
+ or (t is ast.LtE and left <= cmp)
158
+ or (t is ast.Gt and left > cmp)
159
+ or (t is ast.GtE and left >= cmp)
160
+ or (t is ast.In and left in cmp)
161
+ or (t is ast.NotIn and left not in cmp)
162
+ or (t is ast.Is and left is cmp)
163
+ or (t is ast.IsNot and left is not cmp)
164
+ )
165
+ if not ok:
166
+ return False
167
+ left = cmp
168
+ return True
169
+
170
+ # calls -----------------------------------------------------------
171
+ if isinstance(node, ast.Call):
172
+ func = _eval(node.func)
173
+ args = [_eval(a) for a in node.args]
174
+ kwargs = {kw.arg: _eval(kw.value) for kw in node.keywords}
175
+ return func(*args, **kwargs)
176
+
177
+ # literals --------------------------------------------------------
178
+ if isinstance(node, ast.List):
179
+ return [_eval(elt) for elt in node.elts]
180
+ if isinstance(node, ast.Tuple):
181
+ return tuple(_eval(elt) for elt in node.elts)
182
+ if isinstance(node, ast.Set):
183
+ return {_eval(elt) for elt in node.elts}
184
+ if isinstance(node, ast.Dict):
185
+ return {_eval(k): _eval(v) for k, v in zip(node.keys, node.values)}
186
+
187
+ # comprehensions (list, set, generator) --------------------------- ◀
188
+ # NEW
189
+ if isinstance(node, (ast.ListComp, ast.SetComp, ast.GeneratorExp)):
190
+
191
+ def _comp_recurse(gen_idx: int):
192
+ if gen_idx == len(node.generators):
193
+ yield _eval(node.elt)
194
+ return
195
+ gen = node.generators[gen_idx]
196
+ for item in _eval(gen.iter):
197
+ if not isinstance(gen.target, ast.Name):
198
+ raise ValueError("Unsupported comprehension target")
199
+ # save / restore binding to avoid leaks
200
+ name = gen.target.id
201
+ prev = local_env.get(name, object())
202
+ local_env[name] = item
203
+ try:
204
+ if gen.ifs and not all(
205
+ _eval(cond) for cond in gen.ifs
206
+ ):
207
+ continue
208
+ yield from _comp_recurse(gen_idx + 1)
209
+ finally:
210
+ if prev is object():
211
+ local_env.pop(name, None)
212
+ else:
213
+ local_env[name] = prev
214
+
215
+ output = list(_comp_recurse(0))
216
+ # Always return the collection intact;
217
+ # header logic will decide what to do with it.
218
+ if isinstance(node, ast.GeneratorExp):
219
+ return output # ← keep list, don’t join
220
+ if isinstance(node, ast.ListComp):
221
+ return output
222
+ return set(output) # ast.SetComp
223
+
224
+ # subscripting ----------------------------------------------------
225
+ if isinstance(node, ast.Subscript):
226
+ value = _eval(node.value)
227
+ slice_val = _eval(
228
+ node.slice.value
229
+ if isinstance(node.slice, ast.Index)
230
+ else node.slice
231
+ )
232
+ return value[slice_val]
233
+
234
+ # fallback --------------------------------------------------------
235
+ raise ValueError(
236
+ f"Unsupported expression element: {type(node).__name__}"
237
+ )
238
+
239
+ # ── entry-point ─────────────────────────────────────────────────────
240
+ try:
241
+ # wrap top-level bare f-string into a literal so ast.parse works
242
+ if isinstance(expr, str) and expr.lstrip().startswith('f"'):
243
+ expr = f"({expr})" # minimal wrapper
244
+ logger.debug(f"evaluating {expr}")
245
+ tree = ast.parse(expr, mode="eval")
246
+ return _eval(tree)
247
+ except Exception as exc:
248
+ logger.exception(f"Evaluation failed: {exc}")
249
+ raise
jumbl/_expression.py ADDED
@@ -0,0 +1,271 @@
1
+ """
2
+ Folded‑expression evaluation for the *resolve* phase.
3
+
4
+ • Substitutes @{…} / %{…} immediately (supports dotted paths).
5
+ • Leaves ${…} placeholders for render‑time.
6
+ • Executes constant arithmetic / concatenation with safe_eval.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from lark import Token, Tree
14
+
15
+ from ._eval import safe_eval
16
+
17
+
18
+ # ───────────────────────────── token classes ──────────────────────────────
19
+ _STR_TOKENS = {
20
+ "SINGLE_QUOTED_STRING",
21
+ "TRIPLE_QUOTED_STRING",
22
+ "TRIPLE_BACKTICK_STRING",
23
+ "BACKTICK_STRING",
24
+ }
25
+
26
+ _SCOPE_PREFIX = {
27
+ "GLOBAL_SCOPED_VAR": "@",
28
+ "LOCAL_SCOPED_VAR": "%",
29
+ "CONTEXT_SCOPED_VAR": "$",
30
+ }
31
+
32
+
33
+ # ───────────────────────────── helpers ─────────────────────────────────────
34
+ def _lookup(path: str, *envs: Dict[str, Any]) -> Optional[Any]:
35
+ """Return the first hit for a dotted path in the provided envs."""
36
+ parts = path.split(".")
37
+ for env in envs:
38
+ cur: Any = env
39
+ for p in parts:
40
+ if not (isinstance(cur, dict) and p in cur):
41
+ cur = None
42
+ break
43
+ cur = cur[p]
44
+ if cur is not None:
45
+ return cur
46
+ return None
47
+
48
+
49
+ def _tok_to_py(
50
+ tok: Token,
51
+ g: Dict[str, Any],
52
+ local_env: Dict[str, Any],
53
+ c: Dict[str, Any],
54
+ ) -> str:
55
+ """Convert a Lark token to a Python snippet (or placeholder)."""
56
+ # ──────────────────────────────── Strings ────────────────────────────────
57
+ if tok.type in _STR_TOKENS:
58
+ raw = tok.value
59
+ # If the first and last chars are matching quotes/backticks, strip them
60
+ if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ('"', "'", "`"):
61
+ raw = raw[1:-1]
62
+ return repr(raw)
63
+
64
+ # ───────────────────────────── Numerics & Booleans
65
+ # ─────────────────────────
66
+ if tok.type in {"INTEGER", "FLOAT"}:
67
+ return tok.value
68
+ if tok.type == "BOOLEAN":
69
+ return "True" if tok.value == "true" else "False"
70
+
71
+ # ───────────────────────────── Operators ────────────────────────────────
72
+ if tok.type == "OPERATOR":
73
+ return tok.value
74
+
75
+ # ───────────────────────── Scope‑prefixed vars ───────────────────────────
76
+ if tok.type in _SCOPE_PREFIX:
77
+ marker = _SCOPE_PREFIX[tok.type]
78
+ inner = tok.value[2:-1] # strip the @{…}, %{…}, or ${…}
79
+
80
+ # Context‑scoped (${…})
81
+ if marker == "$":
82
+ ctx = c or {}
83
+ val = _lookup(inner, ctx)
84
+ if val is not None:
85
+ if hasattr(val, "evaluate"):
86
+ val = val.evaluate()
87
+ return repr(val)
88
+ return tok.value
89
+
90
+ # Global (@{…}) or local (%{…})
91
+ val = (
92
+ _lookup(inner, g)
93
+ if marker == "@"
94
+ else _lookup(inner, local_env, g)
95
+ )
96
+ if val is None:
97
+ return tok.value
98
+ if hasattr(val, "evaluate"):
99
+ val = val.evaluate()
100
+ if isinstance(val, str):
101
+ # strip any leftover quotes
102
+ val = val.strip("\"'")
103
+ return repr(val)
104
+
105
+ # ────────────────────────────── Fallback ────────────────────────────────
106
+ return tok.value
107
+
108
+
109
+ # ─────────────────────────── public entry‑point ───────────────────────────
110
+ def evaluate_expression_tree(
111
+ tree: Tree,
112
+ global_env: Dict[str, Any],
113
+ local_env: Optional[Dict[str, Any]] = None,
114
+ context: Optional[Dict[str, Any]] = None,
115
+ ) -> Any:
116
+ """Resolve a `<( … )>` expression, substituting @{…} and %{…} immediately.
117
+ Leaves ${…} intact and wraps in an f-string if any remain."""
118
+ from lark import Token
119
+ from ._ast_nodes import (
120
+ BaseNode,
121
+ HspacesNode,
122
+ InlineWhitespaceNode,
123
+ WhitespaceNode,
124
+ IntegerNode,
125
+ FloatNode,
126
+ BooleanNode,
127
+ )
128
+
129
+ # Debug entry
130
+ print("[DEBUG EXPR] → evaluate_expression_tree called")
131
+ local_env = local_env or {}
132
+ context = context or {}
133
+ print(f"[DEBUG EXPR] Global env: {global_env}")
134
+ print(f"[DEBUG EXPR] Local env: {local_env}")
135
+ print(f"[DEBUG EXPR] Context: {context}")
136
+
137
+ # Collect only meaningful children (drop whitespace tokens/nodes)
138
+ items = [
139
+ c
140
+ for c in getattr(tree, "children", [])
141
+ if not (
142
+ (
143
+ isinstance(c, Token)
144
+ and c.type in ("HSPACES", "INLINE_WS", "WHITESPACE")
145
+ )
146
+ or isinstance(
147
+ c, (HspacesNode, InlineWhitespaceNode, WhitespaceNode)
148
+ )
149
+ )
150
+ ]
151
+ print(
152
+ (
153
+ f"[DEBUG EXPR] Expression items: "
154
+ f"{[getattr(c, 'value', repr(c)) for c in items]}"
155
+ )
156
+ )
157
+
158
+ parts: List[str] = []
159
+ for c in items:
160
+ # 1) AST‐level boolean → Python literal
161
+ if isinstance(c, BooleanNode):
162
+ snippet = "True" if c.value.lower() == "true" else "False"
163
+ print(f"[DEBUG EXPR] AST boolean node: {snippet}")
164
+ parts.append(snippet)
165
+ continue
166
+
167
+ # 2) AST‐level integers/floats → raw digits
168
+ if isinstance(c, (IntegerNode, FloatNode)):
169
+ snippet = c.value
170
+ print(f"[DEBUG EXPR] AST numeric node: {snippet}")
171
+ parts.append(snippet)
172
+ continue
173
+
174
+ # 3) Raw Token integers/floats (just in case)
175
+ if isinstance(c, Token) and c.type in {"INTEGER", "FLOAT"}:
176
+ snippet = c.value
177
+ print(f"[DEBUG EXPR] Token numeric: {snippet}")
178
+ parts.append(snippet)
179
+ continue
180
+
181
+ # 4) Other tokens → normal converter
182
+ if isinstance(c, Token):
183
+ snippet = _tok_to_py(c, global_env, local_env, context)
184
+ # strip accidental quotes around digit‐only strings
185
+ if (
186
+ snippet.startswith(("'", '"'))
187
+ and snippet.endswith(("'", '"'))
188
+ and snippet[1:-1].isdigit()
189
+ ):
190
+ snippet = snippet[1:-1]
191
+
192
+ # 5) AST nodes carrying a Token in .meta
193
+ elif (
194
+ isinstance(c, BaseNode)
195
+ and hasattr(c, "meta")
196
+ and isinstance(c.meta, Token)
197
+ ):
198
+ snippet = _tok_to_py(c.meta, global_env, local_env, context)
199
+
200
+ # 6) Other AST nodes → resolve then stringify
201
+ elif isinstance(c, BaseNode):
202
+ try:
203
+ c.resolve(global_env, local_env, context)
204
+ except Exception:
205
+ pass
206
+ val = getattr(c, "resolved", None) or getattr(c, "value", None)
207
+ if isinstance(val, str):
208
+ snippet = repr(val.strip("\"'"))
209
+ else:
210
+ snippet = str(val)
211
+
212
+ # 7) Fallback
213
+ else:
214
+ snippet = str(c)
215
+
216
+ parts.append(snippet)
217
+ print(f"[DEBUG EXPR] Part snippet: {snippet}")
218
+
219
+ # ────────────────────────────────────────────
220
+ # **FIX**: join with spaces so that 'if' / 'else' remain valid
221
+ py_expr = " ".join(parts)
222
+ print(f"[DEBUG EXPR] Built py_expr: {py_expr}")
223
+
224
+ # Static-only: no ${…}, so safe_eval
225
+ if "${" not in py_expr:
226
+ try:
227
+ result = safe_eval(py_expr, local_env=local_env)
228
+ print(f"[DEBUG EXPR] Static eval result: {result}")
229
+ return result
230
+ except Exception as e:
231
+ print(f"[DEBUG EXPR] Static eval error: {e}")
232
+ return py_expr
233
+
234
+ # Mixed dynamic: preserve ${…}
235
+ placeholder_idxs = [
236
+ idx
237
+ for idx, part in enumerate(parts)
238
+ if isinstance(part, str) and part.startswith("${")
239
+ ]
240
+ if placeholder_idxs:
241
+ i0 = placeholder_idxs[0]
242
+ if i0 > 0 and parts[i0 - 1] == "+":
243
+ static_parts = parts[: i0 - 1]
244
+ else:
245
+ static_parts = parts[:i0]
246
+ placeholder_text = parts[i0]
247
+ static_expr = "".join(static_parts)
248
+ try:
249
+ static_value = str(safe_eval(static_expr, local_env=local_env))
250
+ except Exception as e:
251
+ print(f"[DEBUG EXPR] Static prefix eval error: {e}")
252
+ static_value = static_expr
253
+ f_res = f'f"{static_value}{placeholder_text}"'
254
+ print(f"[DEBUG EXPR] Final f-string result: {f_res}")
255
+ return f_res
256
+
257
+ # No placeholders detected, fallback
258
+ return py_expr
259
+
260
+
261
+ # ───────────────────── used by Config.render fallback ─────────────────────
262
+ def _render_folded_expression_node(
263
+ node,
264
+ env: Dict[str, Any],
265
+ context: Optional[Dict[str, Any]] = None,
266
+ ):
267
+ from ._ast_nodes import FoldedExpressionNode
268
+
269
+ if isinstance(node, FoldedExpressionNode) and node.resolved is not None:
270
+ return node.resolved
271
+ return evaluate_expression_tree(node.content_tree, env, env, context)