netherframe.generation 0.3.0__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.
Files changed (68) hide show
  1. netherframe/generation/__init__.py +31 -0
  2. netherframe/generation/api.py +306 -0
  3. netherframe/generation/batch.py +65 -0
  4. netherframe/generation/convert/__init__.py +6 -0
  5. netherframe/generation/convert/bindings.py +180 -0
  6. netherframe/generation/convert/converter.py +365 -0
  7. netherframe/generation/convert/emitter.py +972 -0
  8. netherframe/generation/convert/expressions.py +701 -0
  9. netherframe/generation/convert/hcl_ast.py +721 -0
  10. netherframe/generation/convert/module_fetch.py +135 -0
  11. netherframe/generation/convert/module_source.py +200 -0
  12. netherframe/generation/convert/python_code.py +152 -0
  13. netherframe/generation/discovered_code.py +777 -0
  14. netherframe/generation/functions/__init__.py +8 -0
  15. netherframe/generation/functions/generator.py +369 -0
  16. netherframe/generation/import_specs.py +179 -0
  17. netherframe/generation/imports.py +169 -0
  18. netherframe/generation/nf_alias_shims.py +104 -0
  19. netherframe/generation/providers/__init__.py +1 -0
  20. netherframe/generation/providers/build_backend.py +90 -0
  21. netherframe/generation/providers/cli.py +274 -0
  22. netherframe/generation/providers/code_generator.py +2128 -0
  23. netherframe/generation/providers/codegen_support.py +542 -0
  24. netherframe/generation/providers/logging.py +22 -0
  25. netherframe/generation/providers/output_transaction.py +85 -0
  26. netherframe/generation/providers/package_output.py +440 -0
  27. netherframe/generation/providers/release.py +155 -0
  28. netherframe/generation/providers/schema_generation.py +220 -0
  29. netherframe/generation/providers/schema_loading.py +10 -0
  30. netherframe/generation/providers/schema_native.py +97 -0
  31. netherframe/generation/providers/schema_parser.py +563 -0
  32. netherframe/generation/py.typed +0 -0
  33. netherframe_generation-0.3.0.dist-info/METADATA +66 -0
  34. netherframe_generation-0.3.0.dist-info/RECORD +68 -0
  35. netherframe_generation-0.3.0.dist-info/WHEEL +4 -0
  36. netherframe_generation-0.3.0.dist-info/licenses/LICENSE +21 -0
  37. nf/generation/__init__.py +4 -0
  38. nf/generation/api.py +4 -0
  39. nf/generation/batch.py +4 -0
  40. nf/generation/convert/__init__.py +4 -0
  41. nf/generation/convert/bindings.py +4 -0
  42. nf/generation/convert/converter.py +4 -0
  43. nf/generation/convert/emitter.py +4 -0
  44. nf/generation/convert/expressions.py +4 -0
  45. nf/generation/convert/hcl_ast.py +4 -0
  46. nf/generation/convert/module_fetch.py +4 -0
  47. nf/generation/convert/module_source.py +4 -0
  48. nf/generation/convert/python_code.py +4 -0
  49. nf/generation/discovered_code.py +4 -0
  50. nf/generation/functions/__init__.py +4 -0
  51. nf/generation/functions/generator.py +4 -0
  52. nf/generation/import_specs.py +4 -0
  53. nf/generation/imports.py +4 -0
  54. nf/generation/nf_alias_shims.py +4 -0
  55. nf/generation/providers/__init__.py +4 -0
  56. nf/generation/providers/build_backend.py +4 -0
  57. nf/generation/providers/cli.py +4 -0
  58. nf/generation/providers/code_generator.py +4 -0
  59. nf/generation/providers/codegen_support.py +4 -0
  60. nf/generation/providers/logging.py +4 -0
  61. nf/generation/providers/output_transaction.py +4 -0
  62. nf/generation/providers/package_output.py +4 -0
  63. nf/generation/providers/release.py +4 -0
  64. nf/generation/providers/schema_generation.py +4 -0
  65. nf/generation/providers/schema_loading.py +4 -0
  66. nf/generation/providers/schema_native.py +4 -0
  67. nf/generation/providers/schema_parser.py +4 -0
  68. nf/generation/py.typed +0 -0
