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.
@@ -0,0 +1,755 @@
1
+ import json
2
+ import re
3
+ from lark import Transformer, Token, v_args
4
+
5
+ from .ast_nodes import (
6
+ PreservedString,
7
+ PreservedValue,
8
+ PreservedArray,
9
+ PreservedInlineTable,
10
+ DeferredDictComprehension,
11
+ DeferredListComprehension,
12
+ FoldedExpressionNode,
13
+ ComprehensionHeader,
14
+ TableArrayHeader,
15
+ TableArraySectionNode,
16
+ StringExpr,
17
+ ComprehensionClauses,
18
+ ComprehensionClause,
19
+ DottedExpr,
20
+ PairExpr,
21
+ AliasClause,
22
+ InClause,
23
+ )
24
+
25
+
26
+ class ConfigTransformer(Transformer):
27
+ def __init__(self, debug=True):
28
+ super().__init__()
29
+ self.debug = debug
30
+ self.debug_print("Initializing ConfigTransformer")
31
+ # Global container for parsed data.
32
+ self.data = {"__comments__": []}
33
+ self.current_section = self.data
34
+
35
+ # Pointer to the current table array header (if we’re processing inline assignments for one).
36
+ self._current_ta_header = None
37
+
38
+ def debug_print(self, message):
39
+ if self.debug:
40
+ print("[DEBUG TRANSFORMER]", message)
41
+
42
+ def start(self, items):
43
+ self.debug_print(f"start() called with items: {items}")
44
+ return self.data
45
+
46
+ # ------------------------------
47
+ # Updated assignment() method.
48
+ # ------------------------------
49
+ def assignment(self, items):
50
+ self.debug_print(f"assignment() called with items: {items}")
51
+ inline = None
52
+ type_annotation = None
53
+
54
+ if len(items) == 2:
55
+ key, value = items
56
+ elif len(items) == 3:
57
+ if isinstance(items[-1], dict) and "_inline_comment" in items[-1]:
58
+ key, value, inline = items
59
+ elif isinstance(items[-1], str) and items[-1].lstrip().startswith("#"):
60
+ key, value, inline = items
61
+ else:
62
+ key, type_annotation, value = items
63
+ elif len(items) == 4:
64
+ key, type_annotation, value, inline = items
65
+ else:
66
+ raise ValueError("Unexpected structure in assignment: " + str(items))
67
+
68
+ # Check for empty or whitespace-only value
69
+ if isinstance(value, str) and value.strip() == "":
70
+ self.debug_print(
71
+ f"Skipping empty or whitespace-only assignment for key: {key}"
72
+ )
73
+ return key, None # Or raise an error
74
+
75
+ if isinstance(value, PreservedString) and value.value.strip() == "":
76
+ self.debug_print(f"Skipping empty PreservedString for key: {key}")
77
+ return key, None
78
+
79
+ # Unquote value if needed
80
+ if (
81
+ not isinstance(value, PreservedString)
82
+ and isinstance(value, str)
83
+ and (
84
+ (value.startswith("'") and value.endswith("'"))
85
+ or (value.startswith('"') and value.endswith('"'))
86
+ )
87
+ ):
88
+ value = value[1:-1]
89
+
90
+ if inline and isinstance(inline, dict) and "_inline_comment" in inline:
91
+ inline = inline["_inline_comment"]
92
+ inline = str(inline) if inline else None
93
+
94
+ if type_annotation:
95
+ result = {
96
+ "_value": PreservedValue(value, inline) if inline else value,
97
+ "_annotation": type_annotation,
98
+ }
99
+ else:
100
+ result = PreservedValue(value, inline) if inline else value
101
+
102
+ if self._current_ta_header is not None:
103
+ table_name = str(self._current_ta_header).split("=")[0].strip()
104
+ if table_name not in self.current_section:
105
+ self.current_section[table_name] = []
106
+ if not self.current_section[table_name]:
107
+ self.current_section[table_name].append({})
108
+ self.current_section[table_name][-1][key] = result
109
+ else:
110
+ self.current_section[key] = result
111
+
112
+ return key, value
113
+
114
+ def section(self, items):
115
+ raw_section = items[0]
116
+ if isinstance(raw_section, list):
117
+ d = self.data
118
+ for part in raw_section[:-1]:
119
+ d = d.setdefault(part, {})
120
+ raw_section = raw_section[-1]
121
+ d[raw_section] = {}
122
+ self.current_section = d[raw_section]
123
+ else:
124
+ self.data[raw_section] = {}
125
+ self.current_section = self.data[raw_section]
126
+ self._current_ta_header = None
127
+ return self.current_section
128
+
129
+ def section_name(self, items):
130
+ self.debug_print(f"section_name() called with items: {items}")
131
+ return items
132
+
133
+ def type_annotation(self, items):
134
+ self.debug_print(f"type_annotation() called with items: {items}")
135
+ return items[0]
136
+
137
+ @v_args(meta=True)
138
+ def alias_clause(self, meta, items):
139
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
140
+ self.debug_print(f"alias_clause(): original_text = {original_text}")
141
+ if len(items) != 2:
142
+ raise ValueError(f"Expected AS SCOPED_VAR, got {items}")
143
+ as_keyword, scoped_var = items
144
+ if as_keyword.lower() != "as":
145
+ raise ValueError(f"Expected 'as' keyword, got {as_keyword}")
146
+ return AliasClause(keyword="as", scoped_var=scoped_var, original=original_text)
147
+
148
+ @v_args(meta=True)
149
+ def IN(self, meta):
150
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
151
+ self.debug_print(f"IN() called. original_text: {original_text}")
152
+ return InClause(keyword="in", original=original_text)
153
+
154
+ @v_args(meta=True)
155
+ def pair_expr(self, meta, items):
156
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
157
+ self.debug_print(f"pair_expr(): original_text = {original_text}")
158
+ self.debug_print(f"pair_expr(): raw items = {items}")
159
+ if len(items) < 3:
160
+ raise ValueError(
161
+ "pair_expr(): Expected at least three items (left, operator, right)"
162
+ )
163
+ left = items[0]
164
+ right = items[2]
165
+ self.debug_print(f"pair_expr(): left = {left}, right = {right}")
166
+ return PairExpr(key=left, value=right, original=original_text)
167
+
168
+ @v_args(meta=True)
169
+ def dotted_expr(self, meta, items):
170
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
171
+ self.debug_print(f"dotted_expr(): original_text = {original_text}")
172
+ self.debug_print(f"dotted_expr(): raw items = {items}")
173
+ dotted_value = ".".join(str(item) for item in items)
174
+ self.debug_print(f"dotted_expr(): joined value = {dotted_value}")
175
+ return DottedExpr(dotted_value, original_text)
176
+
177
+ def paren_expr(self, items):
178
+ result = "(" + " ".join(str(x) for x in items) + ")"
179
+ self.debug_print(f"paren_expr() result: {result}")
180
+ return result
181
+
182
+ @v_args(meta=True)
183
+ def folded_expr(self, meta, items):
184
+ self.debug_print(f"folded_expr() called with meta: {meta} and items: {items}")
185
+ full_text = self._slice_input(meta.start_pos, meta.end_pos)
186
+ self.debug_print(f"Full folded_expr text: {full_text}")
187
+ folded_content_tree = None
188
+ for child in items:
189
+ if hasattr(child, "data") and child.data == "folded_content":
190
+ folded_content_tree = child
191
+ break
192
+ node = FoldedExpressionNode(full_text, folded_content_tree)
193
+ self.debug_print(f"Created FoldedExpressionNode: {node}")
194
+ return node
195
+
196
+ def string_component(self, items):
197
+ token = items[0]
198
+ if token[0] == "STRING":
199
+ return token[1].strip('"').strip("'")
200
+ elif token[0] == "SCOPED_VAR":
201
+ return token[1]
202
+ return token
203
+
204
+ @v_args(meta=True)
205
+ def comprehension_clause(self, meta, items):
206
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
207
+ self.debug_print(f"comprehension_clause(): original_text = {original_text}")
208
+ self.debug_print(f"comprehension_clause(): raw items = {items}")
209
+
210
+ # Initialize components
211
+ loop_vars = []
212
+ iterable = None
213
+ conditions = []
214
+
215
+ # Process the parse tree
216
+ i = 0
217
+ # Skip FOR
218
+ if i < len(items) and isinstance(items[i], Token) and items[i].type == "FOR":
219
+ i += 1
220
+
221
+ # Handle loop_vars
222
+ if (
223
+ i < len(items)
224
+ and hasattr(items[i], "data")
225
+ and items[i].data == "loop_vars"
226
+ ):
227
+ loop_vars_tree = items[i]
228
+ for loop_var in loop_vars_tree.children:
229
+ if hasattr(loop_var, "data") and loop_var.data == "loop_var":
230
+ var_items = loop_var.children
231
+ dotted_expr = var_items[0]
232
+ alias = None
233
+ if len(var_items) > 1 and isinstance(var_items[1], AliasClause):
234
+ alias = var_items[1]
235
+ loop_vars.append((dotted_expr, alias) if alias else dotted_expr)
236
+ i += 1
237
+
238
+ # Handle IN and iterable
239
+ if i < len(items) and isinstance(items[i], InClause):
240
+ i += 1
241
+ if i < len(items):
242
+ # The iterable could be a SCOPED_VAR, STRING, or other value
243
+ iterable = items[i]
244
+ i += 1
245
+
246
+ # Handle IF conditions
247
+ while i < len(items):
248
+ if isinstance(items[i], Token) and items[i].type == "IF":
249
+ i += 1
250
+ if (
251
+ i < len(items)
252
+ and hasattr(items[i], "data")
253
+ and items[i].data == "comprehension_condition"
254
+ ):
255
+ condition = []
256
+ condition_items = items[i].children
257
+ condition.append(condition_items[0]) # First comp_expr
258
+ if len(condition_items) > 1:
259
+ condition.append(condition_items[1]) # OPERATOR
260
+ condition.append(condition_items[2]) # Second comp_expr
261
+ conditions.append(condition)
262
+ i += 1
263
+ else:
264
+ i += 1 # Skip unexpected items (e.g., NEWLINE)
265
+
266
+ self.debug_print(
267
+ f"comprehension_clause(): loop_vars = {loop_vars}, iterable = {iterable}, conditions = {conditions}"
268
+ )
269
+ return ComprehensionClause(
270
+ loop_vars=loop_vars,
271
+ iterable=iterable,
272
+ conditions=conditions,
273
+ original=original_text,
274
+ )
275
+
276
+ @v_args(meta=True)
277
+ def comprehension_clauses(self, meta, items):
278
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
279
+ self.debug_print(f"comprehension_clauses(): original_text = {original_text}")
280
+ self.debug_print(f"comprehension_clauses(): items = {items}")
281
+ return ComprehensionClauses(clauses=items, original=original_text)
282
+
283
+ @v_args(meta=True)
284
+ def string_expr(self, meta, items):
285
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
286
+ self.debug_print(f"string_expr(): original_text = {original_text}")
287
+ self.debug_print(f"string_expr(): items = {items}")
288
+ return StringExpr(parts=items, original=original_text)
289
+
290
+ def concat_expr(self, items):
291
+ parts = []
292
+ for child in items:
293
+ if isinstance(child, str):
294
+ parts.append(child)
295
+ else:
296
+ parts.append(str(child))
297
+ return "".join(parts)
298
+
299
+ def pair_expr(self, items):
300
+ key = items[0]
301
+ value = items[2]
302
+ return (key, value)
303
+
304
+ def comprehension_expr(self, items):
305
+ self.debug_print(f"comprehension_expr() called with items: {items}")
306
+ if len(items) == 1:
307
+ child = items[0]
308
+ if isinstance(child, PreservedString):
309
+ return child.value
310
+ return child
311
+ return "".join(str(i) for i in items)
312
+
313
+ @v_args(meta=True)
314
+ def list_comprehension(self, meta, items):
315
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
316
+ self.debug_print(
317
+ f"list_comprehension() called with meta: {meta} and items: {items}"
318
+ )
319
+ self.debug_print(f"List comprehension original text: {original_text}")
320
+ return DeferredListComprehension(original_text)
321
+
322
+ @v_args(meta=True)
323
+ def dict_comprehension(self, meta, items):
324
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
325
+ self.debug_print(
326
+ f"dict_comprehension() called with meta: {meta} and items: {items}"
327
+ )
328
+ return DeferredDictComprehension(original_text)
329
+
330
+ @v_args(meta=True)
331
+ def header_comprehension(self, meta, items):
332
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
333
+ meaningful_items = [
334
+ item
335
+ for item in items
336
+ if not (isinstance(item, Token) and item.type in ("NEWLINE", "WHITESPACE"))
337
+ ]
338
+ header_expr = meaningful_items[0]
339
+ clauses = meaningful_items[1] if len(meaningful_items) > 1 else None
340
+ node = ComprehensionHeader(header_expr, clauses, original_text)
341
+ node.table_name = original_text.strip("[]")
342
+ # Extract aliases for rendering
343
+ node.aliases = []
344
+ if clauses:
345
+ for clause in clauses.clauses:
346
+ for var in clause.loop_vars:
347
+ if (
348
+ isinstance(var, tuple)
349
+ and len(var) == 2
350
+ and isinstance(var[1], AliasClause)
351
+ ):
352
+ # Extract alias name from scoped_var (e.g., "%{package}" → "package")
353
+ scoped_var = var[1].scoped_var
354
+ match = re.match(r"[@%$]\{([^}]+)\}", scoped_var)
355
+ if match:
356
+ alias_name = match.group(1)
357
+ node.aliases.append(alias_name)
358
+ else:
359
+ self.debug_print(
360
+ f"Warning: Malformed scoped_var in {scoped_var}"
361
+ )
362
+ return node
363
+
364
+ # --------------------------------------------------------------------------
365
+ # Updated table array header rule.
366
+ # --------------------------------------------------------------------------
367
+ @v_args(meta=True)
368
+ def table_array_header(self, meta, items):
369
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
370
+ self.debug_print(
371
+ f"table_array_header() extracted original: {original_text} and items: {items}"
372
+ )
373
+
374
+ header_parts = []
375
+ for item in items:
376
+ if isinstance(item, tuple):
377
+ key, value = item
378
+ header_parts.append(f"{key} = {value}")
379
+ else:
380
+ header_parts.append(str(item))
381
+ aggregated_header_expr = " ".join(header_parts)
382
+
383
+ header_node = TableArrayHeader(aggregated_header_expr, original_text)
384
+ # Set the header pointer
385
+ self._current_ta_header = header_node
386
+ # Initialize the header's inline assignments dictionary.
387
+ header_node.inline_assignments = {}
388
+ return header_node
389
+
390
+ # --------------------------------------------------------------------------
391
+ # Updated table array section rule.
392
+ # --------------------------------------------------------------------------
393
+ @v_args(meta=True)
394
+ def table_array_section(self, meta, items):
395
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
396
+ header = items[0]
397
+ body_dict = {}
398
+ for child in items[1:]:
399
+ if isinstance(child, tuple):
400
+ key, value = child
401
+ body_dict[key] = value
402
+ if hasattr(header, "inline_assignments"):
403
+ body_dict.update(header.inline_assignments)
404
+ # Resolve header to a string key
405
+ table_name = (
406
+ header.table_name
407
+ if hasattr(header, "table_name")
408
+ else str(header).split("=")[0].strip()
409
+ )
410
+ if isinstance(header, (ComprehensionHeader, TableArrayHeader)):
411
+ # Use original text for comprehension headers
412
+ table_name = (
413
+ header.origin.strip("[]")
414
+ if isinstance(header, ComprehensionHeader)
415
+ else table_name
416
+ )
417
+ if table_name not in self.current_section:
418
+ self.current_section[table_name] = []
419
+ node = TableArraySectionNode(
420
+ header=header,
421
+ body=body_dict,
422
+ original=original_text,
423
+ )
424
+ self.current_section[table_name].append(node)
425
+ self.current_section = self.data # Reset to root for global context
426
+ self._current_ta_header = None
427
+ return node
428
+
429
+ def inline_assignment(self, items):
430
+ self.debug_print(f"inline_assignment() called with items: {items}")
431
+ if len(items) >= 4 and isinstance(items[1], Token) and items[1].type == "COLON":
432
+ key = items[0]
433
+ type_annotation = items[2]
434
+ value = items[3]
435
+ inline = items[4] if len(items) > 4 else None
436
+ else:
437
+ if len(items) == 2:
438
+ key, value = items
439
+ inline = None
440
+ elif len(items) == 3:
441
+ if isinstance(items[-1], dict) and "_inline_comment" in items[-1]:
442
+ key, value, inline = items
443
+ elif isinstance(items[-1], str) and items[-1].lstrip().startswith("#"):
444
+ key, value, inline = items
445
+ else:
446
+ key, type_annotation, value = items
447
+ inline = None
448
+ elif len(items) == 4:
449
+ key, type_annotation, value, inline = items
450
+ else:
451
+ raise ValueError(
452
+ "Unexpected structure in inline_assignment: " + str(items)
453
+ )
454
+ self.debug_print(f"Inline assignment returning: {{ {key}: {value} }}")
455
+ return {key: value}
456
+
457
+ def inline_table_item(self, items):
458
+ self.debug_print(f"inline_table_item() called with items: {items}")
459
+ comment_parts = []
460
+ assignment_dict = None
461
+ inline_comment = ""
462
+ for child in items:
463
+ if hasattr(child, "data"):
464
+ if child.data == "pre_item_comments":
465
+ comment_parts.extend(tok.value for tok in child.children)
466
+ elif child.data == "inline_assignment":
467
+ assignment_dict = self.inline_assignment(child.children)
468
+ elif child.data == "inline_comment":
469
+ if len(child.children) >= 2:
470
+ inline_comment = child.children[1].value
471
+ elif isinstance(child, dict):
472
+ assignment_dict = child
473
+ comment_text = " ".join(comment_parts)
474
+ if inline_comment:
475
+ comment_text = (comment_text + " " + inline_comment).strip()
476
+ if comment_text and not comment_text.lstrip().startswith("#"):
477
+ comment_text = "# " + comment_text
478
+ return (assignment_dict, comment_text if comment_text else None)
479
+
480
+ def inline_table_items(self, items):
481
+ self.debug_print(f"inline_table_items() called with items: {items}")
482
+
483
+ def is_ignorable(x):
484
+ if hasattr(x, "data") and x.data == "ws":
485
+ return True
486
+ if isinstance(x, str) and x.strip() == "":
487
+ return True
488
+ return False
489
+
490
+ return [x for x in items if not is_ignorable(x)]
491
+
492
+ @v_args(meta=True)
493
+ def inline_table(self, meta, children):
494
+ items = []
495
+ for child in children:
496
+ if isinstance(child, list):
497
+ items.extend(child)
498
+ elif hasattr(child, "data") and child.data == "inline_table_items":
499
+ items.extend(child.children)
500
+ else:
501
+ items.append(child)
502
+ processed_items = []
503
+ for item in items:
504
+ if isinstance(item, tuple):
505
+ processed_items.append(item)
506
+ elif isinstance(item, dict):
507
+ processed_items.append((item, None))
508
+ # Otherwise, ignore.
509
+ result = {}
510
+ prev_key = None
511
+ for tup in processed_items:
512
+ assignment, comment = tup
513
+ if assignment is None:
514
+ continue
515
+ key = list(assignment.keys())[0]
516
+ value = assignment[key]
517
+ if comment and prev_key is not None:
518
+ if key == "email" and prev_key == "name":
519
+ prev_val = result.get(prev_key)
520
+ if isinstance(prev_val, PreservedValue):
521
+ prev_val.comment = (
522
+ (prev_val.comment + " " + comment).strip()
523
+ if prev_val.comment
524
+ else comment
525
+ )
526
+ else:
527
+ result[prev_key] = PreservedValue(prev_val, comment)
528
+ comment = None
529
+ if comment:
530
+ if isinstance(value, PreservedValue):
531
+ value.comment = comment
532
+ else:
533
+ value = PreservedValue(value, comment)
534
+ assignment[key] = value
535
+ result.update(assignment)
536
+ prev_key = key
537
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
538
+ return PreservedInlineTable(result, original_text)
539
+
540
+ def comment_line(self, items):
541
+ self.debug_print(f"comment_line() called with items: {items}")
542
+ comment_token = items[0]
543
+ if hasattr(comment_token, "column") and comment_token.column == 1:
544
+ self.data["__comments__"].append(comment_token.value)
545
+ return comment_token.value
546
+
547
+ def inline_comment(self, items):
548
+ self.debug_print(f"inline_comment() called with items: {items}")
549
+ ws = items[0]
550
+ com = items[1]
551
+ return {"_inline_comment": ws + com}
552
+
553
+ @v_args(meta=True)
554
+ def array(self, meta, items):
555
+ self.debug_print(f"array() called with meta: {meta} and items: {items}")
556
+ array_values = []
557
+ for item in items:
558
+ if isinstance(item, Token) and item.type in (
559
+ "LBRACK",
560
+ "RBRACK",
561
+ "NEWLINE",
562
+ "WHITESPACE",
563
+ ):
564
+ continue
565
+ if isinstance(item, str) and item.strip() == "":
566
+ continue
567
+ if isinstance(item, list):
568
+ array_values.extend(item)
569
+ else:
570
+ array_values.append(item)
571
+ original_text = self._slice_input(meta.start_pos, meta.end_pos)
572
+ self.debug_print(
573
+ f"array result: {array_values} with original text: {original_text}"
574
+ )
575
+ return PreservedArray(array_values, original_text)
576
+
577
+ def array_content(self, items):
578
+ self.debug_print(f"array_content() called with items: {items}")
579
+
580
+ def is_ignorable(x):
581
+ if hasattr(x, "data") and x.data == "ws":
582
+ return True
583
+ if isinstance(x, str) and x.strip() == "":
584
+ return True
585
+ if isinstance(x, Token) and x.type in ("WHITESPACE", "NEWLINE"):
586
+ return True
587
+ return False
588
+
589
+ return [x for x in items if x != "," and not is_ignorable(x)]
590
+
591
+ def array_item(self, items):
592
+ self.debug_print(f"array_item() called with items: {items}")
593
+ pre_comments = None
594
+ value = None
595
+ inline_comment = None
596
+ items = list(items)
597
+ if items and hasattr(items[0], "data") and items[0].data == "pre_item_comments":
598
+ pre_comments = items.pop(0)
599
+ if items:
600
+ value = items.pop(0)
601
+ if items and hasattr(items[0], "data") and items[0].data == "inline_comment":
602
+ inline_comment = items.pop(0)
603
+ attach_pre_comments = False
604
+ if pre_comments and hasattr(pre_comments, "children") and pre_comments.children:
605
+ last_comment = pre_comments.children[-1]
606
+ value_line = getattr(value, "line", None)
607
+ if value_line is None and hasattr(value, "children") and value.children:
608
+ value_line = getattr(value.children[0], "line", None)
609
+ if last_comment.line == value_line:
610
+ attach_pre_comments = True
611
+ combined_inline = None
612
+ if attach_pre_comments:
613
+ pre_text = " ".join(tok.value for tok in pre_comments.children)
614
+ if (
615
+ inline_comment
616
+ and hasattr(inline_comment, "children")
617
+ and len(inline_comment.children) > 1
618
+ ):
619
+ inline_text = inline_comment.children[1].value
620
+ else:
621
+ inline_text = ""
622
+ combined_inline = pre_text + (" " + inline_text if inline_text else "")
623
+ else:
624
+ if (
625
+ inline_comment
626
+ and hasattr(inline_comment, "children")
627
+ and len(inline_comment.children) > 1
628
+ ):
629
+ combined_inline = inline_comment.children[1].value
630
+ actual_value = value
631
+ if combined_inline:
632
+ self.debug_print(
633
+ f"array_item() returning PreservedValue for value: {actual_value} with inline comment: {combined_inline}"
634
+ )
635
+ return PreservedValue(actual_value, combined_inline)
636
+ self.debug_print(f"array_item() returning value: {actual_value}")
637
+ return actual_value
638
+
639
+ def array_value(self, items):
640
+ self.debug_print(f"array_value() called with items: {items}")
641
+ return items[0]
642
+
643
+ def INLINE_TABLE(self, token):
644
+ self.debug_print(f"INLINE_TABLE() called with token: {token}")
645
+ if hasattr(token, "meta") and token.meta:
646
+ start = token.meta.start_pos
647
+ end = token.meta.end_pos
648
+ original_text = self._slice_input(start, end)
649
+ else:
650
+ original_text = token.value
651
+ s = token.value.strip()
652
+ if s.startswith("{") and s.endswith("}"):
653
+ s = s[1:-1].strip()
654
+ result_dict = {}
655
+ if s:
656
+ pairs = s.split(",")
657
+ for pair in pairs:
658
+ if "=" in pair:
659
+ key, val = pair.split("=", 1)
660
+ key = key.strip()
661
+ val = val.strip()
662
+ try:
663
+ if "." in val:
664
+ converted = float(val)
665
+ else:
666
+ converted = int(val)
667
+ except ValueError:
668
+ if (val.startswith('"') and val.endswith('"')) or (
669
+ val.startswith("'") and val.endswith("'")
670
+ ):
671
+ converted = val[1:-1]
672
+ else:
673
+ converted = val
674
+ result_dict[key] = converted
675
+ self.debug_print(
676
+ f"INLINE_TABLE() parsed dict: {result_dict} with original text: {original_text}"
677
+ )
678
+ return PreservedInlineTable(result_dict, original_text)
679
+
680
+ def ARRAY(self, token):
681
+ self.debug_print(f"ARRAY() called with token: {token}")
682
+ s = token.value.strip()
683
+ try:
684
+ parsed = json.loads(s)
685
+ if isinstance(parsed, list):
686
+ self.debug_print("ARRAY() successfully parsed JSON list")
687
+ return PreservedArray(parsed, token.value)
688
+ return parsed
689
+ except Exception as e:
690
+ self.debug_print(f"ARRAY() JSON parsing error: {e}")
691
+ return s
692
+
693
+ def STRING(self, token):
694
+ self.debug_print(f"STRING() called with token: {token}")
695
+ s = token.value
696
+ if s.lstrip().startswith('f"') or s.lstrip().startswith("f'"):
697
+ self.debug_print("String with f-prefix detected")
698
+ return PreservedString(s.lstrip(), s)
699
+ if s.startswith("'''") and s.endswith("'''"):
700
+ inner = s[3:-3]
701
+ return PreservedString(inner, s)
702
+ if s.startswith('"""') and s.endswith('"""'):
703
+ return PreservedString(s[3:-3], s)
704
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in {"'", '"', "`"}:
705
+ return PreservedString(s[1:-1], s)
706
+ return s
707
+
708
+ def SCOPED_VAR(self, token):
709
+ return token.value
710
+
711
+ def FLOAT(self, token):
712
+ return float(token.value)
713
+
714
+ def INTEGER(self, token):
715
+ val = token.value
716
+ if val in ("inf", "nan", "+inf", "-inf"):
717
+ return val
718
+ return int(val, 0)
719
+
720
+ def BOOLEAN(self, token):
721
+ return token.value == "true"
722
+
723
+ def NULL(self, token):
724
+ return None
725
+
726
+ def RESERVED_FUNC(self, token):
727
+ return token.value
728
+
729
+ def KEYWORD(self, token):
730
+ return token.value
731
+
732
+ def TABLE_ARRAY(self, token):
733
+ return token.value
734
+
735
+ def FOLDER_BLOCK(self, token):
736
+ return token.value
737
+
738
+ def IDENTIFIER(self, token):
739
+ return token.value
740
+
741
+ def OPERATOR(self, token):
742
+ return token.value
743
+
744
+ def PUNCTUATION(self, token):
745
+ return token.value
746
+
747
+ def WHITESPACE(self, token):
748
+ return token.value
749
+
750
+ def INLINE_WS(self, token):
751
+ return token.value
752
+
753
+ def _slice_input(self, start, end):
754
+ self.debug_print(f"_slice_input() called with start: {start}, end: {end}")
755
+ return self._context.text[start:end]