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/_ast_nodes.py ADDED
@@ -0,0 +1,2089 @@
1
+ from typing import Any, Dict, List, Optional
2
+
3
+ import logging
4
+ import re
5
+ from lark import Tree
6
+
7
+ from ._make_static import make_static_section
8
+ from ._fstring import _evaluate_f_string, _lookup
9
+ from ._substitute import _substitute_vars
10
+ from ._expression import evaluate_expression_tree
11
+ from ._comprehension import iter_environments, _evaluate_comprehension
12
+
13
+
14
+ logger = logging.getLogger(__name__)
15
+ logger.setLevel(logging.DEBUG) # caller can override
16
+
17
+
18
+ class BaseNode:
19
+ def __init__(self):
20
+ self.meta = None # Parser Metadata
21
+ self.origin = None # Token or raw source string
22
+ self.value = None # Semantic value
23
+ self.resolved = None # Resolved value after substitution
24
+ self.__comments__ = [] # List of comments
25
+
26
+ def __str__(self) -> str:
27
+ return f"{self.__class__.__name__}(value={self.value})"
28
+
29
+ def __repr__(self) -> str:
30
+ if self.meta:
31
+ return (
32
+ f"{self.__class__.__name__}(value={self.value}, "
33
+ f"start_pos={self.meta.start_pos})"
34
+ )
35
+ else:
36
+ return f"{self.__class__.__name__}(value={self.value})"
37
+
38
+ def __eq__(self, other) -> bool:
39
+ """
40
+ Compare AST nodes to strings or other nodes by origin for fidelity in
41
+ tests.
42
+ """
43
+ # If comparing to a string, check origin equality
44
+ if isinstance(other, str):
45
+ return self.origin == other
46
+ # If comparing to another BaseNode, compare origins
47
+ if isinstance(other, BaseNode):
48
+ return self.origin == other.origin
49
+ return NotImplemented
50
+
51
+ def emit(self) -> str:
52
+ raise NotImplementedError(
53
+ f"emit() not implemented for {self.__class__.__name__}"
54
+ )
55
+
56
+ def evaluate(self) -> Any:
57
+ return self.resolved if self.resolved is not None else self.value
58
+
59
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
60
+ pass
61
+
62
+ def render(
63
+ self,
64
+ global_env: Dict,
65
+ local_env: Optional[Dict] = None,
66
+ context: Optional[Dict] = None,
67
+ ) -> str:
68
+ return str(self.resolved if self.resolved is not None else self.value)
69
+
70
+ def load(self):
71
+ pass
72
+
73
+
74
+ class LegacyExpressionNode(BaseNode):
75
+ """Keep deferred expressions verbatim until render is requested."""
76
+
77
+ def emit(self) -> str:
78
+ return self.origin
79
+
80
+
81
+ class StartNode(BaseNode):
82
+ def __init__(self, data, contents, origin, meta):
83
+ super().__init__()
84
+ self.lines = []
85
+ self.global_env = {}
86
+ self.data = data
87
+ self.contents = contents
88
+ self.origin = origin
89
+ self.meta = meta
90
+
91
+ def emit(self) -> str:
92
+ logger.debug("start.emit() triggered.")
93
+ lines: List[str] = []
94
+ from ._ast_nodes import (
95
+ TableArraySectionNode,
96
+ ) # ensure the name is in scope
97
+
98
+ def table_sections(path, table):
99
+ result = [f"[{path}]"]
100
+ nested = []
101
+ for key, assignment in table.data.items():
102
+ value = getattr(assignment, "value", assignment)
103
+ if isinstance(value, InlineTableNode):
104
+ nested.append((f"{path}.{key}", value))
105
+ else:
106
+ emitted = assignment.emit()
107
+ if table.origin:
108
+ comment = re.search(
109
+ rf"(?m)^\s*{re.escape(key)}\s*=.*?,?\s+(#[^\n]*)",
110
+ table.origin,
111
+ )
112
+ if comment:
113
+ emitted += " " + comment.group(1)
114
+ result.append(emitted)
115
+ for child_path, child in nested:
116
+ result.extend(["", *table_sections(child_path, child)])
117
+ if table.origin:
118
+ for comment in re.findall(r"(?m)^\s*(#[^\n]*)", table.origin):
119
+ if comment not in "\n".join(result):
120
+ result.append(comment)
121
+ return result
122
+
123
+ for line in self.lines:
124
+ # ── single-bracket sections ───────────────────────────
125
+ if isinstance(line, SectionNode):
126
+ header = line.header.emit()
127
+ lines.append(f"[{header}]")
128
+ nested = []
129
+ for content in line.contents:
130
+ if isinstance(content, AssignmentNode):
131
+ value = content.value
132
+ if isinstance(value, InlineTableNode) and "\n" in (
133
+ value.origin or ""
134
+ ):
135
+ nested.append(
136
+ (f"{header}.{content.identifier.value}", value)
137
+ )
138
+ else:
139
+ lines.append(content.emit())
140
+ elif isinstance(content, CommentNode):
141
+ lines.append(content.emit().strip())
142
+ for path, table in nested:
143
+ lines.extend(["", *table_sections(path, table)])
144
+
145
+ # ── double-bracket (table-array) sections ─────────────
146
+ elif isinstance(line, TableArraySectionNode):
147
+ header = line.header.emit()
148
+ lines.append(f"[[{header}]]")
149
+ for item in getattr(line, "body", []):
150
+ # only emit assignments and comments; skip untransformed
151
+ # Trees
152
+ if isinstance(item, AssignmentNode):
153
+ lines.append(item.emit())
154
+ elif isinstance(item, CommentNode):
155
+ lines.append(item.emit().strip())
156
+
157
+ # ── top-level assignments ─────────────────────────────
158
+ elif isinstance(line, AssignmentNode):
159
+ lines.append(line.emit())
160
+
161
+ # ── standalone comments ───────────────────────────────
162
+ elif isinstance(line, CommentNode):
163
+ lines.append(line.emit().strip())
164
+
165
+ # ── blank lines ───────────────────────────────────────
166
+ elif isinstance(line, NewlineNode):
167
+ lines.append("")
168
+
169
+ # ── anything else (should be rare) ────────────────────
170
+ else:
171
+ try:
172
+ emitted = line.emit()
173
+ if emitted:
174
+ lines.extend(emitted.split("\n"))
175
+ except Exception:
176
+ # swallow errors to avoid breaking dumps()
177
+ pass
178
+
179
+ return "\n".join(lines)
180
+
181
+ def resolve(
182
+ self,
183
+ global_env: Optional[Dict] = None,
184
+ local_env: Optional[Dict] = None,
185
+ ):
186
+ env = self.global_env if self.global_env else (global_env or {})
187
+ for line in self.lines:
188
+ line.resolve(env, local_env)
189
+ self.resolved = self.evaluate()
190
+
191
+ def evaluate(self) -> Dict:
192
+ result = {}
193
+ for line in self.lines:
194
+ if isinstance(line, SectionNode):
195
+ parts = line.header.value.split(".")
196
+ current_dict = result
197
+ for part in parts[:-1]:
198
+ current_dict = current_dict.setdefault(part, {})
199
+ current_dict[parts[-1]] = line.evaluate()
200
+ return result
201
+
202
+ def render(
203
+ self,
204
+ global_env: Optional[Dict] = None,
205
+ local_env: Optional[Dict] = None,
206
+ context: Optional[Dict] = None,
207
+ ) -> str:
208
+ logger.debug("start.render() triggered.")
209
+ return self.emit()
210
+
211
+
212
+ class SectionNode(BaseNode):
213
+ def __init__(self):
214
+ super().__init__()
215
+ self.leading_whitespace = None
216
+ self.lbrack = None
217
+ self.header = None
218
+ self.rbrack = None
219
+ self.trailing_whitespace = None
220
+ self.contents = []
221
+
222
+ def __str__(self) -> str:
223
+ return (
224
+ f"SectionNode(header={self.header.value if self.header else None})"
225
+ )
226
+
227
+ def emit(self) -> str:
228
+ logger.debug("SectionNode.emit() triggered.")
229
+ parts = []
230
+ if self.leading_whitespace:
231
+ parts.append(self.leading_whitespace.value)
232
+ parts.append(self.lbrack.value)
233
+ parts.append(self.header.emit())
234
+ parts.append(self.rbrack.value)
235
+ if self.trailing_whitespace:
236
+ parts.append(self.trailing_whitespace.value)
237
+ if self.__comments__:
238
+ parts.extend(self.__comments__)
239
+ parts.extend(c.emit() for c in self.contents)
240
+ return "\n".join(parts)
241
+
242
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
243
+ logger.debug("SectionNode.resolve() triggered.")
244
+ base_env = local_env or {}
245
+ # Pre-populate simple numeric assignments in local scope for header
246
+ # resolution
247
+ for content in self.contents:
248
+ if isinstance(content, AssignmentNode) and isinstance(
249
+ content.value, (IntegerNode, FloatNode)
250
+ ):
251
+ base_env[content.identifier.value] = content.value.evaluate()
252
+
253
+ # Resolve header (may generate multiple header_envs in comprehensions)
254
+ self.header.resolve(global_env, base_env)
255
+
256
+ self.resolved = {}
257
+ header_env_pairs = getattr(
258
+ self.header, "header_envs", [(self.header.resolved, {})]
259
+ )
260
+ for header_name, alias_env in header_env_pairs:
261
+ scope = {**base_env, **alias_env}
262
+ for line in self.contents:
263
+ line.resolve(global_env, scope)
264
+ if isinstance(line, AssignmentNode):
265
+ scope[line.identifier.value] = line.resolved
266
+ # Ensure alias bindings persist
267
+ for k, v in alias_env.items():
268
+ scope.setdefault(k, v)
269
+ self.resolved[header_name] = scope
270
+
271
+ self.value = self.resolved
272
+
273
+ def evaluate(self) -> Dict:
274
+ logger.debug("SectionNode.evaluate() triggered.")
275
+ result = {}
276
+ for content in self.contents:
277
+ if isinstance(content, AssignmentNode):
278
+ result[content.identifier.value] = content.evaluate()
279
+ elif isinstance(content, SectionNode):
280
+ result[content.header.value] = content.evaluate()
281
+ return result
282
+
283
+ def render(
284
+ self,
285
+ global_env: Dict,
286
+ local_env: Optional[Dict] = None,
287
+ context: Optional[Dict] = None,
288
+ ) -> str:
289
+ logger.debug("SectionNode.render() triggered.")
290
+ # handle comprehension expansion
291
+ if isinstance(self.header, ComprehensionHeaderNode):
292
+ produced = {}
293
+ new_nodes = []
294
+ start_lines = self.meta.parent.lines
295
+ my_idx = start_lines.index(self)
296
+ self.header.render(global_env, local_env or {}, context or {})
297
+ for hdr, alias_env in self.header.header_envs:
298
+ scope = {**alias_env}
299
+ for line in self.contents:
300
+ line.resolve(global_env, scope, context)
301
+ if isinstance(line, AssignmentNode):
302
+ scope[line.identifier.value] = line.evaluate()
303
+ produced[hdr] = scope
304
+ new_nodes.append(make_static_section(hdr, scope))
305
+ start_lines[my_idx : my_idx + 1] = new_nodes
306
+ global_env.update(produced)
307
+ return str(produced)
308
+
309
+ simple = {}
310
+ for line in self.contents:
311
+ line.resolve(global_env, simple)
312
+ if isinstance(line, AssignmentNode):
313
+ simple[line.identifier.value] = line.evaluate()
314
+ global_env[self.header.value] = simple
315
+ return str({self.header.value: simple})
316
+
317
+
318
+ class SectionNameNode(BaseNode):
319
+ def __init__(self):
320
+ super().__init__()
321
+ self.parts = [] # List of IDENTIFIER tokens
322
+ self.dots = [] # List of '.' tokens
323
+
324
+ def __str__(self) -> str:
325
+ return f"SectionNameNode({self.value})"
326
+
327
+ def emit(self) -> str:
328
+ if not self.parts:
329
+ return self.origin or self.value
330
+ parts = [self.parts[0].value]
331
+ for dot, part in zip(self.dots, self.parts[1:]):
332
+ parts.append(dot.value)
333
+ parts.append(part.value)
334
+ return "".join(parts)
335
+
336
+ def evaluate(self) -> str:
337
+ return self.value
338
+
339
+
340
+ class TableArraySectionNode(BaseNode):
341
+ def __init__(self):
342
+ super().__init__()
343
+ self.header = None # TableArrayHeaderNode or ComprehensionHeaderNode
344
+ self.body = [] # List of AssignmentNode, etc.
345
+
346
+ def __str__(self) -> str:
347
+ return (
348
+ f"TableArraySectionNode(header="
349
+ f"{self.header.value if self.header else None})"
350
+ )
351
+
352
+ def emit(self) -> str:
353
+ logger.debug("TableArraySectionNode.emit() triggered.")
354
+ parts = [f"[[{self.header.emit()}]]"]
355
+ if self.__comments__:
356
+ parts.extend(self.__comments__)
357
+ parts.extend(item.emit() for item in self.body)
358
+ return "\n".join(parts)
359
+
360
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
361
+ logger.debug("TableArraySectionNode.resolve() triggered.")
362
+ local_env = local_env or {}
363
+ for item in self.body:
364
+ if isinstance(item, AssignmentNode) and isinstance(
365
+ item.value, IntegerNode
366
+ ):
367
+ local_env[item.identifier.value] = item.value.evaluate()
368
+ self.header.resolve(global_env, local_env)
369
+ for item in self.body:
370
+ item.resolve(global_env, local_env)
371
+ self.resolved = self.evaluate()
372
+
373
+ def evaluate(self) -> Dict:
374
+ logger.debug("TableArraySectionNode.evaluate() triggered.")
375
+ result = {}
376
+ for line in self.lines:
377
+ if isinstance(line, SectionNode):
378
+ parts = line.header.value.split(".")
379
+ d = result
380
+ for part in parts[:-1]:
381
+ d = d.setdefault(part, {})
382
+ d[parts[-1]] = line.evaluate()
383
+ return result
384
+
385
+ def render(
386
+ self,
387
+ global_env: Dict,
388
+ local_env: Optional[Dict] = None,
389
+ context: Optional[Dict] = None,
390
+ ) -> str:
391
+ logger.debug("TableArraySectionNode.render() triggered.")
392
+ parts = [
393
+ f"{item.identifier.value}: {item.render()}"
394
+ for item in self.body
395
+ if isinstance(item, AssignmentNode)
396
+ ]
397
+ return "{" + ", ".join(parts) + "}"
398
+
399
+
400
+ class TableArrayHeaderNode(BaseNode):
401
+ """
402
+ Represents a [[…]] table‑array section header.
403
+
404
+ • .origin holds the exact raw header text (including newlines and
405
+ indentation)
406
+ • .value holds the clean logical name (used as the mapping key)
407
+ """
408
+
409
+ def __init__(
410
+ self, origin: Optional[str] = None, value: Optional[str] = None
411
+ ):
412
+ super().__init__()
413
+ if origin is not None:
414
+ self.origin = origin
415
+ if value is not None:
416
+ self.value = value
417
+
418
+ def emit(self) -> str:
419
+ logger.debug("TableArrayHeaderNode.emit() triggered.")
420
+ # Emit exactly what was parsed—preserving newlines & indent.
421
+ return self.origin
422
+
423
+ def evaluate(self) -> str:
424
+ logger.debug("TableArrayHeaderNode.evaluate() triggered.")
425
+ # Returns the logical header name.
426
+ return self.value
427
+
428
+
429
+ class ComprehensionHeaderNode(BaseNode):
430
+ def __init__(self):
431
+ super().__init__()
432
+ self.header_expr = None # Expression node (e.g., FStringNode)
433
+ self.clauses = None # ComprehensionClausesNode
434
+
435
+ def emit(self) -> str:
436
+ logger.debug("ComprehensionHeaderNode.emit() triggered.")
437
+ return self.origin
438
+
439
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
440
+ logger.debug("ComprehensionHeaderNode.resolve() triggered.")
441
+ self._evaluate(global_env or {}, local_env or {}, {})
442
+
443
+ def render(
444
+ self,
445
+ global_env: Dict,
446
+ local_env: Optional[Dict] = None,
447
+ context: Optional[Dict] = None,
448
+ ):
449
+ logger.debug("ComprehensionHeaderNode.render() triggered.")
450
+ self._evaluate(global_env, local_env or {}, context or {})
451
+
452
+ def _evaluate(self, g: Dict, local_env: Dict, ctx: Dict):
453
+ logger.debug("ComprehensionHeaderNode._evaluate() triggered.")
454
+ self.header_envs: List[tuple[str, dict]] = []
455
+
456
+ for env in iter_environments(self.clauses, g, local_env, ctx):
457
+ logger.debug(f"ComprehensionHeaderNode._evaluate() env: {env}.")
458
+ scope = {**local_env, **env}
459
+ if ctx is None:
460
+ self.header_expr.resolve(g, scope)
461
+ else:
462
+ self.header_expr.render(g, scope, ctx)
463
+
464
+ header_value = (
465
+ self.header_expr.evaluate()
466
+ if hasattr(self.header_expr, "evaluate")
467
+ else self.header_expr
468
+ )
469
+ self.header_envs.append((header_value, env))
470
+ logger.debug(
471
+ f"ComprehensionHeaderNode.header_envs {self.header_envs}."
472
+ )
473
+
474
+ if not self.header_envs:
475
+ self.resolved = []
476
+ elif len(self.header_envs) > 1:
477
+ self.resolved = [h for h, _ in self.header_envs]
478
+ else:
479
+ self.resolved = self.header_envs[0][0]
480
+
481
+ self.value = self.resolved
482
+
483
+
484
+ class AssignmentNode(BaseNode):
485
+ def __init__(self):
486
+ super().__init__()
487
+ self.leading_whitespace = None
488
+ self.trailing_whitespace = None
489
+ self.equals_leading_whitespace = None # Whitespace before '='
490
+ self.equals_trailing_whitespace = None # Whitespace after '='
491
+ self.identifier = None
492
+ self.colon = None
493
+ self.type_annotation = None
494
+ self.equals = None
495
+ self.value = None
496
+ self.inline_comment = None
497
+
498
+ def emit(self) -> str:
499
+ logger.debug("AssignmentNode.emit() triggered.")
500
+ parts: List[str] = []
501
+ # leading whitespace and identifier
502
+ if self.leading_whitespace:
503
+ parts.append(self.leading_whitespace.value)
504
+ parts.append(self.identifier.value)
505
+ # type annotation if present
506
+ if self.type_annotation:
507
+ parts.append(self.colon.value)
508
+ parts.append(" ")
509
+ parts.append(self.type_annotation.value)
510
+ # equals with surrounding spaces
511
+ parts.append(" ")
512
+ parts.append(self.equals.value if self.equals else "=")
513
+ parts.append(" ")
514
+ # emit the right-hand side value (arrays, nodes, or primitives)
515
+ if hasattr(self.value, "emit"):
516
+ val_text = self.value.emit()
517
+ else:
518
+ val_text = str(self.value)
519
+ # fallback if emit returned None
520
+ if val_text is None:
521
+ val_text = getattr(self.value, "origin", "")
522
+ parts.append(val_text)
523
+ # optional trailing whitespace
524
+ if self.trailing_whitespace:
525
+ parts.append(self.trailing_whitespace.value)
526
+ # inline comment on the assignment
527
+ if self.inline_comment:
528
+ parts.append(self.inline_comment.value)
529
+ return "".join(parts)
530
+
531
+ def __str__(self) -> str:
532
+ return (
533
+ f"AssignmentNode("
534
+ f"{self.identifier.value if self.identifier else None})"
535
+ )
536
+
537
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
538
+ """
539
+ Resolve the assignment's right‑hand side, handling both AST nodes,
540
+ folded-expression strings, and manual folded-expression AST values.
541
+ """
542
+ local_env = local_env or {}
543
+ logger.debug("AssignmentNode.resolve() triggered.")
544
+ # ── Handle folded-expression AST nodes (e.g., <(3 + 4)>) ──
545
+ if isinstance(self.value, FoldedExpressionNode):
546
+ # Extract inner arithmetic expression and evaluate safely
547
+ expr = self.value.origin[2:-2].strip()
548
+ from ._eval import safe_eval
549
+
550
+ try:
551
+ self.resolved = safe_eval(expr, local_env)
552
+ except Exception:
553
+ # Fallback to original origin if evaluation fails
554
+ self.resolved = self.value.origin
555
+ print(
556
+ (
557
+ f"[DEBUG ASSIGNMENT RESOLVE folded expr AST]: "
558
+ f"{self.identifier.value} -> {self.resolved}"
559
+ )
560
+ )
561
+ return
562
+
563
+ # ── Handle manual folded-expression strings (e.g., '<(3 + 4)>') ──
564
+ if (
565
+ isinstance(self.value, str)
566
+ and self.value.startswith("<(")
567
+ and self.value.endswith(")>")
568
+ ):
569
+ expr = self.value[2:-2].strip()
570
+ from ._eval import safe_eval
571
+
572
+ try:
573
+ self.resolved = safe_eval(expr, local_env)
574
+ except Exception:
575
+ self.resolved = self.value
576
+ print(
577
+ (
578
+ f"[DEBUG ASSIGNMENT RESOLVE folded expr]: "
579
+ f"{self.identifier.value} -> {self.resolved}"
580
+ )
581
+ )
582
+ return
583
+
584
+ # ── Delegate to AST node resolution if available ──
585
+ print("[resolve]:", global_env, local_env)
586
+ if hasattr(self.value, "resolve"):
587
+ self.value.resolve(global_env, local_env)
588
+ if (
589
+ hasattr(self.value, "resolved")
590
+ and self.value.resolved is not None
591
+ ):
592
+ self.resolved = self.value.resolved
593
+ else:
594
+ self.resolved = (
595
+ self.value.evaluate()
596
+ if hasattr(self.value, "evaluate")
597
+ else self.value
598
+ )
599
+ else:
600
+ # Plain Python literal (int, float, bool, None, etc.)
601
+ self.resolved = self.value
602
+
603
+ print(
604
+ (
605
+ f"[DEBUG ASSIGNMENT RESOLVE]: {self.identifier.value} -> "
606
+ f"{self.resolved}"
607
+ )
608
+ )
609
+
610
+ def evaluate(self):
611
+ logger.debug("AssignmentNode.evaluate() triggered.")
612
+ return (
613
+ self.resolved
614
+ if self.resolved is not None
615
+ else (
616
+ self.value.evaluate()
617
+ if hasattr(self.value, "evaluate")
618
+ else self.value
619
+ )
620
+ )
621
+
622
+ def render(
623
+ self,
624
+ global_env: Dict,
625
+ local_env: Optional[Dict] = None,
626
+ context: Optional[Dict] = None,
627
+ ) -> str:
628
+ logger.debug("AssignmentNode.render() triggered.")
629
+ return self.value.render(global_env, local_env or {}, context or {})
630
+
631
+
632
+ class CommentNode(BaseNode):
633
+ def __init__(self):
634
+ super().__init__()
635
+
636
+ def emit(self) -> str:
637
+ return self.value + "\n"
638
+
639
+ def evaluate(self) -> None:
640
+ return None
641
+
642
+
643
+ class NewlineNode(BaseNode):
644
+ def __init__(self):
645
+ super().__init__()
646
+ self.value = "\n"
647
+ self.origin = "\n"
648
+
649
+ def emit(self) -> str:
650
+ return self.value
651
+
652
+ def evaluate(self) -> None:
653
+ return None
654
+
655
+
656
+ class IntegerNode(BaseNode):
657
+ def __init__(self):
658
+ super().__init__()
659
+
660
+ def emit(self) -> str:
661
+ return str(self.value)
662
+
663
+ def evaluate(self) -> int:
664
+ if self.resolved is not None:
665
+ return self.resolved
666
+ try:
667
+ return int(self.value, 0) # Auto-detect base for 0o, 0x, 0b
668
+ except ValueError as e:
669
+ print(
670
+ (
671
+ f"[DEBUG INTEGERNODE EVALUATE ERROR]: Invalid integer "
672
+ f"{self.value}: {e}"
673
+ )
674
+ )
675
+ return self.value
676
+
677
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
678
+ try:
679
+ if isinstance(self.value, str):
680
+ self.resolved = int(
681
+ self.value, 0
682
+ ) # Auto-detect base for strings
683
+ else:
684
+ self.resolved = int(
685
+ self.value
686
+ ) # Direct conversion for non-strings (e.g., int)
687
+ self.value = self.resolved
688
+ except ValueError as e:
689
+ print(
690
+ (
691
+ f"[DEBUG INTEGERNODE RESOLVE ERROR]: Invalid integer "
692
+ f"{self.value}: {e}"
693
+ )
694
+ )
695
+ self.resolved = self.value
696
+ print(f"[DEBUG INTEGERNODE RESOLVE]: {self.value} -> {self.resolved}")
697
+
698
+
699
+ class BooleanNode(BaseNode):
700
+ def __init__(self):
701
+ super().__init__()
702
+
703
+ def emit(self) -> str:
704
+ return str(self.value).lower()
705
+
706
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
707
+ self.resolved = self.value.lower() == "true"
708
+ print(f"[DEBUG BOOLEANNODE RESOLVE]: {self.value} -> {self.resolved}")
709
+
710
+ def evaluate(self) -> bool:
711
+ return (
712
+ self.resolved
713
+ if self.resolved is not None
714
+ else (self.value.lower() == "true")
715
+ )
716
+
717
+
718
+ class NullNode(BaseNode):
719
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
720
+ self.resolved = None
721
+ print(f"[DEBUG NULLNODE RESOLVE]: {self.value} -> {self.resolved}")
722
+
723
+ def emit(self) -> str:
724
+ return "null"
725
+
726
+ def evaluate(self):
727
+ return None
728
+
729
+
730
+ class FoldedExpressionNode(BaseNode):
731
+ def __init__(self):
732
+ super().__init__()
733
+ self.content_tree: Optional[Tree] = None
734
+
735
+ def emit(self) -> str:
736
+ logger.debug("FoldedExpressionNode.emit() triggered.")
737
+ # Ensure we always return a string, even if origin was replaced by an
738
+ # int
739
+ return str(self.origin)
740
+
741
+ def resolve(
742
+ self,
743
+ global_env: Dict,
744
+ local_env: Optional[Dict] = None,
745
+ context: Optional[Dict] = None,
746
+ ):
747
+ """
748
+ Phase 2: static folding + placeholder deferral
749
+ - Substitutes @{…} and %{…} immediately.
750
+ - Leaves ${…} intact and wraps the result in an f-string if any remain.
751
+ """
752
+
753
+ logger.debug("FoldedExpressionNode.resolve() triggered.")
754
+ # Always pass an empty dict for `context` here so that ${…} tokens
755
+ # get preserved and trigger the f-string branch in
756
+ # evaluate_expression_tree.
757
+ static_ctx: Dict[str, Any] = {}
758
+
759
+ # Evaluate without real context, deferring ${…}
760
+ self.resolved = evaluate_expression_tree(
761
+ self.content_tree, global_env, local_env or {}, static_ctx
762
+ )
763
+
764
+ # Update origin and value so that subsequent .emit() or lookup
765
+ # returns the folded result (e.g. 'f"...${auth_token}"')
766
+ self.origin = self.resolved
767
+ self.value = self.resolved
768
+
769
+ def render(
770
+ self,
771
+ global_env: Dict,
772
+ local_env: Optional[Dict] = None,
773
+ context: Optional[Dict] = None,
774
+ ) -> Any:
775
+ # Phase 3: final inject of context placeholders
776
+ final = evaluate_expression_tree(
777
+ self.content_tree, global_env, local_env or {}, context or {}
778
+ )
779
+
780
+ logger.debug("FoldedExpressionNode.render() triggered.")
781
+ return final
782
+
783
+ def evaluate(self) -> Any:
784
+ logger.debug("FoldedExpressionNode.evaluate() triggered.")
785
+ # Used by collapse; prefer resolved or fallback to origin
786
+ return self.resolved if self.resolved is not None else self.origin
787
+
788
+
789
+ class InClauseNode(BaseNode):
790
+ def __init__(self):
791
+ super().__init__()
792
+ self.keyword = None # The 'in' keyword
793
+
794
+ def __str__(self) -> str:
795
+ return f"InClauseNode(keyword={self.keyword})"
796
+
797
+ def emit(self) -> str:
798
+ return self.origin
799
+
800
+ def evaluate(self) -> str:
801
+ return self.keyword
802
+
803
+
804
+ class AliasClauseNode(BaseNode):
805
+ def __init__(self):
806
+ super().__init__()
807
+ self.keyword = None # The 'as' keyword
808
+ self.scoped_var = None # Scoped variable (e.g., '%{x}')
809
+
810
+ def __str__(self) -> str:
811
+ return (
812
+ f"AliasClauseNode(keyword={self.keyword}, "
813
+ f"scoped_var={self.scoped_var})"
814
+ )
815
+
816
+ def emit(self) -> str:
817
+ logger.debug("AliasClauseNode.emit() triggered.")
818
+
819
+ """
820
+ Emit the alias clause exactly as parsed, preserving the 'as' keyword
821
+ and the scoped variable.
822
+ """
823
+ return self.origin
824
+
825
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
826
+ """
827
+ During the static *resolve* phase we only capture the alias *name*.
828
+ The actual value is injected at runtime inside
829
+ _comprehension.iter_environments(), once the anchor item is known.
830
+ """
831
+ logger.debug("AliasClauseNode.resolve() triggered.")
832
+ local_env = local_env or {}
833
+
834
+ # ➜ extract the identifier inside %{…}
835
+ raw = getattr(self.scoped_var, "origin", "") or getattr(
836
+ self.scoped_var, "value", ""
837
+ )
838
+ if raw.startswith("%{") and raw.endswith("}"):
839
+ alias_name = raw[2:-1].split(".")[0] # drop %{…} and ignore dots
840
+ else: # (unexpected but safe)
841
+ alias_name = str(self.scoped_var)
842
+
843
+ self.resolved = alias_name # plain string – e.g. "package"
844
+ self.value = alias_name # let callers read .value directly
845
+ return alias_name
846
+
847
+ def evaluate(self) -> Any:
848
+ logger.debug("AliasClauseNode.evaluate() triggered.")
849
+ return self.resolved if self.resolved is not None else self.scoped_var
850
+
851
+
852
+ class PairExprNode(BaseNode):
853
+ def __init__(self):
854
+ super().__init__()
855
+ # Key expression (e.g., (SingleQuotedStringNode,
856
+ # TripleQuotedStringNode, BacktickStringNode, FStringNode,
857
+ # TripleBacktickStringNode), StringExprNode)
858
+ self.key = None
859
+ self.value = None # Value expression
860
+
861
+ def __str__(self) -> str:
862
+ return f"PairExprNode(key={self.key}, value={self.value})"
863
+
864
+ def emit(self) -> str:
865
+ return self.origin
866
+
867
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
868
+ self.key.resolve(global_env, local_env)
869
+ self.value.resolve(global_env, local_env)
870
+ self.resolved = (self.key.resolved, self.value.resolved)
871
+ self.value = self.resolved
872
+
873
+ def evaluate(self) -> tuple:
874
+ return (self.key.evaluate(), self.value.evaluate())
875
+
876
+ def render(
877
+ self,
878
+ global_env: Dict,
879
+ local_env: Optional[Dict] = None,
880
+ context: Optional[Dict] = None,
881
+ ) -> str:
882
+ return f"{self.key.render()}: {self.value.render()}"
883
+
884
+
885
+ class DottedExprNode(BaseNode):
886
+ def __init__(self):
887
+ super().__init__()
888
+ self.dotted_value = None # Full dotted string, e.g. "package.active"
889
+
890
+ def __str__(self) -> str:
891
+ return f"DottedExprNode(dotted_value={self.dotted_value})"
892
+
893
+ def emit(self) -> str:
894
+ return self.origin
895
+
896
+ def resolve(
897
+ self,
898
+ global_env: Dict[str, Any],
899
+ local_env: Optional[Dict[str, Any]] = None,
900
+ ):
901
+ local_env = local_env or {}
902
+
903
+ # Walk a dotted path through a mapping (dict-like or objects with
904
+ # attrs).
905
+ def _dig(src, path: str):
906
+ cur = src
907
+ for part in path.split("."):
908
+ if isinstance(cur, dict) and part in cur:
909
+ cur = cur[part]
910
+ elif hasattr(cur, part):
911
+ cur = getattr(cur, part)
912
+ else:
913
+ return None
914
+ return cur
915
+
916
+ result = _dig(local_env, self.dotted_value)
917
+ if result is None:
918
+ result = _dig(global_env, self.dotted_value)
919
+
920
+ self.resolved = result
921
+ # If nothing found, leave the original dotted string as a fallback
922
+ self.value = result if result is not None else self.dotted_value
923
+
924
+ def evaluate(self) -> Any:
925
+ return (
926
+ self.resolved if self.resolved is not None else self.dotted_value
927
+ )
928
+
929
+
930
+ class ComprehensionClauseNode(BaseNode):
931
+ def __init__(self):
932
+ super().__init__()
933
+ self.loop_vars = [] # List of loop variables
934
+ self.iterable = None # Iterable expression
935
+ self.conditions = [] # Condition expressions
936
+
937
+ def __str__(self) -> str:
938
+ vars_str = " ".join(str(v) for v in self.loop_vars)
939
+ iter_str = str(self.iterable) if self.iterable else ""
940
+ cond_str = (
941
+ " ".join(str(c) for c in self.conditions)
942
+ if self.conditions
943
+ else ""
944
+ )
945
+ result = f"for {vars_str} in {iter_str}"
946
+ if cond_str:
947
+ result += f" if {cond_str}"
948
+ return result
949
+
950
+ def emit(self) -> str:
951
+ # Emit exactly the stored origin, with no extra whitespace
952
+ return self.origin
953
+
954
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
955
+ local_env = local_env or {}
956
+ for var in self.loop_vars:
957
+ if isinstance(var, AliasClauseNode):
958
+ var.resolve(global_env, local_env)
959
+ local_env[var.value] = var.resolved
960
+ if hasattr(self.iterable, "resolve"):
961
+ self.iterable.resolve(global_env, local_env)
962
+ iterable_resolved = self.iterable.resolved
963
+ else:
964
+ iterable_resolved = self.iterable
965
+ for cond in self.conditions:
966
+ if hasattr(cond, "resolve"):
967
+ cond.resolve(global_env, local_env)
968
+ self.resolved = {
969
+ "loop_vars": [
970
+ var.resolved
971
+ for var in self.loop_vars
972
+ if isinstance(var, AliasClauseNode)
973
+ ],
974
+ "iterable": iterable_resolved,
975
+ "conditions": [cond.resolved for cond in self.conditions],
976
+ }
977
+ self.value = self.resolved
978
+
979
+ def evaluate(self) -> Dict:
980
+ return {
981
+ "loop_vars": [var.evaluate() for var in self.loop_vars],
982
+ "iterable": self.iterable.evaluate(),
983
+ "conditions": [cond.evaluate() for cond in self.conditions],
984
+ }
985
+
986
+ def render(
987
+ self,
988
+ global_env: Dict,
989
+ local_env: Optional[Dict] = None,
990
+ context: Optional[Dict] = None,
991
+ ) -> str:
992
+ vars_str = ", ".join(var.render() for var in self.loop_vars)
993
+ iter_str = self.iterable.render()
994
+ cond_str = ", ".join(cond.render() for cond in self.conditions)
995
+ result = f"for {vars_str} in {iter_str}"
996
+ if cond_str:
997
+ result += f" if {cond_str}"
998
+ return result
999
+
1000
+
1001
+ class ComprehensionClausesNode(BaseNode):
1002
+ def __init__(self):
1003
+ super().__init__()
1004
+ self.clauses = [] # List of ComprehensionClauseNode
1005
+
1006
+ def __str__(self) -> str:
1007
+ return f"ComprehensionClausesNode(clauses={len(self.clauses)})"
1008
+
1009
+ def emit(self) -> str:
1010
+ return self.origin
1011
+
1012
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
1013
+ for clause in self.clauses:
1014
+ clause.resolve(global_env, local_env)
1015
+ self.resolved = [clause.resolved for clause in self.clauses]
1016
+ self.value = self.resolved
1017
+
1018
+ def evaluate(self) -> List:
1019
+ return [clause.evaluate() for clause in self.clauses]
1020
+
1021
+ def render(
1022
+ self,
1023
+ global_env: Dict,
1024
+ local_env: Optional[Dict] = None,
1025
+ context: Optional[Dict] = None,
1026
+ ) -> str:
1027
+ return " ".join(clause.render() for clause in self.clauses)
1028
+
1029
+
1030
+ class StringExprNode(BaseNode):
1031
+ """
1032
+ Represents a concatenation expression like
1033
+ "%{rootDir}" + "/" + "%{name}"
1034
+ Resolves each fragment individually and joins them into a single string.
1035
+ """
1036
+
1037
+ def __init__(self):
1038
+ super().__init__()
1039
+ self.parts: list[Any] = []
1040
+
1041
+ def render(self, global_env, local_env=None, context=None):
1042
+ values = []
1043
+ for part in self.parts:
1044
+ if isinstance(part, (FStringNode, ContextScopedVarNode)):
1045
+ value = part.render(global_env, local_env, context)
1046
+ else:
1047
+ part.resolve(global_env, local_env)
1048
+ value = part.evaluate()
1049
+ if isinstance(value, str) and value.startswith(('"', "'")):
1050
+ from ._utils import unquote
1051
+
1052
+ value = unquote(value)
1053
+ values.append(value)
1054
+ self.resolved = (
1055
+ values[0] if len(values) == 1 else "".join(map(str, values))
1056
+ )
1057
+ self.value = self.resolved
1058
+ return self.resolved
1059
+
1060
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
1061
+ """
1062
+ Resolve a concatenation expression into a plain Python value.
1063
+ - If there are multiple parts, build a Python f-string that
1064
+ interpolates any scoped variables and then evaluate it.
1065
+ - If there's exactly one part, just resolve that node directly.
1066
+ """
1067
+ from ._fstring import _evaluate_f_string
1068
+ from ._ast_nodes import (
1069
+ LocalScopedVarNode,
1070
+ GlobalScopedVarNode,
1071
+ SingleQuotedStringNode,
1072
+ )
1073
+
1074
+ local_env = local_env or {}
1075
+
1076
+ # Helper to strip quotes from a SingleQuotedStringNode
1077
+ def _lit_text(node: SingleQuotedStringNode) -> str:
1078
+ return node.origin.strip("\"'") # drop surrounding quotes
1079
+
1080
+ # -- multiple parts: build and eval an f-string --
1081
+ if len(self.parts) > 1:
1082
+ segments: list[str] = []
1083
+ for part in self.parts:
1084
+ if isinstance(part, LocalScopedVarNode) or isinstance(
1085
+ part, GlobalScopedVarNode
1086
+ ):
1087
+ # strip the leading marker (%{ or @{) and trailing }
1088
+ inner = part.origin
1089
+ segments.append(f"{inner}")
1090
+ elif isinstance(part, SingleQuotedStringNode):
1091
+ segments.append(_lit_text(part))
1092
+ else:
1093
+ # resolve any other node to its Python value
1094
+ part.resolve(global_env, local_env)
1095
+ val = (
1096
+ part.resolved
1097
+ if hasattr(part, "resolved")
1098
+ else part.value
1099
+ )
1100
+ segments.append(str(val))
1101
+
1102
+ # build a quoted Python f-string, e.g. f"{module.name}.py"
1103
+ fstring = 'f"' + "".join(segments) + '"'
1104
+ # evaluate via our helper
1105
+ self.resolved = _evaluate_f_string(
1106
+ fstring,
1107
+ global_data=global_env,
1108
+ local_data=local_env,
1109
+ context={},
1110
+ )
1111
+ self.value = self.resolved
1112
+ return
1113
+
1114
+ # -- single part: just resolve that node directly --
1115
+ single = self.parts[0]
1116
+ single.resolve(global_env, local_env)
1117
+ val = getattr(single, "resolved", None)
1118
+ if val is None:
1119
+ # fallback to its literal or origin if nothing resolved
1120
+ val = single.value if hasattr(single, "value") else single.origin
1121
+ self.resolved = val
1122
+ self.value = self.resolved
1123
+
1124
+ def evaluate(self) -> Any:
1125
+ return self.resolved if self.resolved is not None else ""
1126
+
1127
+ def emit(self) -> str:
1128
+ # If resolved, emit as a quoted string
1129
+ if self.resolved is not None:
1130
+ s = str(self.resolved)
1131
+ if not (s.startswith('"') or s.startswith("'")):
1132
+ s = f'"{s}"'
1133
+ return s
1134
+ # Before resolution, emit original parts
1135
+ return "".join(
1136
+ p.emit() if hasattr(p, "emit") else str(p) for p in self.parts
1137
+ )
1138
+
1139
+
1140
+ class ListComprehensionNode(BaseNode):
1141
+ def __init__(self):
1142
+ super().__init__()
1143
+ self.header_expr = None # Expression for list items
1144
+ self.clauses = None # ComprehensionClausesNode
1145
+
1146
+ def __str__(self) -> str:
1147
+ return f"ListComprehensionNode(expr={self.header_expr})"
1148
+
1149
+ def emit(self) -> str:
1150
+ return self.origin
1151
+
1152
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
1153
+ self.header_expr.resolve(global_env, local_env)
1154
+ if self.clauses:
1155
+ self.clauses.resolve(global_env, local_env)
1156
+ self.resolved = _evaluate_comprehension(self, global_env)
1157
+ self.value = self.resolved
1158
+
1159
+ def evaluate(self) -> List:
1160
+ return self.resolved if self.resolved is not None else []
1161
+
1162
+ def render(
1163
+ self,
1164
+ global_env: Dict,
1165
+ local_env: Optional[Dict] = None,
1166
+ context: Optional[Dict] = None,
1167
+ ) -> str:
1168
+ return f"[{', '.join(str(item) for item in self.evaluate())}]"
1169
+
1170
+
1171
+ class DictComprehensionNode(BaseNode):
1172
+ def __init__(self):
1173
+ super().__init__()
1174
+ self.pair = None # PairExprNode
1175
+ self.loop_var = None # Variable identifier
1176
+ self.iterable = None # Iterable expression
1177
+ self.condition = None # Optional condition expression
1178
+
1179
+ def __str__(self) -> str:
1180
+ return f"DictComprehensionNode(pair={self.pair})"
1181
+
1182
+ def emit(self) -> str:
1183
+ return self.origin
1184
+
1185
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
1186
+ self.pair.resolve(global_env, local_env)
1187
+ self.iterable.resolve(global_env, local_env)
1188
+ if self.condition:
1189
+ self.condition.resolve(global_env, local_env)
1190
+ self.resolved = _evaluate_comprehension(self, global_env)
1191
+ self.value = self.resolved
1192
+
1193
+ def evaluate(self) -> Dict:
1194
+ return self.resolved if self.resolved is not None else {}
1195
+
1196
+ def render(
1197
+ self,
1198
+ global_env: Dict,
1199
+ local_env: Optional[Dict] = None,
1200
+ context: Optional[Dict] = None,
1201
+ ) -> str:
1202
+ return (
1203
+ "{"
1204
+ + ", ".join(f"{k}: {v}" for k, v in self.evaluate().items())
1205
+ + "}"
1206
+ )
1207
+
1208
+
1209
+ class InlineTableComprehensionNode(BaseNode):
1210
+ def __init__(self):
1211
+ super().__init__()
1212
+ self.pair = None # PairExprNode
1213
+ self.loop_var = None # Variable identifier
1214
+ self.iterable = None # Iterable expression
1215
+ self.condition = None # Optional condition expression
1216
+
1217
+ def __str__(self) -> str:
1218
+ return f"InlineTableComprehensionNode(pair={self.pair})"
1219
+
1220
+ def emit(self) -> str:
1221
+ return self.origin
1222
+
1223
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
1224
+ self.pair.resolve(global_env, local_env)
1225
+ self.iterable.resolve(global_env, local_env)
1226
+ if self.condition:
1227
+ self.condition.resolve(global_env, local_env)
1228
+ self.resolved = _evaluate_comprehension(self, global_env)
1229
+ self.value = self.resolved
1230
+
1231
+ def evaluate(self) -> Dict:
1232
+ return self.resolved if self.resolved is not None else {}
1233
+
1234
+ def render(
1235
+ self,
1236
+ global_env: Dict,
1237
+ local_env: Optional[Dict] = None,
1238
+ context: Optional[Dict] = None,
1239
+ ) -> str:
1240
+ return (
1241
+ "{"
1242
+ + ", ".join(f"{k}: {v}" for k, v in self.evaluate().items())
1243
+ + "}"
1244
+ )
1245
+
1246
+
1247
+ class ValueNode(BaseNode):
1248
+ def __init__(self):
1249
+ super().__init__()
1250
+ self.value = None # Wrapped value (IntegerNode, StringNode, …)
1251
+ self.comment = None
1252
+ self.inline_comment = (
1253
+ None # Holds Token('INLINE_COMMENT', …) – includes leading spaces
1254
+ )
1255
+ # True when a ',' token directly followed this item in source
1256
+ self.has_comma = False
1257
+
1258
+ def emit(self) -> str:
1259
+ """Return the exact textual representation for round‑trip
1260
+ serialisation.
1261
+ """
1262
+ # ── comment‑only line ───────────────────────────────────────────
1263
+ if self.value is None:
1264
+ txt = self.inline_comment.value.strip()
1265
+ if self.has_comma:
1266
+ txt += ","
1267
+ return txt
1268
+
1269
+ # ── regular value (may have inline comment) ────────────────────
1270
+ base = (
1271
+ self.value.emit()
1272
+ if hasattr(self.value, "emit")
1273
+ else str(self.value)
1274
+ )
1275
+ if self.has_comma:
1276
+ base += ","
1277
+ if self.inline_comment:
1278
+ base += self.inline_comment.value # already holds leading spaces
1279
+ return base
1280
+
1281
+ def __str__(self):
1282
+ ic = self.inline_comment.value if self.inline_comment else None
1283
+ return (
1284
+ f"ValueNode(value={self.value}, inline_comment={ic}, "
1285
+ f"has_comma={self.has_comma})"
1286
+ )
1287
+
1288
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
1289
+ if hasattr(self.value, "resolve"):
1290
+ self.value.resolve(global_env, local_env)
1291
+ self.resolved = self.value.resolved
1292
+ else:
1293
+ self.resolved = self.value
1294
+
1295
+ def evaluate(self):
1296
+ return (
1297
+ self.value.evaluate()
1298
+ if hasattr(self.value, "evaluate")
1299
+ else self.value
1300
+ )
1301
+
1302
+ def render(
1303
+ self,
1304
+ global_env: Dict,
1305
+ local_env: Optional[Dict] = None,
1306
+ context: Optional[Dict] = None,
1307
+ ):
1308
+ return (
1309
+ self.value.render()
1310
+ if hasattr(self.value, "render")
1311
+ else str(self.value)
1312
+ )
1313
+
1314
+
1315
+ class SLArrayItemNode(ValueNode):
1316
+ """
1317
+ Represents an item in a single-line array, preserving value, inline
1318
+ comments, and comma.
1319
+ """
1320
+
1321
+ def __init__(self):
1322
+ super().__init__()
1323
+ # Already inherits value, inline_comment, and has_comma from ValueNode
1324
+
1325
+
1326
+ class MLArrayItemNode(ValueNode):
1327
+ """
1328
+ Represents an item in a multi-line array, preserving value, inline
1329
+ comments, and comma.
1330
+ """
1331
+
1332
+ def __init__(self):
1333
+ super().__init__()
1334
+ # Already inherits value, inline_comment, and has_comma from ValueNode
1335
+
1336
+
1337
+ class InlineTableNode(BaseNode):
1338
+ def __init__(self):
1339
+ super().__init__()
1340
+ self.data = {}
1341
+
1342
+ def emit(self) -> str:
1343
+ if self.origin and "#" in self.origin:
1344
+ return self.origin
1345
+ emit_items = []
1346
+ for key, value in self.data.items():
1347
+ if isinstance(value, AssignmentNode):
1348
+ item = value.emit()
1349
+ print(f"[DEBUG INLINE_TABLE EMIT]: {key} -> {item}")
1350
+ emit_items.append(item)
1351
+ else:
1352
+ value_str = (
1353
+ value.emit() if hasattr(value, "emit") else str(value)
1354
+ )
1355
+ emit_items.append(f"{key}={value_str}")
1356
+ result = f"{{{', '.join(emit_items)}}}"
1357
+ print(f"[DEBUG INLINE_TABLE EMIT RESULT]: {result}")
1358
+ return result
1359
+
1360
+ def __str__(self) -> str:
1361
+ return f"InlineTableNode(data={len(self.data)})"
1362
+
1363
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
1364
+ local_env = dict(local_env or {})
1365
+ merged = {}
1366
+ for key, value in self.data.items():
1367
+ if key == "<<":
1368
+ from ._legacy import _lookup
1369
+
1370
+ reference = (
1371
+ value.value if isinstance(value, AssignmentNode) else value
1372
+ )
1373
+ inherited = _lookup(
1374
+ str(reference).lstrip("@"), global_env, local_env
1375
+ )
1376
+ if not isinstance(inherited, dict):
1377
+ raise TypeError("Inline table merge requires a mapping")
1378
+ merged.update(inherited)
1379
+ continue
1380
+ # If the value supports resolution, resolve it.
1381
+ if hasattr(value, "resolve"):
1382
+ value.resolve(global_env, local_env)
1383
+ local_env[key] = value.resolved
1384
+ else:
1385
+ local_env[key] = value
1386
+ # Build a dict of resolved values. If the stored item is a node,
1387
+ # use its .resolved attribute; otherwise, use the raw value.
1388
+ self.resolved = dict(merged)
1389
+ self.resolved.update(
1390
+ {
1391
+ key: value.resolved if hasattr(value, "resolved") else value
1392
+ for key, value in self.data.items()
1393
+ if key != "<<"
1394
+ }
1395
+ )
1396
+ self.value = self.resolved
1397
+
1398
+ def evaluate(self) -> Dict:
1399
+ if self.resolved is not None:
1400
+ return self.resolved
1401
+ out = {}
1402
+ # Only call .evaluate() if the stored object is a node.
1403
+ for key, value in self.data.items():
1404
+ if hasattr(value, "evaluate"):
1405
+ out[key] = value.evaluate()
1406
+ else:
1407
+ out[key] = value
1408
+ return out
1409
+
1410
+ def render(
1411
+ self,
1412
+ global_env: Dict,
1413
+ local_env: Optional[Dict] = None,
1414
+ context: Optional[Dict] = None,
1415
+ ) -> str:
1416
+ # Render each entry; if the entry is a node, call its render method.
1417
+ rendered_items = []
1418
+ for key, value in self.data.items():
1419
+ if hasattr(value, "render"):
1420
+ rendered_val = value.render()
1421
+ else:
1422
+ rendered_val = str(value)
1423
+ rendered_items.append(f"{key}: {rendered_val}")
1424
+ return "{" + ", ".join(rendered_items) + "}"
1425
+
1426
+
1427
+ class FloatNode(BaseNode):
1428
+ def __init__(self):
1429
+ super().__init__()
1430
+ self.value = None # The string value, e.g. "inf", "3.14", etc.
1431
+ self.origin = None
1432
+ self.meta = None
1433
+ self.resolved = None # The actual float, once evaluated/resolved
1434
+
1435
+ def __str__(self) -> str:
1436
+ return f"FloatNode(value={self.value})"
1437
+
1438
+ def __repr__(self) -> str:
1439
+ return f"FloatNode(value={self.value})"
1440
+
1441
+ def emit(self) -> str:
1442
+ # When emitting config text back to a file/string, we just turn the
1443
+ # float into a string
1444
+ return str(self.value)
1445
+
1446
+ def evaluate(self) -> float:
1447
+ """
1448
+ Returns the evaluated float value, preferring self.resolved if
1449
+ available.
1450
+ If not yet resolved, parse self.value as a float.
1451
+ """
1452
+ if self.resolved is not None:
1453
+ return self.resolved
1454
+
1455
+ # Try calling float() directly. "inf", "-inf", "nan" are valid in
1456
+ # Python, but you
1457
+ # can add extra checks if you want to handle uppercase, plus-sign, etc.
1458
+ self.resolved = float(self.value)
1459
+ return self.resolved
1460
+
1461
+ def resolve(self, global_env: Dict, local_env: Optional[Dict] = None):
1462
+ """
1463
+ Forces creation of a float from self.value.
1464
+ """
1465
+ self.resolved = float(self.value)
1466
+ print(f"[DEBUG FLOATNODE RESOLVE]: {self.value} -> {self.resolved}")
1467
+
1468
+ def render(
1469
+ self,
1470
+ global_env: Dict,
1471
+ local_env: Optional[Dict] = None,
1472
+ context: Optional[Dict] = None,
1473
+ ) -> str:
1474
+ """
1475
+ Renders the resolved float back to a string (e.g. '3.14' or 'inf').
1476
+ """
1477
+ return str(self.evaluate())
1478
+
1479
+
1480
+ class SingleQuotedStringNode(BaseNode):
1481
+ """
1482
+ Represents a single- or double-quoted string, e.g. 'hello' or "world".
1483
+ Supports both `${...}` and `%{...}` placeholders.
1484
+ """
1485
+
1486
+ def __init__(self):
1487
+ super().__init__()
1488
+
1489
+ def emit(self) -> str:
1490
+ return self.origin
1491
+
1492
+ def resolve(
1493
+ self,
1494
+ global_env: Dict,
1495
+ local_env: Optional[Dict] = None,
1496
+ context: Optional[Dict] = None,
1497
+ ):
1498
+ from ._substitute import _substitute_vars
1499
+ from collections.abc import Mapping
1500
+
1501
+ # Initialize environments
1502
+ local_env = local_env or {}
1503
+ context = context or {}
1504
+
1505
+ # Strip surrounding quotes
1506
+ s = self.origin
1507
+ if (s.startswith('"') and s.endswith('"')) or (
1508
+ s.startswith("'") and s.endswith("'")
1509
+ ):
1510
+ s = s[1:-1]
1511
+
1512
+ # First, substitute `${...}` placeholders using the provided context
1513
+ substituted = _substitute_vars(
1514
+ s,
1515
+ global_env,
1516
+ local_env,
1517
+ context=context,
1518
+ quote_strings=False,
1519
+ )
1520
+
1521
+ # Then substitute `%{...}` placeholders via regex
1522
+ def repl(match):
1523
+ key = match.group(1)
1524
+ if key in local_env:
1525
+ return str(local_env[key])
1526
+ if isinstance(global_env, Mapping) and key in global_env:
1527
+ return str(global_env[key])
1528
+ return match.group(0)
1529
+
1530
+ result = re.sub(r"%\{([^}]+)\}", repl, substituted)
1531
+ self.resolved = result
1532
+ self.value = result
1533
+
1534
+ def evaluate(self) -> Any:
1535
+ return self.resolved if self.resolved is not None else self.origin
1536
+
1537
+
1538
+ class TripleQuotedStringNode(BaseNode):
1539
+ """
1540
+ Represents a triple-quoted string, e.g. '''Hello\nWorld''' or
1541
+ \"\"\"Hello\nWorld\"\"\".
1542
+ Often multiline.
1543
+ """
1544
+
1545
+ def __init__(self):
1546
+ super().__init__()
1547
+
1548
+ def emit(self) -> str:
1549
+ # Re-wrap in triple quotes:
1550
+ return f'"""{self.value or ""}"""'
1551
+
1552
+ def resolve(self, global_env, local_env=None):
1553
+ # Strip the triple quotes. For example, if origin is """...""", remove
1554
+ # them.
1555
+ # We assume it's either '''...''' or """..."""
1556
+ # This is a naive approach; you could do more robust logic if needed
1557
+ # to handle edge cases or multiline strings with embedded quotes.
1558
+ stripped = self.origin
1559
+ if stripped.startswith('"""') and stripped.endswith('"""'):
1560
+ stripped = stripped[3:-3]
1561
+ elif stripped.startswith("'''") and stripped.endswith("'''"):
1562
+ stripped = stripped[3:-3]
1563
+
1564
+ # Perform variable substitution if your DSL allows that:
1565
+ self.resolved = _substitute_vars(
1566
+ stripped, global_env, local_env, context={}, quote_strings=False
1567
+ )
1568
+ self.value = self.resolved
1569
+
1570
+ def evaluate(self):
1571
+ return self.resolved if self.resolved else self.origin
1572
+
1573
+
1574
+ class BacktickStringNode(BaseNode):
1575
+ """
1576
+ Represents a backtick-quoted string, e.g. `some text`.
1577
+ """
1578
+
1579
+ def __init__(self):
1580
+ super().__init__()
1581
+
1582
+ def emit(self) -> str:
1583
+ return self.origin # e.g. `abc`
1584
+
1585
+ def resolve(self, global_env, local_env=None):
1586
+ # Typically, backticks are used verbatim. But if your DSL allows
1587
+ # some variable interpolation or special handling, do it here.
1588
+ # Example: Just remove backticks and do a substitution:
1589
+ unquoted = self.origin.strip("`")
1590
+ self.resolved = _substitute_vars(
1591
+ unquoted, global_env, local_env, context={}, quote_strings=False
1592
+ )
1593
+ self.value = self.resolved
1594
+
1595
+ def evaluate(self):
1596
+ return self.resolved if self.resolved is not None else self.origin
1597
+
1598
+
1599
+ class FStringNode(BaseNode):
1600
+ """
1601
+ Represents an f-string, e.g. f"hello {name}" or f'''hello {name}'''.
1602
+ """
1603
+
1604
+ def __init__(self):
1605
+ super().__init__()
1606
+
1607
+ def emit(self) -> str:
1608
+ # Return the original f-string if you want to preserve the 'f' prefix
1609
+ # and quotes:
1610
+ return self.origin
1611
+
1612
+ def resolve(self, global_env, local_env=None):
1613
+ if "${" in self.origin:
1614
+ self.resolved = self.value = self.origin
1615
+ return
1616
+ # Use your existing _evaluate_f_string helper to evaluate python-like
1617
+ # f-strings
1618
+ self.resolved = _evaluate_f_string(
1619
+ self.origin,
1620
+ global_data=global_env,
1621
+ local_data=local_env,
1622
+ context={},
1623
+ )
1624
+ self.value = self.resolved
1625
+
1626
+ def render(self, global_env, local_env=None, context=None):
1627
+ self.resolved = _evaluate_f_string(
1628
+ self.origin,
1629
+ global_data=global_env,
1630
+ local_data=local_env,
1631
+ context=context or {},
1632
+ )
1633
+ self.value = self.resolved
1634
+ return self.resolved
1635
+
1636
+ def evaluate(self):
1637
+ return self.resolved if self.resolved is not None else self.origin
1638
+
1639
+
1640
+ class TripleBacktickStringNode(BaseNode):
1641
+ """
1642
+ Represents a triple-backtick-quoted string, often used for code blocks.
1643
+ Example: ```some code here```
1644
+ """
1645
+
1646
+ def __init__(self):
1647
+ super().__init__()
1648
+
1649
+ def emit(self) -> str:
1650
+ """
1651
+ Return the original triple-backtick text verbatim, or you
1652
+ could re-wrap it with triple backticks if you want uniformity.
1653
+ """
1654
+ return self.origin
1655
+
1656
+ def resolve(self, global_env, local_env=None):
1657
+ """
1658
+ If your DSL permits variable interpolation or environment-based
1659
+ substitutions
1660
+ inside triple-backtick strings, handle it here. Otherwise, you can
1661
+ treat them
1662
+ as literal blocks that remain untouched.
1663
+ """
1664
+ # Example: Remove the outer ```...```, do your variable substitions,
1665
+ # then reassign:
1666
+ content = self.origin
1667
+ if content.startswith("```") and content.endswith("```"):
1668
+ content = content[3:-3] # remove the leading and trailing ```
1669
+ # If you do want to do variable substitution, you might do:
1670
+ # content = _substitute_vars(content, global_env, local_env,
1671
+ # quote_strings=False)
1672
+ self.resolved = content
1673
+ self.value = self.resolved
1674
+
1675
+ def evaluate(self):
1676
+ """
1677
+ Return the resolved content (if any), else fallback to the raw origin.
1678
+ """
1679
+ return self.resolved if self.resolved is not None else self.origin
1680
+
1681
+
1682
+ class SingleLineArrayNode(BaseNode):
1683
+ """
1684
+ Represents an array on a single line, e.g. [1, 2, "three"] or ["blue" #
1685
+ Accent color].
1686
+ Preserves inline comments for round-trip serialization.
1687
+ """
1688
+
1689
+ def __init__(self):
1690
+ super().__init__()
1691
+ self.lbrack = None # '[' token
1692
+ self.rbrack = None # ']' token
1693
+ self.contents = [] # List of ValueNode
1694
+ self.inline_comment = None # Optional inline comment token
1695
+ self.value = [] # Evaluated values (without comments)
1696
+ self.resolved = None # Resolved values after substitution
1697
+ self.meta = None # Parser metadata
1698
+
1699
+ def emit(self) -> str:
1700
+ """
1701
+ Return a single-line representation, including comments.
1702
+ """
1703
+ items = [item.emit() for item in self.contents if item]
1704
+ content = ", ".join(items) if items else ""
1705
+ if self.inline_comment:
1706
+ content += f" {self.inline_comment.value}"
1707
+ return f"[{content}]"
1708
+
1709
+ def resolve(self, global_env, local_env=None):
1710
+ """
1711
+ Resolve each item, e.g., substituting variables or evaluating
1712
+ subexpressions.
1713
+ Store the fully resolved result in self.resolved.
1714
+ """
1715
+ resolved_items = []
1716
+ for item in self.contents:
1717
+ if hasattr(item, "resolve"):
1718
+ item.resolve(global_env, local_env)
1719
+ resolved_items.append(getattr(item, "resolved", item.value))
1720
+ else:
1721
+ resolved_items.append(item.value)
1722
+ self.resolved = resolved_items
1723
+ self.value = resolved_items
1724
+
1725
+ def evaluate(self) -> list:
1726
+ """
1727
+ Return the evaluated list of items, excluding comments.
1728
+ """
1729
+ return [
1730
+ item.evaluate() if hasattr(item, "evaluate") else item.value
1731
+ for item in self.contents
1732
+ if item.value is not None
1733
+ ]
1734
+
1735
+ def __str__(self) -> str:
1736
+ return (
1737
+ f"SingleLineArrayNode(value={self.value}, "
1738
+ f"comments={self.inline_comment})"
1739
+ )
1740
+
1741
+ def __repr__(self) -> str:
1742
+ return f"SingleLineArrayNode(value={self.value})"
1743
+
1744
+
1745
+ class MultiLineArrayNode(BaseNode):
1746
+ def __init__(self):
1747
+ super().__init__()
1748
+ self.lbrack = None # '[' token
1749
+ self.rbrack = None # ']' token
1750
+ self.contents = [] # List of ValueNode
1751
+ # We ignore parsed newlines for serialization and instead produce a
1752
+ # canonical format.
1753
+ self.leading_newlines = None
1754
+ self.trailing_newlines = None
1755
+ self.value = []
1756
+ self.resolved = None
1757
+ self.meta = None
1758
+
1759
+ def emit(self) -> str:
1760
+ """
1761
+ Emit the multiline array in canonical form, preserving both
1762
+ values and inline comments exactly as parsed, but omitting
1763
+ any blank-only lines.
1764
+ """
1765
+ typed_tables = any(
1766
+ isinstance(item.value, InlineTableNode)
1767
+ and any(
1768
+ getattr(field, "type_annotation", None)
1769
+ for field in item.value.data.values()
1770
+ )
1771
+ for item in self.contents
1772
+ )
1773
+ if (
1774
+ self.origin
1775
+ and not typed_tables
1776
+ and not any(
1777
+ not line.strip() for line in self.origin.splitlines()[1:-1]
1778
+ )
1779
+ ):
1780
+ return self.origin
1781
+ lines = ["["]
1782
+ for item in self.contents:
1783
+ # Get emitted text and strip trailing newline to avoid blank lines
1784
+ text = item.emit().rstrip("\n")
1785
+ # Skip blank-only lines
1786
+ if not text.strip():
1787
+ continue
1788
+ lines.append(f" {text}")
1789
+ lines.append("]")
1790
+ return "\n".join(lines)
1791
+
1792
+ def resolve(self, global_env, local_env=None):
1793
+ resolved_items = []
1794
+ for item in self.contents:
1795
+ if item.value is not None:
1796
+ if hasattr(item, "resolve") and callable(item.resolve):
1797
+ item.resolve(global_env, local_env)
1798
+ if hasattr(item, "evaluate") and callable(item.evaluate):
1799
+ resolved_items.append(item.evaluate())
1800
+ else:
1801
+ resolved_items.append(item.value)
1802
+ self.resolved = resolved_items
1803
+ self.value = resolved_items
1804
+
1805
+ # Preserve inline comments
1806
+ for item in self.contents:
1807
+ if item.inline_comment:
1808
+ self.__comments__.append(item.inline_comment.value)
1809
+
1810
+ def evaluate(self) -> list:
1811
+ return [
1812
+ item.evaluate()
1813
+ if hasattr(item, "evaluate") and item.value is not None
1814
+ else item.value
1815
+ for item in self.contents
1816
+ if item.value is not None
1817
+ ]
1818
+
1819
+ def __str__(self) -> str:
1820
+ return (
1821
+ f"MultiLineArrayNode(value={self.value}, "
1822
+ f"comments={self.__comments__})"
1823
+ )
1824
+
1825
+ def __repr__(self) -> str:
1826
+ return f"MultiLineArrayNode(value={self.value})"
1827
+
1828
+
1829
+ class GlobalScopedVarNode(BaseNode):
1830
+ """
1831
+ Represents a global scoped variable, e.g. @{variable}.
1832
+ """
1833
+
1834
+ def __init__(self):
1835
+ super().__init__()
1836
+
1837
+ def emit(self) -> str:
1838
+ # Return the original token text (including "@{...}")
1839
+ return self.origin
1840
+
1841
+ def resolve(self, global_env, local_env=None):
1842
+ inner = self.origin[2:-1]
1843
+ val = _lookup(inner, global_env, {})
1844
+ self.resolved = val if val is not None else self.origin
1845
+ self.value = self.resolved
1846
+
1847
+ def evaluate(self):
1848
+ # Return the inner variable name or fallback to the original token text
1849
+ return self.resolved if self.resolved is not None else self.origin
1850
+
1851
+
1852
+ class LocalScopedVarNode(BaseNode):
1853
+ """
1854
+ Represents a local scoped variable, e.g. %{variable}.
1855
+ """
1856
+
1857
+ def __init__(self):
1858
+ super().__init__()
1859
+
1860
+ def emit(self) -> str:
1861
+ # Return the original token text (including "%{...}")
1862
+ return self.origin
1863
+
1864
+ def resolve(self, global_env, local_env=None):
1865
+ """
1866
+ Resolve `%{dotted.path}` against:
1867
+
1868
+ 1. the *local_env* created by comprehension aliases,
1869
+ 2. the whole configuration (`global_env`),
1870
+
1871
+ Supports dotted traversal through **dicts _and_ objects with
1872
+ attributes**, so `%{package.name}` works even when `package` is a
1873
+ custom class instance.
1874
+ """
1875
+ from collections.abc import Mapping
1876
+
1877
+ local_env = local_env or {}
1878
+
1879
+ dotted = self.origin[2:-1] # strip `%{` … `}`
1880
+
1881
+ # ----------------------------------------------------------------
1882
+ # helpers
1883
+ def _dig(obj, path: str):
1884
+ """Walk *obj* through a dotted path trying both dict keys and
1885
+ attrs.
1886
+ """
1887
+ cur = obj
1888
+ for part in path.split("."):
1889
+ if isinstance(cur, Mapping) and part in cur:
1890
+ cur = cur[part]
1891
+ elif hasattr(cur, part):
1892
+ cur = getattr(cur, part)
1893
+ else:
1894
+ return None
1895
+ return cur
1896
+
1897
+ # ❶ local alias scope
1898
+ result = _dig(local_env, dotted)
1899
+
1900
+ # ❷ full configuration
1901
+ if result is None:
1902
+ result = _dig(global_env, dotted)
1903
+
1904
+ # still unresolved → keep literal to be handled later
1905
+ if result is None:
1906
+ result = self.origin
1907
+
1908
+ self.resolved = result
1909
+ self.value = self.resolved
1910
+
1911
+ def evaluate(self):
1912
+ # Return the inner variable name or fallback to the original token text
1913
+ return self.resolved if self.resolved is not None else self.origin
1914
+
1915
+
1916
+ class ContextScopedVarNode(BaseNode):
1917
+ """
1918
+ Represents a context-scoped variable, e.g. ${variable}.
1919
+ """
1920
+
1921
+ def __init__(self):
1922
+ super().__init__()
1923
+
1924
+ def emit(self) -> str:
1925
+ # Return the original token text (including "${…}")
1926
+ return self.origin
1927
+
1928
+ def resolve(
1929
+ self,
1930
+ global_env: Dict,
1931
+ local_env: Optional[Dict] = None,
1932
+ ):
1933
+ """
1934
+ Replace the ${placeholder} with a concrete value, supporting nested
1935
+ lookups and
1936
+ list flattening. Lookup order:
1937
+ 1. local_env
1938
+ 2. global_env
1939
+ If the lookup yields another AST node (including this one), treat it as
1940
+ missing.
1941
+ """
1942
+ logger.warning("ContextScopeVariable should not have resolve.")
1943
+ from collections.abc import Mapping
1944
+
1945
+ local_env = local_env or {}
1946
+
1947
+ # Extract path segments
1948
+ path = self.origin[2:-1]
1949
+ parts = path.split(".")
1950
+
1951
+ def _dig(src):
1952
+ cur = src
1953
+ for part in parts:
1954
+ if isinstance(cur, Mapping) and part in cur:
1955
+ cur = cur[part]
1956
+ elif hasattr(cur, part):
1957
+ cur = getattr(cur, part)
1958
+ elif isinstance(cur, list):
1959
+ out = []
1960
+ for item in cur:
1961
+ val = None
1962
+ if isinstance(item, Mapping) and part in item:
1963
+ val = item[part]
1964
+ elif hasattr(item, part):
1965
+ val = getattr(item, part)
1966
+ if val is None:
1967
+ continue
1968
+ if isinstance(val, list):
1969
+ out.extend(val)
1970
+ else:
1971
+ out.append(val)
1972
+ cur = out
1973
+ else:
1974
+ return None
1975
+ return cur
1976
+
1977
+ candidate = _dig(global_env)
1978
+
1979
+ # If we got another AST node back, ignore it (to prevent
1980
+ # self-reference)
1981
+ from ._ast_nodes import BaseNode
1982
+
1983
+ if isinstance(candidate, BaseNode):
1984
+ candidate = None
1985
+
1986
+ self.resolved = candidate
1987
+ self.value = self.resolved
1988
+
1989
+ def render(
1990
+ self,
1991
+ global_env: Dict[str, Any],
1992
+ local_env: Dict[str, Any] | None = None,
1993
+ context: Dict[str, Any] | None = None,
1994
+ ) -> Any:
1995
+ """
1996
+ During Config.render we have a *context* dict. First try to
1997
+ resolve the variable against that dict; if not found, fall back
1998
+ to the full configuration (global_env + local_env).
1999
+ """
2000
+ from collections.abc import Mapping
2001
+
2002
+ local_env = local_env or {}
2003
+ context = context or {}
2004
+
2005
+ # split e.g. "packages.0.name"
2006
+ path = self.origin[2:-1].split(".")
2007
+
2008
+ def _dig(src):
2009
+ cur = src
2010
+ for part in path:
2011
+ if isinstance(cur, Mapping) and part in cur:
2012
+ cur = cur[part]
2013
+ elif hasattr(cur, part):
2014
+ cur = getattr(cur, part)
2015
+ else:
2016
+ return None
2017
+ return cur
2018
+
2019
+ candidate = _dig(context) # ❶ runtime context
2020
+ if candidate is None:
2021
+ candidate = _dig(local_env) # ❷ current local env
2022
+ if candidate is None:
2023
+ candidate = _dig(global_env) # ❸ whole config
2024
+
2025
+ self.resolved = candidate
2026
+ self.value = candidate
2027
+ return candidate
2028
+
2029
+
2030
+ class WhitespaceNode(BaseNode):
2031
+ def __init__(self, value: str):
2032
+ super().__init__()
2033
+ self.value = value
2034
+
2035
+ def emit(self) -> str:
2036
+ return self.value
2037
+
2038
+ def evaluate(self) -> str:
2039
+ return self.value
2040
+
2041
+
2042
+ class HspacesNode(BaseNode):
2043
+ def __init__(self, value: str):
2044
+ super().__init__()
2045
+ self.value = value
2046
+
2047
+ def emit(self) -> str:
2048
+ return self.value
2049
+
2050
+ def evaluate(self) -> str:
2051
+ return self.value
2052
+
2053
+
2054
+ class InlineWhitespaceNode(BaseNode):
2055
+ def __init__(self, value: str):
2056
+ super().__init__()
2057
+ self.value = value
2058
+
2059
+ def emit(self) -> str:
2060
+ return self.value
2061
+
2062
+ def evaluate(self) -> str:
2063
+ return self.value
2064
+
2065
+
2066
+ class ReservedFuncNode(BaseNode):
2067
+ """
2068
+ Represents a reserved function call like File() or Git().
2069
+ """
2070
+
2071
+ def __init__(self):
2072
+ super().__init__()
2073
+
2074
+ def emit(self) -> str:
2075
+ # Return e.g. "File()" or "Git()"
2076
+ return self.origin
2077
+
2078
+ def resolve(self, global_env, local_env=None):
2079
+ """
2080
+ If your DSL requires special evaluation for `File()` or `Git()`,
2081
+ handle it. Otherwise, keep as literal.
2082
+ """
2083
+ # Example naive: just store it as resolved
2084
+ self.resolved = self.origin
2085
+ self.value = self.resolved
2086
+
2087
+ def evaluate(self):
2088
+ # Return the resolved function call string
2089
+ return self.resolved if self.resolved is not None else self.origin