@@ -0,0 +1,721 @@
1
+ """HCL expressions as a small typed tree, from native syntax (python-hcl2's parse tree) or JSON.
2
+
3
+ The converter translates this tree, not python-hcl2's, so the two syntaxes share one translator
4
+ and the parser's tree shapes stay in this module. Every node keeps its original source text
5
+ (``source``), which TODO markers quote.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ import hcl2
16
+ from lark import Token, Tree
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Iterator
20
+
21
+
22
+ class HclSyntaxError(ValueError):
23
+ """HCL the converter cannot parse."""
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Expr:
28
+ """An HCL expression."""
29
+
30
+ source: str = field(default="", compare=False, kw_only=True)
31
+ line: int = field(default=0, compare=False, kw_only=True)
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Literal(Expr):
36
+ """A string, number, bool or null."""
37
+
38
+ value: str | int | float | bool | None
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Template(Expr):
43
+ """A string with interpolations: each part is literal text or an expression."""
44
+
45
+ parts: tuple[str | Expr, ...]
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class TupleExpr(Expr):
50
+ items: tuple[Expr, ...]
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class ObjectExpr(Expr):
55
+ """An object; a key is a ``Literal`` (a bare identifier or string) or an expression."""
56
+
57
+ items: tuple[tuple[Expr, Expr], ...]
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Name(Expr):
62
+ """A bare identifier: the root of a traversal (``var``, ``aws_vpc``, ``each``)."""
63
+
64
+ name: str
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class GetAttr(Expr):
69
+ obj: Expr
70
+ name: str
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class Index(Expr):
75
+ obj: Expr
76
+ key: Expr
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class Splat(Expr):
81
+ """``obj[*].a.b``: the steps apply to each element (a step is an attribute name or an index)."""
82
+
83
+ obj: Expr
84
+ steps: tuple[str | Expr, ...]
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class Call(Expr):
89
+ name: str
90
+ args: tuple[Expr, ...]
91
+ expand_final: bool = False # `f(args...)`
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class BinaryOp(Expr):
96
+ op: str
97
+ left: Expr
98
+ right: Expr
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class UnaryOp(Expr):
103
+ op: str # "-" or "!"
104
+ operand: Expr
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class Conditional(Expr):
109
+ condition: Expr
110
+ if_true: Expr
111
+ if_false: Expr
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class ForExpr(Expr):
116
+ """``[for k, v in xs : value if cond]`` or ``{for k, v in xs : key => value if cond}``."""
117
+
118
+ key_var: str | None
119
+ value_var: str
120
+ iterable: Expr
121
+ value: Expr
122
+ key: Expr | None = None # set for object results
123
+ condition: Expr | None = None
124
+ grouping: bool = False
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class Unsupported(Expr):
129
+ """An expression the converter does not translate (template directives, provider functions...)."""
130
+
131
+ reason: str
132
+
133
+
134
+ def traversal(expr: Expr) -> tuple[str, tuple[str | Expr, ...]] | None:
135
+ """``var.x[0].y`` as its root name and steps (``("var", ("x", Literal(0), "y"))``), if it is one."""
136
+ steps: list[str | Expr] = []
137
+ while True:
138
+ if isinstance(expr, Name):
139
+ return expr.name, tuple(reversed(steps))
140
+ if isinstance(expr, GetAttr):
141
+ steps.append(expr.name)
142
+ expr = expr.obj
143
+ elif isinstance(expr, Index):
144
+ steps.append(expr.key)
145
+ expr = expr.obj
146
+ else:
147
+ return None
148
+
149
+
150
+ def walk(expr: Expr) -> Iterator[Expr]:
151
+ """The expression and every expression in it."""
152
+ yield expr
153
+ match expr:
154
+ case Template(parts=parts):
155
+ for part in parts:
156
+ if isinstance(part, Expr):
157
+ yield from walk(part)
158
+ case TupleExpr(items=items):
159
+ for item in items:
160
+ yield from walk(item)
161
+ case ObjectExpr(items=items):
162
+ for key, value in items:
163
+ yield from walk(key)
164
+ yield from walk(value)
165
+ case GetAttr(obj=obj):
166
+ yield from walk(obj)
167
+ case Index(obj=obj, key=key):
168
+ yield from walk(obj)
169
+ yield from walk(key)
170
+ case Splat(obj=obj, steps=steps):
171
+ yield from walk(obj)
172
+ for step in steps:
173
+ if isinstance(step, Expr):
174
+ yield from walk(step)
175
+ case Call(args=args):
176
+ for arg in args:
177
+ yield from walk(arg)
178
+ case BinaryOp(left=left, right=right):
179
+ yield from walk(left)
180
+ yield from walk(right)
181
+ case UnaryOp(operand=operand):
182
+ yield from walk(operand)
183
+ case Conditional(condition=condition, if_true=if_true, if_false=if_false):
184
+ yield from walk(condition)
185
+ yield from walk(if_true)
186
+ yield from walk(if_false)
187
+ case ForExpr(iterable=iterable, value=value, key=key, condition=condition):
188
+ yield from walk(iterable)
189
+ yield from walk(value)
190
+ if key is not None:
191
+ yield from walk(key)
192
+ if condition is not None:
193
+ yield from walk(condition)
194
+ case _:
195
+ pass
196
+
197
+
198
+ # --- Native syntax --------------------------------------------------------------------------------
199
+
200
+ _ESCAPES = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\"}
201
+ _ESCAPE = re.compile(r"\\(?:u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|(.))", re.DOTALL)
202
+
203
+
204
+ def unescape(text: str) -> str:
205
+ """The value of the characters of a quoted HCL string."""
206
+
207
+ def replace(match: re.Match[str]) -> str:
208
+ if match.group(1) or match.group(2):
209
+ return chr(int(match.group(1) or match.group(2), 16))
210
+ return _ESCAPES.get(match.group(3), match.group(0))
211
+
212
+ return _ESCAPE.sub(replace, text)
213
+
214
+
215
+ def _trees(node: Tree) -> list[Tree]:
216
+ return [child for child in node.children if isinstance(child, Tree) and child.data != "new_line_or_comment"]
217
+
218
+
219
+ class NativeConverter:
220
+ """python-hcl2 parse trees of one file to ``Expr`` trees."""
221
+
222
+ def __init__(self, text: str, *, first_line: int = 1) -> None:
223
+ self.text = text
224
+ self.line_offset = first_line - 1
225
+
226
+ def source(self, node: Tree | Token) -> str:
227
+ if isinstance(node, Token):
228
+ return str(node)
229
+ meta = node.meta
230
+ if getattr(meta, "empty", True):
231
+ return ""
232
+ return self.text[meta.start_pos : meta.end_pos]
233
+
234
+ def line(self, node: Tree | Token) -> int:
235
+ line = getattr(node, "line", None) if isinstance(node, Token) else getattr(node.meta, "line", None)
236
+ return (line or 1) + self.line_offset
237
+
238
+ def expr(self, node: Tree | Token) -> Expr:
239
+ source, line = self.source(node), self.line(node)
240
+ try:
241
+ result = self._expr(node)
242
+ except _Unsupported as error:
243
+ return Unsupported(str(error), source=source, line=line)
244
+ if not result.source:
245
+ object.__setattr__(result, "source", source)
246
+ object.__setattr__(result, "line", line)
247
+ return result
248
+
249
+ def _expr(self, node: Tree | Token) -> Expr: # noqa: PLR0911, PLR0912
250
+ if isinstance(node, Token):
251
+ raise _Unsupported(f"unexpected token {node.type}")
252
+ data = node.data
253
+ children = _trees(node)
254
+ if data == "expr_term":
255
+ if len(children) == 1:
256
+ return self.expr(children[0])
257
+ raise _Unsupported("empty expression")
258
+ if data == "conditional":
259
+ condition, if_true, if_false = children
260
+ return Conditional(self.expr(condition), self.expr(if_true), self.expr(if_false))
261
+ if data == "binary_op":
262
+ left, term = children
263
+ operator_node, right = _trees(term)
264
+ return BinaryOp(str(operator_node.children[0]), self.expr(left), self.expr(right))
265
+ if data == "unary_op":
266
+ operator = next(child for child in node.children if isinstance(child, Token))
267
+ return UnaryOp(str(operator), self.expr(children[0]))
268
+ if data == "int_lit":
269
+ return Literal(int(str(node.children[0])))
270
+ if data == "float_lit":
271
+ return Literal(float(str(node.children[0])))
272
+ if data == "literal_value":
273
+ return Literal({"true": True, "false": False, "null": None}[str(node.children[0])])
274
+ if data == "identifier":
275
+ return Name(str(node.children[0]))
276
+ if data == "string":
277
+ return self._string(node)
278
+ if data in {"heredoc_template", "heredoc_template_trim"}:
279
+ return parse_template(heredoc_text(str(node.children[0]), trim=data == "heredoc_template_trim"), line=self.line(node))
280
+ if data == "tuple":
281
+ return TupleExpr(tuple(self.expr(child) for child in children))
282
+ if data == "object":
283
+ return ObjectExpr(tuple(self._object_elem(child) for child in children))
284
+ if data == "function_call":
285
+ return self._call(node)
286
+ if data == "get_attr_expr_term":
287
+ obj, get_attr = children
288
+ return GetAttr(self.expr(obj), self._attr_name(get_attr))
289
+ if data == "index_expr_term":
290
+ obj, index = children
291
+ return Index(self.expr(obj), self._index(index))
292
+ if data in {"attr_splat_expr_term", "full_splat_expr_term"}:
293
+ obj, splat = children
294
+ steps = tuple(self._attr_name(step) if step.data == "get_attr" else self._index(step) for step in _trees(splat))
295
+ return Splat(self.expr(obj), steps)
296
+ if data in {"for_tuple_expr", "for_object_expr"}:
297
+ return self._for(node, children, as_object=data == "for_object_expr")
298
+ if data == "template_string":
299
+ raise _Unsupported("escaped string in a template directive")
300
+ raise _Unsupported(f"unsupported expression {data}")
301
+
302
+ def _attr_name(self, get_attr: Tree) -> str:
303
+ (child,) = _trees(get_attr)
304
+ return str(child.children[0])
305
+
306
+ def _index(self, index: Tree) -> Expr:
307
+ if index.data == "short_index":
308
+ token = next(child for child in index.children if isinstance(child, Token) and child.type == "INT_LITERAL")
309
+ return Literal(int(str(token)))
310
+ (child,) = _trees(index)
311
+ return self.expr(child)
312
+
313
+ def _object_elem(self, elem: Tree) -> tuple[Expr, Expr]:
314
+ key_node, value = _trees(elem)
315
+ key_children = _trees(key_node)
316
+ key: Expr
317
+ if not key_children: # a keyword (`in`, `for`) as a key
318
+ key = Literal(str(key_node.children[0].children[0]) if isinstance(key_node.children[0], Tree) else str(key_node.children[0]))
319
+ else:
320
+ term = key_children[0]
321
+ inner = _trees(term) if term.data == "expr_term" else [term]
322
+ parenthesized = term.data == "expr_term" and any(isinstance(child, Token) and child.type == "LPAR" for child in term.children)
323
+ if not parenthesized and len(inner) == 1 and inner[0].data == "identifier":
324
+ key = Literal(str(inner[0].children[0]), source=self.source(term), line=self.line(term))
325
+ elif not parenthesized and len(inner) == 1 and inner[0].data == "keyword":
326
+ key = Literal(str(inner[0].children[0]), source=self.source(term), line=self.line(term))
327
+ else:
328
+ key = self.expr(term)
329
+ return key, self.expr(value)
330
+
331
+ def _call(self, node: Tree) -> Expr:
332
+ names = [str(child.children[0]) for child in _trees(node) if child.data == "identifier"]
333
+ if len(names) != 1:
334
+ raise _Unsupported("provider-defined function call")
335
+ arguments = next((child for child in _trees(node) if child.data == "arguments"), None)
336
+ args: tuple[Expr, ...] = ()
337
+ expand = False
338
+ if arguments is not None:
339
+ args = tuple(self.expr(child) for child in _trees(arguments))
340
+ expand = any(isinstance(child, Token) and child.type == "ELLIPSIS" for child in arguments.children)
341
+ return Call(names[0], args, expand)
342
+
343
+ def _string(self, node: Tree) -> Expr:
344
+ raw = self.source(node)
345
+ if "%{" in raw:
346
+ return parse_template(unescape(raw[1:-1]), line=self.line(node))
347
+ parts: list[str | Expr] = []
348
+ for part in _trees(node):
349
+ (child,) = part.children
350
+ if isinstance(child, Token):
351
+ text = str(child)
352
+ if child.type == "ESCAPED_INTERPOLATION":
353
+ text = text[1:] # $${ -> ${
354
+ elif child.type == "ESCAPED_DIRECTIVE":
355
+ text = text[1:]
356
+ else:
357
+ text = unescape(text)
358
+ _append_text(parts, text)
359
+ elif child.data == "interpolation":
360
+ (inner,) = _trees(child)
361
+ parts.append(self.expr(inner))
362
+ else:
363
+ raise _Unsupported("template directive (%{ ... })")
364
+ return _template(parts)
365
+
366
+ def _for(self, node: Tree, children: list[Tree], *, as_object: bool) -> Expr:
367
+ intro = children[0]
368
+ intro_children = _trees(intro)
369
+ identifiers = [str(child.children[0]) for child in intro_children if child.data == "identifier"]
370
+ iterable = self.expr(intro_children[-1])
371
+ key_var, value_var = (identifiers[0], identifiers[1]) if len(identifiers) == 2 else (None, identifiers[0])
372
+ rest = children[1:]
373
+ condition = None
374
+ if rest and rest[-1].data == "for_cond":
375
+ condition = self.expr(_trees(rest[-1])[0])
376
+ rest = rest[:-1]
377
+ grouping = any(isinstance(child, Token) and child.type == "ELLIPSIS" for child in node.children)
378
+ if as_object:
379
+ key, value = rest
380
+ return ForExpr(key_var, value_var, iterable, self.expr(value), key=self.expr(key), condition=condition, grouping=grouping)
381
+ (value,) = rest
382
+ return ForExpr(key_var, value_var, iterable, self.expr(value), condition=condition)
383
+
384
+
385
+ class _Unsupported(Exception):
386
+ pass
387
+
388
+
389
+ def _append_text(parts: list[str | Expr], text: str) -> None:
390
+ if parts and isinstance(parts[-1], str):
391
+ parts[-1] += text
392
+ elif text:
393
+ parts.append(text)
394
+
395
+
396
+ def _template(parts: list[str | Expr]) -> Expr:
397
+ if not parts:
398
+ return Literal("")
399
+ if len(parts) == 1 and isinstance(parts[0], str):
400
+ return Literal(parts[0])
401
+ return Template(tuple(parts))
402
+
403
+
404
+ def heredoc_text(token: str, *, trim: bool) -> str:
405
+ """The template text of a heredoc token (``<<EOT\\n...\\nEOT\\n``), indentation trimmed for ``<<-``."""
406
+ lines = token.split("\n")
407
+ body = lines[1:]
408
+ # The token ends with the closing marker line and a newline
409
+ while body and body[-1].strip() == "":
410
+ body.pop()
411
+ body = body[:-1]
412
+ if trim:
413
+ indents = [len(line) - len(line.lstrip(" \t")) for line in body if line.strip()]
414
+ indent = min(indents, default=0)
415
+ body = [line[indent:] for line in body]
416
+ return "".join(f"{line}\n" for line in body)
417
+
418
+
419
+ def parse_template(text: str, *, line: int = 0) -> Expr:
420
+ """Parse interpolations and nested if/for directives, including whitespace strip markers."""
421
+ tokens: list[str | Expr | tuple[str, str]] = []
422
+ literal = ""
423
+ index = 0
424
+ strip_next = False
425
+ while index < len(text):
426
+ if text.startswith(("$${", "%%{"), index):
427
+ literal += text[index + 1 : index + 3]
428
+ index += 3
429
+ continue
430
+ if not text.startswith(("${", "%{"), index):
431
+ literal += text[index]
432
+ index += 1
433
+ continue
434
+ end = _matching_brace(text, index + 2)
435
+ if end < 0:
436
+ return Unsupported("unterminated template sequence", source=text, line=line)
437
+ content = text[index + 2 : end]
438
+ if strip_next:
439
+ literal = literal.lstrip()
440
+ if content.startswith("~"):
441
+ literal = literal.rstrip()
442
+ if literal:
443
+ tokens.append(literal)
444
+ literal = ""
445
+ strip_next = content.endswith("~")
446
+ content = content.strip("~ \t\n\r")
447
+ tokens.append(("directive", content) if text[index] == "%" else parse_expression(content, line=line))
448
+ index = end + 1
449
+ if strip_next:
450
+ literal = literal.lstrip()
451
+ if literal:
452
+ tokens.append(literal)
453
+ cursor = 0
454
+
455
+ def read(stops: set[str]) -> tuple[Expr, str | None]:
456
+ nonlocal cursor
457
+ parts: list[str | Expr] = []
458
+ while cursor < len(tokens):
459
+ token = tokens[cursor]
460
+ cursor += 1
461
+ if not isinstance(token, tuple):
462
+ parts.append(token)
463
+ continue
464
+ _, command = token
465
+ if command in stops:
466
+ return _template(parts), command
467
+ if command.startswith("if "):
468
+ yes, stop = read({"else", "endif"})
469
+ no, closing = read({"endif"}) if stop == "else" else (Literal(""), stop)
470
+ if closing != "endif":
471
+ raise _Unsupported("template if needs endif")
472
+ # Directive bodies are text even when they contain just one interpolation.
473
+ yes = Call("join", (Literal(""), TupleExpr((yes,))))
474
+ no = Call("join", (Literal(""), TupleExpr((no,))))
475
+ parts.append(Conditional(parse_expression(command[3:].strip(), line=line), yes, no))
476
+ elif match := re.fullmatch(r"for\s+([\w-]+)(?:\s*,\s*([\w-]+))?\s+in\s+(.+)", command, re.DOTALL):
477
+ body, closing = read({"endfor"})
478
+ if closing != "endfor":
479
+ raise _Unsupported("template for needs endfor")
480
+ first, second, iterable = match.groups()
481
+ value_name, key_name = (second, first) if second else (first, None)
482
+ parts.append(Call("join", (Literal(""), ForExpr(key_name, value_name, parse_expression(iterable, line=line), body))))
483
+ else:
484
+ raise _Unsupported(f"invalid template directive: {command}")
485
+ return _template(parts), None
486
+
487
+ try:
488
+ result, _ = read(set())
489
+ except _Unsupported as error:
490
+ return Unsupported(str(error), source=text, line=line)
491
+ return result
492
+
493
+
494
+ def _matching_brace(text: str, start: int) -> int:
495
+ depth = 1
496
+ index = start
497
+ quote = False
498
+ while index < len(text):
499
+ char = text[index]
500
+ if quote:
501
+ if char == "\\":
502
+ index += 1
503
+ elif char == '"':
504
+ quote = False
505
+ elif char == '"':
506
+ quote = True
507
+ elif char == "{":
508
+ depth += 1
509
+ elif char == "}":
510
+ depth -= 1
511
+ if depth == 0:
512
+ return index
513
+ index += 1
514
+ return -1
515
+
516
+
517
+ def parse_expression(text: str, *, line: int = 0) -> Expr:
518
+ """One HCL expression from its source text."""
519
+ prefix = "x = "
520
+ try:
521
+ tree = hcl2.parses_to_tree(f"{prefix}{text}\n")
522
+ except Exception as error:
523
+ return Unsupported(f"cannot parse: {error.__class__.__name__}", source=text, line=line)
524
+ attribute = next(tree.find_data("attribute"))
525
+ expression = _trees(attribute)[1]
526
+ converter = NativeConverter(f"{prefix}{text}\n", first_line=line or 1)
527
+ result = converter.expr(expression)
528
+ return result
529
+
530
+
531
+ # --- Bodies ---------------------------------------------------------------------------------------
532
+
533
+
534
+ @dataclass
535
+ class Attribute:
536
+ name: str
537
+ value: Expr
538
+ line: int = 0
539
+
540
+
541
+ @dataclass
542
+ class Block:
543
+ """A block: its type, labels and body."""
544
+
545
+ type: str
546
+ labels: list[str]
547
+ body: Body
548
+ source: str = ""
549
+ line: int = 0
550
+ file: str = ""
551
+
552
+
553
+ @dataclass
554
+ class Body:
555
+ attributes: dict[str, Attribute] = field(default_factory=dict)
556
+ blocks: list[Block] = field(default_factory=list)
557
+
558
+ def get(self, name: str) -> Expr | None:
559
+ attribute = self.attributes.get(name)
560
+ return attribute.value if attribute else None
561
+
562
+ def blocks_of(self, block_type: str) -> list[Block]:
563
+ return [block for block in self.blocks if block.type == block_type]
564
+
565
+
566
+ def parse_native(text: str, file: str) -> Body:
567
+ """A ``.tf`` file's body."""
568
+ try:
569
+ tree = hcl2.parses_to_tree(text)
570
+ except Exception as error:
571
+ raise HclSyntaxError(f"{file}: {error}") from error
572
+ converter = NativeConverter(text if text.endswith("\n") else f"{text}\n")
573
+ (body,) = _trees(tree)
574
+ return _native_body(converter, body, file)
575
+
576
+
577
+ def _native_body(converter: NativeConverter, body: Tree, file: str) -> Body:
578
+ result = Body()
579
+ for child in _trees(body):
580
+ if child.data == "attribute":
581
+ name_node, value = _trees(child)
582
+ name = _label(name_node)
583
+ result.attributes[name] = Attribute(name, converter.expr(value), converter.line(child))
584
+ elif child.data == "block":
585
+ parts = _trees(child)
586
+ inner = parts[-1]
587
+ block_type = _label(parts[0])
588
+ labels = [_label(part) for part in parts[1:-1]]
589
+ result.blocks.append(Block(block_type, labels, _native_body(converter, inner, file), converter.source(child), converter.line(child), file))
590
+ return result
591
+
592
+
593
+ def _label(node: Tree) -> str:
594
+ if node.data == "string":
595
+ return "".join(unescape(str(part.children[0])) for part in _trees(node))
596
+ if node.data in {"identifier", "keyword", "literal_value"}:
597
+ return str(node.children[0])
598
+ raise HclSyntaxError(f"unexpected label {node.data}")
599
+
600
+
601
+ # --- JSON syntax ----------------------------------------------------------------------------------
602
+
603
+
604
+ def json_expr(value: Any) -> Expr:
605
+ """A JSON value of a ``.tf.json`` file as an expression: strings are templates."""
606
+ source = json.dumps(value)
607
+ if isinstance(value, str):
608
+ result = parse_template(value)
609
+ if not result.source:
610
+ object.__setattr__(result, "source", source)
611
+ return result
612
+ if isinstance(value, list):
613
+ return TupleExpr(tuple(json_expr(item) for item in value), source=source)
614
+ if isinstance(value, dict):
615
+ return ObjectExpr(tuple((Literal(key), json_expr(item)) for key, item in value.items() if key != "//"), source=source)
616
+ return Literal(value, source=source)
617
+
618
+
619
+ # Top-level JSON block types and how many labels each has
620
+ _JSON_LABELS = {"resource": 2, "data": 2, "ephemeral": 2, "module": 1, "provider": 1, "variable": 1, "output": 1, "locals": 0, "terraform": 0, "moved": 0, "import": 0, "removed": 0, "check": 1}
621
+ # Blocks inside JSON bodies that are always blocks (others depend on the provider's schema)
622
+ _JSON_META_BLOCKS = {"lifecycle", "provisioner", "connection", "dynamic", "required_providers", "backend", "validation", "precondition", "postcondition", "content"}
623
+
624
+
625
+ def parse_json(text: str, file: str) -> Body:
626
+ """A ``.tf.json`` file's body."""
627
+ try:
628
+ document = json.loads(text)
629
+ except json.JSONDecodeError as error:
630
+ raise HclSyntaxError(f"{file}: {error}") from error
631
+ result = Body()
632
+ for block_type, content in document.items():
633
+ if block_type == "//":
634
+ continue
635
+ labels = _JSON_LABELS.get(block_type)
636
+ if labels is None:
637
+ continue
638
+ for labels_list, body in _json_labelled(content, labels):
639
+ if block_type in {"locals"}:
640
+ for name, value in body.items():
641
+ result.blocks.append(Block("locals", [], Body({name: Attribute(name, json_expr(value))}), file=file))
642
+ continue
643
+ result.blocks.append(Block(block_type, labels_list, json_body(body, block_type=block_type), source=json.dumps({block_type: content}), file=file))
644
+ return result
645
+
646
+
647
+ def _json_labelled(content: Any, depth: int) -> Iterator[tuple[list[str], dict[str, Any]]]:
648
+ items = content if isinstance(content, list) else [content]
649
+ for item in items:
650
+ if depth == 0:
651
+ yield [], item
652
+ continue
653
+ for label, inner in item.items():
654
+ for labels, body in _json_labelled(inner, depth - 1):
655
+ yield [label, *labels], body
656
+
657
+
658
+ def json_body(content: Any, *, block_type: str = "") -> Body:
659
+ """A JSON object as a block body; its object values stay attributes but for meta blocks."""
660
+ result = Body()
661
+ for name, value in content.items():
662
+ if name == "//":
663
+ continue
664
+ is_block = name in _JSON_META_BLOCKS or (block_type == "terraform" and isinstance(value, dict))
665
+ if block_type == "variable" and name == "type" and isinstance(value, str):
666
+ result.attributes[name] = Attribute(name, parse_expression(value))
667
+ continue
668
+ if block_type in {"lifecycle"} and name in {"ignore_changes", "replace_triggered_by"}:
669
+ result.attributes[name] = Attribute(name, _json_traversals(value))
670
+ continue
671
+ if block_type == "resource_meta" and name == "depends_on":
672
+ result.attributes[name] = Attribute(name, _json_traversals(value))
673
+ continue
674
+ if name == "depends_on" and isinstance(value, list):
675
+ result.attributes[name] = Attribute(name, _json_traversals(value))
676
+ continue
677
+ if name == "provider" and isinstance(value, str) and block_type in {"resource", "data", "ephemeral"}:
678
+ result.attributes[name] = Attribute(name, parse_expression(value))
679
+ continue
680
+ if is_block:
681
+ labelled = name in {"provisioner", "dynamic", "backend"}
682
+ entries = value if isinstance(value, list) else [value]
683
+ for entry in entries:
684
+ if labelled:
685
+ for label, inner in entry.items():
686
+ for item in inner if isinstance(inner, list) else [inner]:
687
+ result.blocks.append(Block(name, [label], json_body(item, block_type=name), source=json.dumps({name: entry})))
688
+ else:
689
+ result.blocks.append(Block(name, [], json_body(entry, block_type=name), source=json.dumps({name: entry})))
690
+ continue
691
+ result.attributes[name] = Attribute(name, json_expr(value))
692
+ return result
693
+
694
+
695
+ def _json_traversals(value: Any) -> Expr:
696
+ """``["aws_vpc.main", "tags"]``: JSON writes references and attribute names as strings."""
697
+ if isinstance(value, list):
698
+ return TupleExpr(tuple(parse_expression(item) if isinstance(item, str) else json_expr(item) for item in value), source=json.dumps(value))
699
+ if isinstance(value, str):
700
+ return parse_expression(value)
701
+ return json_expr(value)
702
+
703
+
704
+ def object_to_bodies(expr: Expr) -> list[Body] | None:
705
+ """An object (or a list of objects) given where a block is expected, as block bodies (JSON syntax)."""
706
+ if isinstance(expr, ObjectExpr):
707
+ body = Body()
708
+ for key, value in expr.items:
709
+ if not isinstance(key, Literal) or not isinstance(key.value, str):
710
+ return None
711
+ body.attributes[key.value] = Attribute(key.value, value)
712
+ return [body]
713
+ if isinstance(expr, TupleExpr):
714
+ bodies: list[Body] = []
715
+ for item in expr.items:
716
+ converted = object_to_bodies(item)
717
+ if converted is None:
718
+ return None
719
+ bodies.extend(converted)
720
+ return bodies
721
+ return None