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/__init__.py +35 -0
- jumbl/_ast_nodes.py +2089 -0
- jumbl/_comprehension.py +179 -0
- jumbl/_config.py +657 -0
- jumbl/_eval.py +249 -0
- jumbl/_expression.py +271 -0
- jumbl/_fstring.py +238 -0
- jumbl/_lark_parser.py +12 -0
- jumbl/_legacy.py +93 -0
- jumbl/_make_static.py +86 -0
- jumbl/_substitute.py +52 -0
- jumbl/_transformer.bak.py +755 -0
- jumbl/_transformer.py +2415 -0
- jumbl/_utils.py +46 -0
- jumbl/api.py +236 -0
- jumbl/ast_nodes.bak.py +676 -0
- jumbl/grammar.lark +302 -0
- jumbl/unparser.bak.py +345 -0
- jumbl-0.2.1.dev1.dist-info/METADATA +331 -0
- jumbl-0.2.1.dev1.dist-info/RECORD +23 -0
- jumbl-0.2.1.dev1.dist-info/WHEEL +4 -0
- jumbl-0.2.1.dev1.dist-info/licenses/LICENSE +201 -0
- jumbl-0.2.1.dev1.dist-info/licenses/NOTICE +7 -0
jumbl/_config.py
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
from collections.abc import MutableMapping
|
|
2
|
+
from copy import deepcopy
|
|
3
|
+
from typing import Any, Dict, Optional, Sequence, List, TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
from ._fstring import _evaluate_f_string
|
|
6
|
+
import logging
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
logger.setLevel(logging.DEBUG) # caller can override
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from ._ast_nodes import BaseNode
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SectionProxy(MutableMapping):
|
|
16
|
+
def __init__(self, config: "Config", prefix: str):
|
|
17
|
+
self._config = config
|
|
18
|
+
self._prefix = prefix
|
|
19
|
+
|
|
20
|
+
def _cur_dict(self):
|
|
21
|
+
# grab the nested dict at top‑level key self._prefix
|
|
22
|
+
current = self._config._data
|
|
23
|
+
for part in self._prefix.split("."):
|
|
24
|
+
current = current[part]
|
|
25
|
+
return current
|
|
26
|
+
|
|
27
|
+
def __getitem__(self, key: str) -> Any:
|
|
28
|
+
cur = self._cur_dict()
|
|
29
|
+
val = cur[key]
|
|
30
|
+
if isinstance(val, dict):
|
|
31
|
+
# nested SectionProxy for deeper sections
|
|
32
|
+
return SectionProxy(self._config, f"{self._prefix}.{key}")
|
|
33
|
+
return val
|
|
34
|
+
|
|
35
|
+
def __setitem__(self, key: str, value: Any) -> None:
|
|
36
|
+
print("SectionProxy setter")
|
|
37
|
+
cur = self._cur_dict()
|
|
38
|
+
cur[key] = value
|
|
39
|
+
# still sync the AST with the dotted path
|
|
40
|
+
self._config._sync_ast(f"{self._prefix}.{key}", value)
|
|
41
|
+
|
|
42
|
+
def __delitem__(self, key: str) -> None:
|
|
43
|
+
cur = self._cur_dict()
|
|
44
|
+
del cur[key]
|
|
45
|
+
self._config._sync_ast(f"{self._prefix}.{key}", None)
|
|
46
|
+
|
|
47
|
+
def __iter__(self):
|
|
48
|
+
return iter(self._cur_dict())
|
|
49
|
+
|
|
50
|
+
def __len__(self) -> int:
|
|
51
|
+
return len(self._cur_dict())
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Config(MutableMapping):
|
|
55
|
+
"""
|
|
56
|
+
A thin wrapper around the parsed AST that preserves round-trip fidelity
|
|
57
|
+
yet behaves like a normal mutable mapping.
|
|
58
|
+
|
|
59
|
+
• `resolve()` collapses every AST node and expands **static** f‑strings
|
|
60
|
+
(those that do *not* reference `${…}` context placeholders).
|
|
61
|
+
|
|
62
|
+
• `render()` finishes the job, expanding any remaining f‑strings with the
|
|
63
|
+
runtime *context* supplied by the caller.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
# imported lazily to avoid circulars
|
|
67
|
+
from ._ast_nodes import StartNode
|
|
68
|
+
|
|
69
|
+
def __init__(self, ast: "Config.StartNode"):
|
|
70
|
+
self._ast = ast
|
|
71
|
+
self._data = ast.data
|
|
72
|
+
self._rendered_source = None
|
|
73
|
+
print("[DEBUG CONFIG INIT]:", self._data, self._ast)
|
|
74
|
+
|
|
75
|
+
def __getitem__(self, key: str) -> Any:
|
|
76
|
+
val = self._data[key] # only literal keys
|
|
77
|
+
if isinstance(val, dict):
|
|
78
|
+
return SectionProxy(self, key)
|
|
79
|
+
return val
|
|
80
|
+
|
|
81
|
+
def __setitem__(self, key: str, value: Any) -> None:
|
|
82
|
+
print("Config setter")
|
|
83
|
+
self._data[key] = value # only literal keys
|
|
84
|
+
self._sync_ast(key, value)
|
|
85
|
+
|
|
86
|
+
def __delitem__(self, key: str) -> None:
|
|
87
|
+
del self._data[key]
|
|
88
|
+
|
|
89
|
+
def __iter__(self):
|
|
90
|
+
return iter(self._data)
|
|
91
|
+
|
|
92
|
+
def __len__(self) -> int:
|
|
93
|
+
return len(self._data)
|
|
94
|
+
|
|
95
|
+
def __repr__(self) -> str:
|
|
96
|
+
return f"Config({self._data})"
|
|
97
|
+
|
|
98
|
+
def __contains__(self, key: str) -> bool:
|
|
99
|
+
if key in self._data:
|
|
100
|
+
return True
|
|
101
|
+
import re
|
|
102
|
+
|
|
103
|
+
def _normalize(s: str) -> str:
|
|
104
|
+
return re.sub(r"\s+", " ", s.strip())
|
|
105
|
+
|
|
106
|
+
normalized = _normalize(key)
|
|
107
|
+
return any(
|
|
108
|
+
isinstance(k, str) and _normalize(k) == normalized
|
|
109
|
+
for k in self._data
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# ──────────────────────────────────────────────────────── helpers
|
|
113
|
+
|
|
114
|
+
def _materialise_comprehension(
|
|
115
|
+
self,
|
|
116
|
+
node,
|
|
117
|
+
concrete_keys: Sequence[str],
|
|
118
|
+
section_map: dict,
|
|
119
|
+
):
|
|
120
|
+
"""
|
|
121
|
+
Replace *node* (whose header is still a ComprehensionHeaderNode) with
|
|
122
|
+
one or more TableArraySectionNode clones so that StartNode.emit() will
|
|
123
|
+
re-serialize the expanded keys exactly.
|
|
124
|
+
|
|
125
|
+
• *concrete_keys* – list/tuple of the header strings produced by the
|
|
126
|
+
comprehension, in order.
|
|
127
|
+
• *section_map* – the body mapping for that section (already popped
|
|
128
|
+
from self._data by the caller).
|
|
129
|
+
|
|
130
|
+
Returns nothing. Mutates self._ast.lines in place.
|
|
131
|
+
"""
|
|
132
|
+
from ._ast_nodes import TableArrayHeaderNode
|
|
133
|
+
|
|
134
|
+
lines = self._ast.lines
|
|
135
|
+
idx = lines.index(node)
|
|
136
|
+
|
|
137
|
+
# convert THIS node to the first key
|
|
138
|
+
first_key = concrete_keys[0]
|
|
139
|
+
node.header = TableArrayHeaderNode(origin=first_key, value=first_key)
|
|
140
|
+
|
|
141
|
+
# any additional keys → deep-clone the section node
|
|
142
|
+
for k in concrete_keys[1:]:
|
|
143
|
+
clone = deepcopy(node)
|
|
144
|
+
clone.header = TableArrayHeaderNode(origin=k, value=k)
|
|
145
|
+
idx += 1
|
|
146
|
+
lines.insert(idx, clone)
|
|
147
|
+
|
|
148
|
+
# finally, write bodies into _data (caller already handled first one)
|
|
149
|
+
for k in concrete_keys[1:]:
|
|
150
|
+
self._insert_nested_key(k, deepcopy(section_map))
|
|
151
|
+
|
|
152
|
+
def _insert_nested_key(self, dotted_key: str, value: Any) -> None:
|
|
153
|
+
"""
|
|
154
|
+
Insert *value* into self._data following the dotted path in
|
|
155
|
+
*dotted_key*
|
|
156
|
+
(e.g. "file.auth.login.source"). Intermediate mappings are created as
|
|
157
|
+
needed. Any pre-existing scalar encountered on the path is replaced by
|
|
158
|
+
a new mapping.
|
|
159
|
+
"""
|
|
160
|
+
cur: Dict[str, Any] = self._data
|
|
161
|
+
parts: List[str] = dotted_key.split(".")
|
|
162
|
+
for part in parts[:-1]:
|
|
163
|
+
if not isinstance(cur.get(part, {}), dict):
|
|
164
|
+
cur[part] = {}
|
|
165
|
+
cur = cur.setdefault(part, {})
|
|
166
|
+
cur[parts[-1]] = value
|
|
167
|
+
logger.debug(" ↳ nested-set %s → %r", dotted_key, value)
|
|
168
|
+
|
|
169
|
+
def _reparse_value(self, value: str) -> "BaseNode":
|
|
170
|
+
"""
|
|
171
|
+
Parse a value fragment (e.g. folded, array, inline table,
|
|
172
|
+
comprehension, etc.) by
|
|
173
|
+
wrapping it in a tiny config snippet and using the existing parser +
|
|
174
|
+
transformer.
|
|
175
|
+
Returns the newly built AST node for that fragment.
|
|
176
|
+
"""
|
|
177
|
+
from .api import round_trip_loads
|
|
178
|
+
|
|
179
|
+
# Wrap the fragment into a dummy section with a single assignment
|
|
180
|
+
snippet = f"key = {value}\n"
|
|
181
|
+
tmp_cfg = round_trip_loads(snippet)
|
|
182
|
+
# The second line is the AssignmentNode for 'key'
|
|
183
|
+
assign_node = tmp_cfg._ast.lines[0]
|
|
184
|
+
return assign_node.value
|
|
185
|
+
|
|
186
|
+
def _sync_ast(self, dotted: str, value: Any):
|
|
187
|
+
"""Update one assignment while preserving its annotation and
|
|
188
|
+
section.
|
|
189
|
+
"""
|
|
190
|
+
from lark import Token
|
|
191
|
+
from ._ast_nodes import AssignmentNode, BaseNode, SectionNode
|
|
192
|
+
from ._legacy import _literal
|
|
193
|
+
|
|
194
|
+
self._rendered_source = None
|
|
195
|
+
parts = dotted.split(".")
|
|
196
|
+
current = self._ast.data
|
|
197
|
+
for part in parts[:-1]:
|
|
198
|
+
current = current.setdefault(part, {})
|
|
199
|
+
key = parts[-1]
|
|
200
|
+
prefix = ".".join(parts[:-1])
|
|
201
|
+
contents = self._ast.lines
|
|
202
|
+
if prefix:
|
|
203
|
+
section = next(
|
|
204
|
+
(
|
|
205
|
+
node
|
|
206
|
+
for node in self._ast.lines
|
|
207
|
+
if isinstance(node, SectionNode)
|
|
208
|
+
and getattr(node.header, "value", None) == prefix
|
|
209
|
+
),
|
|
210
|
+
None,
|
|
211
|
+
)
|
|
212
|
+
if section is None:
|
|
213
|
+
raise KeyError(prefix)
|
|
214
|
+
contents = section.contents
|
|
215
|
+
if isinstance(value, BaseNode):
|
|
216
|
+
replacement = value
|
|
217
|
+
elif isinstance(value, str) and value.strip().startswith("<("):
|
|
218
|
+
replacement = self._reparse_value(value)
|
|
219
|
+
elif isinstance(value, str) and value.strip().startswith(
|
|
220
|
+
('"', "'", 'f"', "f'", "[", "{", "`")
|
|
221
|
+
):
|
|
222
|
+
replacement = value
|
|
223
|
+
else:
|
|
224
|
+
replacement = self._reparse_value(_literal(value))
|
|
225
|
+
assignment = next(
|
|
226
|
+
(
|
|
227
|
+
node
|
|
228
|
+
for node in contents
|
|
229
|
+
if isinstance(node, AssignmentNode)
|
|
230
|
+
and node.identifier.value == key
|
|
231
|
+
),
|
|
232
|
+
None,
|
|
233
|
+
)
|
|
234
|
+
if assignment is None:
|
|
235
|
+
assignment = AssignmentNode()
|
|
236
|
+
assignment.identifier = Token("IDENTIFIER", key)
|
|
237
|
+
assignment.equals = Token("SETTER", "=")
|
|
238
|
+
contents.append(assignment)
|
|
239
|
+
assignment.value = replacement
|
|
240
|
+
assignment.resolved = None
|
|
241
|
+
current[key] = replacement
|
|
242
|
+
|
|
243
|
+
# round‑trip helpers ------------------------------------------------------
|
|
244
|
+
def dumps(self) -> str:
|
|
245
|
+
"""Emit the configuration exactly as it would appear on disk."""
|
|
246
|
+
if self._rendered_source is not None:
|
|
247
|
+
return self._rendered_source
|
|
248
|
+
return self._ast.emit()
|
|
249
|
+
|
|
250
|
+
to_jml = dumps
|
|
251
|
+
|
|
252
|
+
dump = staticmethod(lambda obj, fp: fp.write(Config.dumps(obj))) # type: ignore
|
|
253
|
+
|
|
254
|
+
# ───────────────────────────────────────────────────────── resolution
|
|
255
|
+
def resolve(self) -> Dict[str, Any]:
|
|
256
|
+
logger.debug("\n\n\n\n⮕ [resolve] entered...")
|
|
257
|
+
from ._eval import safe_eval
|
|
258
|
+
from ._fstring import _eval_fstrings
|
|
259
|
+
from ._comprehension import _eval_comprehensions
|
|
260
|
+
from ._utils import _strip_quotes
|
|
261
|
+
|
|
262
|
+
_eval_fstrings(self._data)
|
|
263
|
+
|
|
264
|
+
logger.debug("① after _eval_fstrings → self._data=%r", self._data)
|
|
265
|
+
|
|
266
|
+
from ._ast_nodes import (
|
|
267
|
+
BaseNode,
|
|
268
|
+
SectionNode,
|
|
269
|
+
TableArraySectionNode,
|
|
270
|
+
TableArrayHeaderNode,
|
|
271
|
+
ComprehensionHeaderNode,
|
|
272
|
+
)
|
|
273
|
+
import re
|
|
274
|
+
|
|
275
|
+
# ② expand conditional headers
|
|
276
|
+
for node in list(self._ast.lines):
|
|
277
|
+
header = getattr(node, "header", None)
|
|
278
|
+
if isinstance(
|
|
279
|
+
node, (SectionNode, TableArraySectionNode)
|
|
280
|
+
) and isinstance(
|
|
281
|
+
header, (TableArrayHeaderNode, ComprehensionHeaderNode)
|
|
282
|
+
): # ← broaden test
|
|
283
|
+
raw_key = header.origin
|
|
284
|
+
expr = raw_key
|
|
285
|
+
logger.debug(
|
|
286
|
+
"②a processing header raw_key=%s expr=%s", raw_key, expr
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
# -- strip alias clauses like "as %{alias}" before placeholder
|
|
290
|
+
# work --
|
|
291
|
+
expr = re.sub(r"\s+as\s+%\{[^}]+\}", "", expr)
|
|
292
|
+
|
|
293
|
+
def _scoped_repl(m):
|
|
294
|
+
var = m.group(1)
|
|
295
|
+
if var in self._data:
|
|
296
|
+
v = self._data[var]
|
|
297
|
+
if isinstance(v, str):
|
|
298
|
+
v = v.strip(
|
|
299
|
+
"\"'"
|
|
300
|
+
) # ➞ strip any surrounding quotes
|
|
301
|
+
return repr(v)
|
|
302
|
+
return "None"
|
|
303
|
+
|
|
304
|
+
expr_py = re.sub(r"[@%]\{([^}]+)\}", _scoped_repl, expr)
|
|
305
|
+
expr_py = expr_py.replace("null", "None")
|
|
306
|
+
if "${" in expr_py:
|
|
307
|
+
logger.debug(
|
|
308
|
+
(
|
|
309
|
+
"skipping header expression with context "
|
|
310
|
+
"placeholders: %s"
|
|
311
|
+
),
|
|
312
|
+
expr_py,
|
|
313
|
+
)
|
|
314
|
+
continue
|
|
315
|
+
logger.debug("executing safe_eval on expr_py=%s", expr_py)
|
|
316
|
+
try:
|
|
317
|
+
result = safe_eval(expr_py, {})
|
|
318
|
+
except Exception as e:
|
|
319
|
+
logger.exception(f"exception: {e}")
|
|
320
|
+
continue
|
|
321
|
+
|
|
322
|
+
if not result:
|
|
323
|
+
self._data.pop(raw_key, None)
|
|
324
|
+
else:
|
|
325
|
+
section_map = self._data.pop(raw_key, None)
|
|
326
|
+
if isinstance(result, (list, tuple, set)):
|
|
327
|
+
import copy
|
|
328
|
+
|
|
329
|
+
for idx, new_key in enumerate(result):
|
|
330
|
+
tgt_map = (
|
|
331
|
+
section_map
|
|
332
|
+
if idx == 0
|
|
333
|
+
else copy.deepcopy(section_map)
|
|
334
|
+
)
|
|
335
|
+
self._insert_nested_key(new_key, tgt_map)
|
|
336
|
+
else:
|
|
337
|
+
self._insert_nested_key(result, section_map)
|
|
338
|
+
node.header.value = result
|
|
339
|
+
node.header.origin = result
|
|
340
|
+
|
|
341
|
+
# ③ collapse all AST nodes into plain Python values
|
|
342
|
+
def _collapse(value: Any, scope: Dict[str, Any]) -> Any:
|
|
343
|
+
if isinstance(value, BaseNode):
|
|
344
|
+
value.resolve(self._data, scope)
|
|
345
|
+
return _collapse(value.evaluate(), scope)
|
|
346
|
+
|
|
347
|
+
if isinstance(value, dict):
|
|
348
|
+
merged = {**scope, **value}
|
|
349
|
+
out: Dict[str, Any] = {}
|
|
350
|
+
for k, v in value.items():
|
|
351
|
+
if k == "__comments__":
|
|
352
|
+
out[k] = v
|
|
353
|
+
else:
|
|
354
|
+
out[k] = _collapse(v, merged)
|
|
355
|
+
return out
|
|
356
|
+
|
|
357
|
+
if isinstance(value, list):
|
|
358
|
+
return [_collapse(x, scope) for x in value]
|
|
359
|
+
|
|
360
|
+
return value
|
|
361
|
+
|
|
362
|
+
collapsed: Dict[str, Any] = {}
|
|
363
|
+
for key, val in list(self._data.items()):
|
|
364
|
+
if key == "__comments__":
|
|
365
|
+
collapsed[key] = val
|
|
366
|
+
else:
|
|
367
|
+
collapsed[key] = _collapse(val, self._data)
|
|
368
|
+
|
|
369
|
+
# ──────────────────────────────────────────────────────────────
|
|
370
|
+
collapsed = _eval_comprehensions(collapsed)
|
|
371
|
+
|
|
372
|
+
# ──────────────────────────────────────────────────────────────
|
|
373
|
+
# ③ post‑process both global‑ and local‑scoped placeholders in strings
|
|
374
|
+
def _expand(val: Any, local_scope: Any) -> Any:
|
|
375
|
+
if isinstance(val, dict):
|
|
376
|
+
return {k: _expand(v, val) for k, v in val.items()}
|
|
377
|
+
if isinstance(val, str):
|
|
378
|
+
pattern = re.compile(r"%\{([^}]+)\}")
|
|
379
|
+
|
|
380
|
+
def repl(m):
|
|
381
|
+
path = m.group(1)
|
|
382
|
+
tgt = local_scope
|
|
383
|
+
for part in path.split("."):
|
|
384
|
+
if isinstance(tgt, dict) and part in tgt:
|
|
385
|
+
tgt = tgt[part]
|
|
386
|
+
else:
|
|
387
|
+
return "None"
|
|
388
|
+
return repr(tgt)
|
|
389
|
+
|
|
390
|
+
return re.sub(pattern, repl, val)
|
|
391
|
+
return val
|
|
392
|
+
|
|
393
|
+
final: Dict[str, Any] = {}
|
|
394
|
+
for k, v in collapsed.items():
|
|
395
|
+
if k == "__comments__":
|
|
396
|
+
final[k] = v
|
|
397
|
+
else:
|
|
398
|
+
final[k] = _expand(v, collapsed)
|
|
399
|
+
return _strip_quotes(final)
|
|
400
|
+
|
|
401
|
+
def render(
|
|
402
|
+
self, context: Optional[Dict[str, Any]] = None
|
|
403
|
+
) -> Dict[str, Any]:
|
|
404
|
+
"""
|
|
405
|
+
Render the parsed JAML AST to a concrete Python object.
|
|
406
|
+
|
|
407
|
+
Detailed DEBUG-level logs trace every transformation step so that
|
|
408
|
+
complex scope interactions are visible during troubleshooting.
|
|
409
|
+
"""
|
|
410
|
+
logger.debug("\n\n\n\n⮕ [render] entered with context=%r", context)
|
|
411
|
+
|
|
412
|
+
# ① expand global- and local-scope f-strings ----------------------
|
|
413
|
+
from ._eval import safe_eval
|
|
414
|
+
from ._fstring import _eval_fstrings
|
|
415
|
+
from ._utils import _strip_quotes
|
|
416
|
+
from ._comprehension import _eval_comprehensions
|
|
417
|
+
|
|
418
|
+
_eval_fstrings(self._data)
|
|
419
|
+
logger.debug("① after _eval_fstrings → self._data=%r", self._data)
|
|
420
|
+
|
|
421
|
+
# imports that create circulars if done at module top -------------
|
|
422
|
+
from ._ast_nodes import (
|
|
423
|
+
BaseNode,
|
|
424
|
+
SectionNode,
|
|
425
|
+
TableArraySectionNode,
|
|
426
|
+
TableArrayHeaderNode,
|
|
427
|
+
ComprehensionHeaderNode,
|
|
428
|
+
)
|
|
429
|
+
import re
|
|
430
|
+
|
|
431
|
+
# ② expand conditional headers (with context) --------------------
|
|
432
|
+
from ._ast_nodes import (
|
|
433
|
+
ContextScopedVarNode,
|
|
434
|
+
FStringNode,
|
|
435
|
+
SectionNameNode,
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
# Bind root context values before header clauses consume them.
|
|
439
|
+
for key, value in list(self._data.items()):
|
|
440
|
+
if isinstance(value, ContextScopedVarNode):
|
|
441
|
+
self._data[key] = value.render(self._data, {}, context or {})
|
|
442
|
+
|
|
443
|
+
def render_body(value, scope):
|
|
444
|
+
if isinstance(value, (ContextScopedVarNode, FStringNode)):
|
|
445
|
+
return render_body(
|
|
446
|
+
value.render(self._data, scope, context), scope
|
|
447
|
+
)
|
|
448
|
+
if isinstance(value, BaseNode):
|
|
449
|
+
value.resolve(self._data, scope)
|
|
450
|
+
return render_body(value.evaluate(), scope)
|
|
451
|
+
if isinstance(value, dict):
|
|
452
|
+
local = {**scope, **value}
|
|
453
|
+
rendered = {}
|
|
454
|
+
for key, item in value.items():
|
|
455
|
+
rendered[key] = render_body(item, local)
|
|
456
|
+
local[key] = rendered[key]
|
|
457
|
+
return rendered
|
|
458
|
+
if isinstance(value, list):
|
|
459
|
+
return [render_body(item, scope) for item in value]
|
|
460
|
+
if isinstance(value, str) and value.startswith(('f"', "f'")):
|
|
461
|
+
return _evaluate_f_string(value, self._data, scope, context)
|
|
462
|
+
return value
|
|
463
|
+
|
|
464
|
+
for node in list(self._ast.lines):
|
|
465
|
+
header = getattr(node, "header", None)
|
|
466
|
+
if isinstance(header, ComprehensionHeaderNode):
|
|
467
|
+
original_key = header.origin
|
|
468
|
+
header.render(self._data, {}, context or {})
|
|
469
|
+
body = self._data.pop(original_key, {})
|
|
470
|
+
aliases = re.findall(r"\bas\s+%\{([^}]+)\}", original_key)
|
|
471
|
+
clones = []
|
|
472
|
+
for key, environment in header.header_envs:
|
|
473
|
+
values = render_body(deepcopy(body), environment)
|
|
474
|
+
for alias in aliases:
|
|
475
|
+
if alias in environment:
|
|
476
|
+
values[alias] = environment[alias]
|
|
477
|
+
self._insert_nested_key(key, values)
|
|
478
|
+
clone = deepcopy(node)
|
|
479
|
+
literal = SectionNameNode()
|
|
480
|
+
literal.value = literal.origin = key
|
|
481
|
+
clone.header = literal
|
|
482
|
+
clones.append(clone)
|
|
483
|
+
index = self._ast.lines.index(node)
|
|
484
|
+
self._ast.lines[index : index + 1] = clones
|
|
485
|
+
continue
|
|
486
|
+
if isinstance(
|
|
487
|
+
node, (SectionNode, TableArraySectionNode)
|
|
488
|
+
) and isinstance(
|
|
489
|
+
header, (TableArrayHeaderNode, ComprehensionHeaderNode)
|
|
490
|
+
): # ← broaden test
|
|
491
|
+
raw_key = header.origin
|
|
492
|
+
expr = raw_key
|
|
493
|
+
logger.debug(
|
|
494
|
+
"②a processing header raw_key=%s expr=%s", raw_key, expr
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
# --- ①: Capture alias clause(s) before stripping them for
|
|
498
|
+
# later binding ---
|
|
499
|
+
alias_anchors = re.findall(
|
|
500
|
+
r"\s+as\s+%\{([^}]+)\}", expr
|
|
501
|
+
) # get list of aliases (may be empty)
|
|
502
|
+
expr = re.sub(
|
|
503
|
+
r"\s+as\s+%\{[^}]+\}", "", expr
|
|
504
|
+
) # strip for python eval
|
|
505
|
+
logger.debug(f"\t- alias_anchors found {alias_anchors}")
|
|
506
|
+
|
|
507
|
+
# substitute ${…} placeholders from *context*
|
|
508
|
+
def _context_repl(m):
|
|
509
|
+
var = m.group(1)
|
|
510
|
+
v = (context or {}).get(var, None)
|
|
511
|
+
logger.debug(
|
|
512
|
+
" – context placeholder ${%s} -> %r", var, v
|
|
513
|
+
)
|
|
514
|
+
if isinstance(v, str):
|
|
515
|
+
v = v.strip("\"'")
|
|
516
|
+
return repr(v)
|
|
517
|
+
|
|
518
|
+
expr_py = re.sub(r"\$\{([^}]+)\}", _context_repl, expr)
|
|
519
|
+
|
|
520
|
+
# substitute @{…} (global) and %{…} (local) placeholders
|
|
521
|
+
def _scoped_repl(m):
|
|
522
|
+
var = m.group(1)
|
|
523
|
+
v = self._data.get(var, None)
|
|
524
|
+
logger.debug(" – scoped placeholder {%s} -> %r", var, v)
|
|
525
|
+
if isinstance(v, str):
|
|
526
|
+
v = v.strip("\"'")
|
|
527
|
+
return repr(v)
|
|
528
|
+
|
|
529
|
+
expr_py = re.sub(r"[@%]\{([^}]+)\}", _scoped_repl, expr_py)
|
|
530
|
+
expr_py = expr_py.replace("null", "None")
|
|
531
|
+
|
|
532
|
+
logger.debug(" – evaluated Python expr: %s", expr_py)
|
|
533
|
+
try:
|
|
534
|
+
result = safe_eval(expr_py, {})
|
|
535
|
+
logger.debug(" – result=%r", result)
|
|
536
|
+
except Exception as exc:
|
|
537
|
+
logger.exception(
|
|
538
|
+
(
|
|
539
|
+
" ✖ header expression failed (%s); leaving "
|
|
540
|
+
"untouched"
|
|
541
|
+
),
|
|
542
|
+
exc,
|
|
543
|
+
)
|
|
544
|
+
continue
|
|
545
|
+
if not result:
|
|
546
|
+
self._data.pop(raw_key, None)
|
|
547
|
+
else:
|
|
548
|
+
logger.debug(
|
|
549
|
+
" – condition truthy → renaming %s → %s",
|
|
550
|
+
raw_key,
|
|
551
|
+
result,
|
|
552
|
+
)
|
|
553
|
+
section_map = self._data.pop(raw_key, None)
|
|
554
|
+
if isinstance(result, (list, tuple, set)):
|
|
555
|
+
# write the first body now – clones handled by helper
|
|
556
|
+
self._insert_nested_key(result[0], section_map)
|
|
557
|
+
self._materialise_comprehension(
|
|
558
|
+
node, list(result), section_map
|
|
559
|
+
)
|
|
560
|
+
else:
|
|
561
|
+
self._insert_nested_key(result, section_map)
|
|
562
|
+
node.header.value = result
|
|
563
|
+
node.header.origin = result
|
|
564
|
+
|
|
565
|
+
# -- inject alias bindings if present --
|
|
566
|
+
if isinstance(header, ComprehensionHeaderNode):
|
|
567
|
+
logger.debug("\t- injecting alias bindings")
|
|
568
|
+
header.render(self._data, {}, context or {})
|
|
569
|
+
logger.debug(
|
|
570
|
+
f"\t- processing alias_env {header.header_envs}"
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
logger.debug("② complete → self._data=%r", self._data)
|
|
574
|
+
|
|
575
|
+
# ③ collapse all AST nodes into plain Python values --------------
|
|
576
|
+
def _collapse(value: Any, scope: Dict[str, Any]) -> Any:
|
|
577
|
+
if isinstance(value, (ContextScopedVarNode, FStringNode)):
|
|
578
|
+
return _collapse(
|
|
579
|
+
value.render(self._data, scope, context), scope
|
|
580
|
+
)
|
|
581
|
+
if isinstance(value, BaseNode):
|
|
582
|
+
value.resolve(self._data, scope)
|
|
583
|
+
return _collapse(value.evaluate(), scope)
|
|
584
|
+
if isinstance(value, dict):
|
|
585
|
+
merged = {**scope, **value}
|
|
586
|
+
return {
|
|
587
|
+
k: _collapse(v, merged) if k != "__comments__" else v
|
|
588
|
+
for k, v in value.items()
|
|
589
|
+
}
|
|
590
|
+
if isinstance(value, list):
|
|
591
|
+
return [_collapse(x, scope) for x in value]
|
|
592
|
+
return value
|
|
593
|
+
|
|
594
|
+
collapsed = {
|
|
595
|
+
k: v if k == "__comments__" else _collapse(v, self._data)
|
|
596
|
+
for k, v in self._data.items()
|
|
597
|
+
}
|
|
598
|
+
logger.debug("③ collapsed AST → %r", collapsed)
|
|
599
|
+
|
|
600
|
+
# ④ evaluate comprehensions --------------------------------------
|
|
601
|
+
collapsed = _eval_comprehensions(collapsed)
|
|
602
|
+
logger.debug("④ after comprehensions → %r", collapsed)
|
|
603
|
+
|
|
604
|
+
# ⑤ expand remaining f-strings with context ----------------------
|
|
605
|
+
def _eval_context_fstrings(obj: Any) -> Any:
|
|
606
|
+
if isinstance(obj, dict):
|
|
607
|
+
return {k: _eval_context_fstrings(v) for k, v in obj.items()}
|
|
608
|
+
if isinstance(obj, list):
|
|
609
|
+
return [_eval_context_fstrings(v) for v in obj]
|
|
610
|
+
if isinstance(obj, str) and (
|
|
611
|
+
obj.startswith('f"') or obj.startswith("f'")
|
|
612
|
+
):
|
|
613
|
+
try:
|
|
614
|
+
evaluated = _evaluate_f_string(
|
|
615
|
+
obj,
|
|
616
|
+
global_data=self._data,
|
|
617
|
+
local_data={},
|
|
618
|
+
context=context,
|
|
619
|
+
)
|
|
620
|
+
logger.debug(" – f-string %s -> %r", obj, evaluated)
|
|
621
|
+
return evaluated
|
|
622
|
+
except Exception as exc:
|
|
623
|
+
logger.debug(
|
|
624
|
+
" ✖ f-string %s failed (%s); leaving literal",
|
|
625
|
+
obj,
|
|
626
|
+
exc,
|
|
627
|
+
)
|
|
628
|
+
return obj
|
|
629
|
+
return obj
|
|
630
|
+
|
|
631
|
+
expanded = _eval_context_fstrings(collapsed)
|
|
632
|
+
logger.debug("⑤ after context f-str → %r", expanded)
|
|
633
|
+
|
|
634
|
+
# ⑥ strip surrounding quotes on string literals ------------------
|
|
635
|
+
final = _strip_quotes(expanded)
|
|
636
|
+
# Keep the rendered view serializable without overwriting the deferred
|
|
637
|
+
# expressions needed when the same Config is rendered again.
|
|
638
|
+
from ._legacy import _literal, _lookup
|
|
639
|
+
|
|
640
|
+
snapshot = deepcopy(self._ast)
|
|
641
|
+
values = final
|
|
642
|
+
for node in snapshot.lines:
|
|
643
|
+
if isinstance(node, SectionNode):
|
|
644
|
+
try:
|
|
645
|
+
values = _lookup(node.header.emit(), final)
|
|
646
|
+
except KeyError:
|
|
647
|
+
continue
|
|
648
|
+
assignments = node.contents
|
|
649
|
+
else:
|
|
650
|
+
assignments = [node]
|
|
651
|
+
for assignment in assignments:
|
|
652
|
+
identifier = getattr(assignment, "identifier", None)
|
|
653
|
+
if identifier is not None and identifier.value in values:
|
|
654
|
+
assignment.value = _literal(values[identifier.value])
|
|
655
|
+
self._rendered_source = snapshot.emit()
|
|
656
|
+
logger.debug("⭢ [render] returning → %r", final)
|
|
657
|
+
return final
|