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,701 @@
1
+ """Translate HCL expressions to Python code.
2
+
3
+ Static values become plain Python (a variable's ``upper(var.name)`` is ``name.upper()``), runtime
4
+ values become netherframe runtime values (a resource attribute is ``vpc.ref_id_``, an operation on
5
+ one an operator or an ``Fn`` call), and what has no translation becomes the original expression as
6
+ a Terraform string (``"${...}"``) with a TODO marker.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import functools
12
+ from dataclasses import dataclass, field
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ from netherframe.generation.providers.codegen_support import safe_name
16
+
17
+ from .hcl_ast import (
18
+ BinaryOp,
19
+ Call,
20
+ Conditional,
21
+ Expr,
22
+ ForExpr,
23
+ GetAttr,
24
+ Index,
25
+ Literal,
26
+ Name,
27
+ ObjectExpr,
28
+ Splat,
29
+ Template,
30
+ TupleExpr,
31
+ UnaryOp,
32
+ Unsupported,
33
+ heredoc_text,
34
+ traversal,
35
+ unescape,
36
+ )
37
+ from .python_code import PRECEDENCE, Kind, Names, Py, identifier, join_kinds, literal, quote, string_body, value_kind
38
+
39
+ if TYPE_CHECKING:
40
+ from collections.abc import Callable
41
+
42
+
43
+ class Untranslatable(Exception):
44
+ """An expression without a translation; the caller writes it as a Terraform string."""
45
+
46
+
47
+ @dataclass
48
+ class Todo:
49
+ """A TODO marker: what was not converted, where, and its HCL."""
50
+
51
+ reason: str
52
+ hcl: str = ""
53
+ file: str = ""
54
+ line: int = 0
55
+
56
+
57
+ @dataclass
58
+ class Iterator:
59
+ """A loop variable of HCL (``each``, ``count``, a ``dynamic`` block's iterator, a ``for``'s names)."""
60
+
61
+ key: Py # count.index for count
62
+ value: Py | None
63
+
64
+
65
+ @dataclass
66
+ class Scope:
67
+ """What names mean while translating: the module's symbols, and loop variables."""
68
+
69
+ variables: dict[str, Py]
70
+ locals: dict[str, Py]
71
+ constructs: dict[str, Py] # "aws_vpc.main" / "data.aws_ami.x" / "ephemeral.T.N" -> construct (list/dict)
72
+ modules: dict[str, Py]
73
+ providers: dict[str, str] # "aws" / "aws.west" -> Python code of the provider object
74
+ resource_types: set[str]
75
+ path_module: str = "."
76
+ names: Names = field(default_factory=Names)
77
+ iterators: dict[str, Iterator] = field(default_factory=dict) # "each", "count", "subnet", "v"
78
+ for_vars: dict[str, Py] = field(default_factory=dict) # names a `for` expression binds
79
+
80
+ def child(self, *, iterators: dict[str, Iterator] | None = None, for_vars: dict[str, Py] | None = None) -> Scope:
81
+ return Scope(
82
+ self.variables,
83
+ self.locals,
84
+ self.constructs,
85
+ self.modules,
86
+ self.providers,
87
+ self.resource_types,
88
+ self.path_module,
89
+ self.names,
90
+ {**self.iterators, **(iterators or {})},
91
+ {**self.for_vars, **(for_vars or {})},
92
+ )
93
+
94
+
95
+ @functools.cache
96
+ def _fn_catalog() -> Any:
97
+ try:
98
+ from netherframe.core.functions.functions import Fn
99
+ except Exception: # no catalog installed: emit Fn calls unchecked
100
+ return None
101
+ return Fn
102
+
103
+
104
+ class Translator:
105
+ """Translates the expressions of one module; collects the imports and helpers they need."""
106
+
107
+ def __init__(self, scope: Scope, file: str = "") -> None:
108
+ self.scope = scope
109
+ self.file = file
110
+ self.todos: list[Todo] = []
111
+ self.imports: set[tuple[str, str]] = set() # (module, name)
112
+ self.helpers: set[str] = set() # names from the package's _support module
113
+
114
+ # --- Entry points ------------------------------------------------------------------------
115
+
116
+ def translate(self, expr: Expr, scope: Scope | None = None, *, context: str = "") -> Py:
117
+ """``expr`` as Python; an untranslatable part becomes a Terraform string with a TODO."""
118
+ scope = scope or self.scope
119
+ try:
120
+ return self._expr(expr, scope)
121
+ except Untranslatable as error:
122
+ return self.fallback(expr, str(error), context=context)
123
+
124
+ def fallback(self, expr: Expr, reason: str, *, context: str = "") -> Py:
125
+ source = expr.source.strip()
126
+ what = f"{context}: " if context else ""
127
+ self.todos.append(Todo(f"{what}{reason}", source, self.file, expr.line))
128
+ self.import_name("netherframe.core.values.hcl_expressions", "RawHcl")
129
+ return Py(f"_nf_RawHcl({quote(terraform_text(expr))})", Kind.RUNTIME)
130
+
131
+ # --- Expressions -------------------------------------------------------------------------
132
+
133
+ def _expr(self, expr: Expr, scope: Scope) -> Py: # noqa: PLR0911
134
+ match expr:
135
+ case Literal(value=value):
136
+ return Py(literal(value), Kind.STATIC)
137
+ case Template():
138
+ return self._template(expr, scope)
139
+ case TupleExpr(items=items):
140
+ values = [self._expr(item, scope) for item in items]
141
+ entries = ", ".join(value.code for value in values)
142
+ return Py(f"[{entries}]", join_kinds(*(value.kind for value in values)), shape="list", entries=entries)
143
+ case ObjectExpr(items=items):
144
+ return self._object(items, scope)
145
+ case Name() | GetAttr() | Index():
146
+ return self._traversal(expr, scope)
147
+ case Splat(obj=obj, steps=steps):
148
+ return self._splat(self._expr(obj, scope), steps, scope)
149
+ case Call():
150
+ return self._call(expr, scope)
151
+ case BinaryOp():
152
+ return self._binary(expr, scope)
153
+ case UnaryOp(op=op, operand=operand):
154
+ value = self._expr(operand, scope)
155
+ if op == "-":
156
+ return Py(f"-{value.operand(PRECEDENCE['unary'])}", value_kind(value.kind), precedence=PRECEDENCE["unary"])
157
+ if value.static:
158
+ return Py(value.negated(), Kind.STATIC, precedence=PRECEDENCE["not"] if value.negation is None else value.precedence, negation=value.code)
159
+ return Py(f"~{value.operand(PRECEDENCE['unary'])}", Kind.RUNTIME, precedence=PRECEDENCE["unary"])
160
+ case Conditional(condition=condition, if_true=if_true, if_false=if_false):
161
+ test = self._expr(condition, scope)
162
+ yes = self._expr(if_true, scope)
163
+ no = self._expr(if_false, scope)
164
+ if test.static:
165
+ kind = yes.kind if yes.kind == no.kind else max(Kind.MIXED, value_kind(yes.kind, no.kind))
166
+ shape = yes.shape if yes.shape == no.shape else None
167
+ return Py(f"{yes.operand(2)} if {test.operand(2)} else {no.operand(1)}", kind, precedence=PRECEDENCE["if"], shape=shape, binding=yes.binding or no.binding)
168
+ return self._fn_call("conditional", [test.code, yes.code, no.code])
169
+ case ForExpr():
170
+ return self._for(expr, scope)
171
+ case Unsupported(reason=reason):
172
+ raise Untranslatable(reason)
173
+ case _:
174
+ raise Untranslatable(f"unsupported expression {type(expr).__name__}")
175
+
176
+ def _untranslatable(self, reason: str) -> Py:
177
+ raise Untranslatable(reason)
178
+
179
+ def _use_fn(self) -> bool:
180
+ self.imports.add(("netherframe.core", "Fn"))
181
+ return True
182
+
183
+ def _template(self, expr: Template, scope: Scope) -> Py:
184
+ if len(expr.parts) == 1 and isinstance(expr.parts[0], Expr):
185
+ return self._expr(expr.parts[0], scope) # "${x}" is x itself
186
+ pieces: list[str] = []
187
+ kinds: list[Kind] = []
188
+ for part in expr.parts:
189
+ if isinstance(part, str):
190
+ pieces.append(string_body(part).replace("{", "{{").replace("}", "}}"))
191
+ continue
192
+ value = self._expr(part, scope)
193
+ if value.kind in {Kind.CONSTRUCT, Kind.CONSTRUCTS, Kind.MODULE, Kind.MODULES}:
194
+ raise Untranslatable("a construct or module object in a string")
195
+ kinds.append(value.kind)
196
+ code = value.operand(2)
197
+ if value.static:
198
+ self.import_name("netherframe.core.values.terraform_operations", "to_string")
199
+ code = f"_nf_to_string({value.code})"
200
+ pieces.append("{" + code + "}")
201
+ return Py('f"' + "".join(pieces) + '"', value_kind(*kinds))
202
+
203
+ def _object(self, items: tuple[tuple[Expr, Expr], ...], scope: Scope) -> Py:
204
+ entries: list[str] = []
205
+ kinds: list[Kind] = []
206
+ for key, value in items:
207
+ key_py = self._expr(key, scope)
208
+ if not key_py.static:
209
+ raise Untranslatable("an object key computed from a runtime value")
210
+ value_py = self._expr(value, scope)
211
+ kinds.append(value_py.kind)
212
+ entries.append(f"{key_py.code}: {value_py.code}")
213
+ return Py("{" + ", ".join(entries) + "}", join_kinds(*kinds), shape="map", entries=", ".join(entries))
214
+
215
+ # --- References --------------------------------------------------------------------------
216
+
217
+ def _traversal(self, expr: Expr, scope: Scope) -> Py:
218
+ path = traversal(expr)
219
+ if path is None:
220
+ # an index or attribute of something else (a call, a parenthesized expression)
221
+ if isinstance(expr, GetAttr):
222
+ return self._get_attr(self._expr(expr.obj, scope), expr.name)
223
+ if isinstance(expr, Index):
224
+ return self._index(self._expr(expr.obj, scope), self._expr(expr.key, scope))
225
+ raise Untranslatable("unsupported reference")
226
+ root, steps = path
227
+ value, rest = self._root(root, list(steps), scope)
228
+ for step in rest:
229
+ value = self._get_attr(value, step) if isinstance(step, str) else self._index(value, self._expr(step, scope))
230
+ return value
231
+
232
+ def _root(self, root: str, steps: list[str | Expr], scope: Scope) -> tuple[Py, list[str | Expr]]: # noqa: PLR0911, PLR0912
233
+ def name_at(index: int) -> str:
234
+ if index >= len(steps) or not isinstance(steps[index], str):
235
+ raise Untranslatable(f"incomplete reference to {root}")
236
+ return str(steps[index])
237
+
238
+ if root in scope.for_vars:
239
+ return scope.for_vars[root], steps
240
+ if root in scope.iterators:
241
+ iterator = scope.iterators[root]
242
+ attribute = name_at(0)
243
+ value = {"key": iterator.key, "value": iterator.value, "index": iterator.key}.get(attribute)
244
+ if value is None:
245
+ raise Untranslatable(f"{root}.{attribute} is not available here")
246
+ return value, steps[1:]
247
+ if root == "var":
248
+ name = name_at(0)
249
+ if name not in scope.variables:
250
+ raise Untranslatable(f"undeclared variable {name}")
251
+ return scope.variables[name], steps[1:]
252
+ if root == "local":
253
+ name = name_at(0)
254
+ if name not in scope.locals:
255
+ raise Untranslatable(f"undeclared local value {name}")
256
+ return scope.locals[name], steps[1:]
257
+ if root == "data":
258
+ key = f"data.{name_at(0)}.{name_at(1)}"
259
+ if key not in scope.constructs:
260
+ raise Untranslatable(f"undeclared data source {key}")
261
+ return scope.constructs[key], steps[2:]
262
+ if root == "ephemeral":
263
+ key = f"ephemeral.{name_at(0)}.{name_at(1)}"
264
+ if key not in scope.constructs:
265
+ raise Untranslatable(f"undeclared ephemeral resource {key}")
266
+ return scope.constructs[key], steps[2:]
267
+ if root == "module":
268
+ name = name_at(0)
269
+ if name not in scope.modules:
270
+ raise Untranslatable(f"undeclared module {name}")
271
+ return scope.modules[name], steps[1:]
272
+ if root == "path":
273
+ name = name_at(0)
274
+ if name == "module":
275
+ return Py(quote(scope.path_module), Kind.STATIC), steps[1:]
276
+ if name in {"root", "cwd"}:
277
+ return Py(quote("."), Kind.STATIC), steps[1:]
278
+ raise Untranslatable(f"path.{name}")
279
+ if root == "terraform" and steps[:1] == ["workspace"]:
280
+ raise Untranslatable("terraform.workspace has no netherframe equivalent")
281
+ if root in scope.resource_types:
282
+ key = f"{root}.{name_at(0)}"
283
+ if key not in scope.constructs:
284
+ raise Untranslatable(f"undeclared resource {key}")
285
+ return scope.constructs[key], steps[1:]
286
+ if root == "self":
287
+ raise Untranslatable("self is only available to provisioners and conditions")
288
+ raise Untranslatable(f"unknown reference {root}")
289
+
290
+ def _get_attr(self, value: Py, name: str) -> Py:
291
+ if value.kind is Kind.CONSTRUCT:
292
+ if value.binding is None:
293
+ raise Untranslatable(f"an attribute of {value.code}, whose type is not known")
294
+ return Py(value.binding.attribute_ref(value.code, name), Kind.RUNTIME)
295
+ if value.kind is Kind.MODULE:
296
+ if value.module is None:
297
+ raise Untranslatable(f"refers to {value.code.removeprefix('self.')}, a module that is not converted")
298
+ output = value.module_outputs.get(name, identifier(name))
299
+ return Py(f"{value.code}.{output}", Kind.RUNTIME)
300
+ if value.kind in {Kind.CONSTRUCTS, Kind.MODULES}:
301
+ raise Untranslatable("an attribute of a resource or module with count or for_each needs an index or a splat")
302
+ return Py(f"{value.operand()}[{quote(name)}]", value.kind if value.kind is not Kind.MIXED else Kind.MIXED)
303
+
304
+ def _index(self, value: Py, key: Py) -> Py:
305
+ if value.kind is Kind.MODULE and value.module is None:
306
+ raise Untranslatable(f"refers to {value.code.removeprefix('self.')}, a module that is not converted")
307
+ if value.kind in {Kind.CONSTRUCTS, Kind.MODULES}:
308
+ if not key.static:
309
+ raise Untranslatable("an index of count or for_each instances computed from a runtime value")
310
+ kind = Kind.CONSTRUCT if value.kind is Kind.CONSTRUCTS else Kind.MODULE
311
+ return Py(f"{value.code}[{key.code}]", kind, binding=value.binding, module=value.module, module_outputs=value.module_outputs)
312
+ if value.kind in {Kind.CONSTRUCT, Kind.MODULE}:
313
+ raise Untranslatable("an index of a resource or module without count or for_each")
314
+ if value.python_container and not key.static:
315
+ self._use_fn()
316
+ function = "lookup" if value.shape == "map" else "element"
317
+ return Py(f"_nf_Fn.{function}({value.code}, {key.code})", Kind.RUNTIME)
318
+ return Py(f"{value.operand()}[{key.code}]", value.kind)
319
+
320
+ def _splat(self, value: Py, steps: tuple[str | Expr, ...], scope: Scope) -> Py:
321
+ item_name = scope.names.allocate("item")
322
+ try:
323
+ if value.kind is Kind.CONSTRUCTS:
324
+ item = Py(item_name, Kind.CONSTRUCT, binding=value.binding)
325
+ source = f"{value.code}.values()" if value.shape == "map" else value.code
326
+ elif value.kind is Kind.CONSTRUCT:
327
+ item = Py(item_name, Kind.CONSTRUCT, binding=value.binding)
328
+ source = f"[{value.code}]"
329
+ elif value.python_container:
330
+ item = Py(item_name, value.kind)
331
+ source = value.code
332
+ else:
333
+ raise Untranslatable("a splat of a runtime value")
334
+ for step in steps:
335
+ item = self._get_attr(item, step) if isinstance(step, str) else self._index(item, self._expr(step, scope))
336
+ return Py(f"[{item.code} for {item_name} in {source}]", join_kinds(value.kind, item.kind), shape="list")
337
+ finally:
338
+ scope.names.taken.discard(item_name)
339
+
340
+ def _for(self, expr: ForExpr, scope: Scope) -> Py:
341
+ iterable = self._expr(expr.iterable, scope)
342
+ if not iterable.python_container or expr.grouping:
343
+ return self._runtime_for(expr, iterable, scope)
344
+ names = scope.names
345
+ value_name = names.allocate(expr.value_var)
346
+ key_name = names.allocate(expr.key_var) if expr.key_var else None
347
+ try:
348
+ element_kind = Kind.CONSTRUCT if iterable.kind is Kind.CONSTRUCTS else iterable.kind
349
+ value_py = Py(value_name, element_kind, binding=iterable.binding)
350
+ bound = {expr.value_var: value_py}
351
+ if key_name and expr.key_var:
352
+ bound[expr.key_var] = Py(key_name, Kind.STATIC)
353
+ inner = scope.child(for_vars=bound)
354
+ loop = self._loop_clause(iterable, key_name, value_name)
355
+ result = self._expr(expr.value, inner)
356
+ predicate = self._expr(expr.condition, inner) if expr.condition is not None else None
357
+ if predicate is not None and not predicate.static:
358
+ return self._runtime_for(expr, iterable, scope)
359
+ condition = f" if {predicate.operand(2)}" if predicate is not None else ""
360
+ if expr.key is not None:
361
+ key = self._expr(expr.key, inner)
362
+ if not key.static:
363
+ raise Untranslatable("a for expression with keys computed from runtime values")
364
+ return Py(f"{{{key.code}: {result.code} {loop}{condition}}}", join_kinds(result.kind), shape="map")
365
+ return Py(f"[{result.code} {loop}{condition}]", join_kinds(result.kind), shape="list")
366
+ finally:
367
+ names.taken.discard(value_name)
368
+ if key_name:
369
+ names.taken.discard(key_name)
370
+
371
+ def _runtime_for(self, expr: ForExpr, iterable: Py, scope: Scope) -> Py:
372
+ self.import_name("netherframe.core.values.hcl_expressions", "Bound")
373
+ self.import_name("netherframe.core.values.hcl_expressions", "Comprehension")
374
+ names = scope.names
375
+ value_name = names.allocate(expr.value_var)
376
+ key_name = names.allocate(expr.key_var) if expr.key_var else None
377
+ try:
378
+ bound = {expr.value_var: Py(f"_nf_Bound({quote(value_name)})", Kind.RUNTIME)}
379
+ if key_name and expr.key_var:
380
+ bound[expr.key_var] = Py(f"_nf_Bound({quote(key_name)})", Kind.RUNTIME)
381
+ inner = scope.child(for_vars=bound)
382
+ value = self._expr(expr.value, inner)
383
+ self.import_name("netherframe.core.values.hcl_expressions", "hcl_value")
384
+ arguments = [f"_nf_hcl_value({iterable.code})", quote(value_name), f"_nf_hcl_value({value.code})"]
385
+ if key_name:
386
+ arguments.append(f"key_name={quote(key_name)}")
387
+ if expr.key is not None:
388
+ arguments.append(f"key=_nf_hcl_value({self._expr(expr.key, inner).code})")
389
+ if expr.condition is not None:
390
+ arguments.append(f"condition={self._expr(expr.condition, inner).code}")
391
+ if expr.grouping:
392
+ arguments.append("grouping=True")
393
+ return Py(f"_nf_Comprehension({', '.join(arguments)})", Kind.RUNTIME, shape="map" if expr.key is not None else "list")
394
+ finally:
395
+ names.taken.discard(value_name)
396
+ if key_name:
397
+ names.taken.discard(key_name)
398
+
399
+ def _loop_clause(self, iterable: Py, key_name: str | None, value_name: str) -> str:
400
+ """``for k, v in ...`` over a list (index, element), a set (element) or a map (key, value)."""
401
+ if iterable.shape == "map":
402
+ return f"for {key_name}, {value_name} in {iterable.code}.items()" if key_name else f"for {value_name} in {iterable.code}.values()"
403
+ if iterable.shape in {"list", "set"}:
404
+ return f"for {key_name}, {value_name} in enumerate({iterable.code})" if key_name else f"for {value_name} in {iterable.operand()}"
405
+ self.helpers.add("items")
406
+ if key_name:
407
+ return f"for {key_name}, {value_name} in _nf_items({iterable.code})"
408
+ return f"for _, {value_name} in _nf_items({iterable.code})"
409
+
410
+ # --- Operators ---------------------------------------------------------------------------
411
+
412
+ _ARITHMETIC = frozenset({"+", "-", "*", "/", "%", "<", ">", "<=", ">="})
413
+
414
+ def _binary(self, expr: BinaryOp, scope: Scope) -> Py:
415
+ left = self._expr(expr.left, scope)
416
+ right = self._expr(expr.right, scope)
417
+ op = expr.op
418
+ both_static = left.static and right.static
419
+ if not both_static:
420
+ from dataclasses import replace
421
+
422
+ self.import_name("netherframe.core.values.hcl_expressions", "hcl_value")
423
+ left = replace(left, code=f"_nf_hcl_value({left.code})", precedence=14) if left.python_container else left
424
+ right = replace(right, code=f"_nf_hcl_value({right.code})", precedence=14) if right.python_container else right
425
+ level = PRECEDENCE.get(op, 0)
426
+ if op in self._ARITHMETIC:
427
+ # Comparisons chain in Python, so neither side of one may be a comparison
428
+ left_minimum = level + 1 if level == PRECEDENCE["<"] else level
429
+ return Py(f"{left.operand(left_minimum)} {op} {right.operand(level + 1)}", value_kind(left.kind, right.kind), precedence=level)
430
+ if op in {"==", "!="}:
431
+ if both_static:
432
+ negation = f"{left.operand(level + 1)} {'!=' if op == '==' else '=='} {right.operand(level + 1)}"
433
+ return Py(f"{left.operand(level + 1)} {op} {right.operand(level + 1)}", Kind.STATIC, precedence=level, negation=negation)
434
+ runtime, other = (left, right) if not left.static else (right, left)
435
+ method = "eq" if op == "==" else "ne"
436
+ return Py(f"{runtime.operand()}.{method}({other.code})", Kind.RUNTIME)
437
+ if op in {"&&", "||"}:
438
+ if both_static:
439
+ python_op = "and" if op == "&&" else "or"
440
+ level = PRECEDENCE[python_op]
441
+ return Py(f"{left.operand(level)} {python_op} {right.operand(level + 1)}", Kind.STATIC, precedence=level)
442
+ python_op = "&" if op == "&&" else "|"
443
+ level = PRECEDENCE[python_op]
444
+ return Py(f"{left.operand(level)} {python_op} {right.operand(level + 1)}", Kind.RUNTIME, precedence=level)
445
+ raise Untranslatable(f"operator {op}")
446
+
447
+ # --- Functions ---------------------------------------------------------------------------
448
+
449
+ def _call(self, expr: Call, scope: Scope) -> Py:
450
+ args = [self._expr(arg, scope) for arg in expr.args]
451
+ if expr.name in {"try", "can"}:
452
+ if not args or (expr.name == "can" and len(args) != 1) or expr.expand_final:
453
+ raise Untranslatable(f"invalid {expr.name}() arguments")
454
+ function = f"{expr.name}_expression"
455
+ self.import_name("netherframe.core.values.hcl_expressions", function)
456
+ return Py(f"_nf_{function}({', '.join(f'lambda: {arg.code}' for arg in args)})", value_kind(*(arg.kind for arg in args)))
457
+ if expr.expand_final:
458
+ if not args or not args[-1].python_container:
459
+ raise Untranslatable(f"{expr.name}(...) expanding a runtime value")
460
+ *head, last = args
461
+ if all(arg.static for arg in args):
462
+ python = PYTHON_FUNCTIONS.get(expr.name)
463
+ if python is not None and expr.name in _VARIADIC:
464
+ result = python([*head, Py(f"*{last.operand()}", last.kind)], self)
465
+ if result is not None:
466
+ return result
467
+ return self._fn_call(expr.name, [*(arg.code for arg in head), f"*{last.operand()}"])
468
+ python = PYTHON_FUNCTIONS.get(expr.name)
469
+ if python is not None:
470
+ result = python(args, self)
471
+ if result is not None:
472
+ return result
473
+ return self._fn_call(expr.name, [arg.code for arg in args])
474
+
475
+ def _fn_call(self, name: str, codes: list[str]) -> Py:
476
+ method = safe_name(name)
477
+ catalog = _fn_catalog()
478
+ if catalog is not None and not hasattr(catalog, method):
479
+ raise Untranslatable(f"function {name} is not in the installed function catalog")
480
+ self._use_fn()
481
+ self.import_name("netherframe.core.values.hcl_expressions", "hcl_value")
482
+ protected = [f"*_nf_hcl_value({code[1:]})" if code.startswith("*") else f"_nf_hcl_value({code})" for code in codes]
483
+ return Py(f"_nf_Fn.{method}({', '.join(protected)})", Kind.RUNTIME)
484
+
485
+ def import_name(self, module: str, name: str) -> None:
486
+ self.imports.add((module, name))
487
+
488
+
489
+ def terraform_text(expr: Expr) -> str:
490
+ """An expression as Terraform reads it in a JSON string: a template stays text, others ``${...}``."""
491
+ source = expr.source.strip()
492
+ if source.startswith("<<"):
493
+ return heredoc_text(f"{source}\n", trim=source.startswith("<<-"))
494
+ if len(source) >= 2 and source.startswith('"') and source.endswith('"'):
495
+ return unescape(source[1:-1])
496
+ if source.startswith("${") or ("%{" in source and not source.startswith(("[", "{"))):
497
+ return source # already template text (a JSON string)
498
+ return f"${{{source}}}"
499
+
500
+
501
+ # --- Python equivalents of Terraform functions -------------------------------------------------
502
+
503
+ _VARIADIC = frozenset({"concat", "merge", "min", "max", "coalesce"})
504
+
505
+
506
+ def _static(*args: Py) -> bool:
507
+ return all(arg.static for arg in args)
508
+
509
+
510
+ def _containers(*args: Py) -> bool:
511
+ return all(arg.python_container for arg in args)
512
+
513
+
514
+ def _length(args: list[Py], tr: Translator) -> Py | None:
515
+ if len(args) == 1 and args[0].python_container and (args[0].static or args[0].shape in {"list", "map", "set"} or args[0].kind in {Kind.CONSTRUCTS, Kind.MODULES}):
516
+ return Py(f"len({args[0].code})", Kind.STATIC)
517
+ return None
518
+
519
+
520
+ def _method(method: str) -> Callable[[list[Py], Translator], Py | None]:
521
+ def translate(args: list[Py], tr: Translator) -> Py | None:
522
+ if len(args) == 1 and _static(*args):
523
+ return Py(f"{args[0].operand()}.{method}()", Kind.STATIC)
524
+ return None
525
+
526
+ return translate
527
+
528
+
529
+ def _join(args: list[Py], tr: Translator) -> Py | None:
530
+ if len(args) == 2 and _static(*args):
531
+ tr.import_name("netherframe.core.values.terraform_operations", "to_string")
532
+ return Py(f"{args[0].operand()}.join(_nf_to_string(_nf_item) for _nf_item in {args[1].operand()})", Kind.STATIC)
533
+ if len(args) == 2:
534
+ tr.import_name("netherframe.core.values.expressions", "MethodCallResult")
535
+ return Py(f'_nf_MethodCallResult({args[0].code}, "join", ({args[1].code},), {{}})', Kind.RUNTIME)
536
+ return None
537
+
538
+
539
+ def _split(args: list[Py], tr: Translator) -> Py | None:
540
+ if len(args) == 2 and _static(*args):
541
+ return Py(f"{args[1].operand()}.split({args[0].code})", Kind.STATIC, shape="list")
542
+ return None
543
+
544
+
545
+ def _concat(args: list[Py], tr: Translator) -> Py | None:
546
+ if _containers(*args):
547
+ parts = [arg.code if arg.code.startswith("*") else arg.entries if arg.entries is not None else f"*{arg.operand()}" for arg in args]
548
+ return Py("[" + ", ".join(part for part in parts if part) + "]", join_kinds(*(arg.kind for arg in args)), shape="list")
549
+ return None
550
+
551
+
552
+ def _merge(args: list[Py], tr: Translator) -> Py | None:
553
+ if _containers(*args):
554
+ parts = [arg.entries if arg.entries is not None else f"**{arg.operand()}" for arg in args]
555
+ return Py("{" + ", ".join(part for part in parts if part) + "}", join_kinds(*(arg.kind for arg in args)), shape="map")
556
+ return None
557
+
558
+
559
+ def _lookup(args: list[Py], tr: Translator) -> Py | None:
560
+ if len(args) in {2, 3} and args[0].python_container and args[1].static:
561
+ if len(args) == 2:
562
+ return Py(f"{args[0].operand()}[{args[1].code}]", args[0].kind)
563
+ return Py(f"{args[0].operand()}.get({args[1].code}, {args[2].code})", join_kinds(args[0].kind, args[2].kind))
564
+ return None
565
+
566
+
567
+ def _keys(args: list[Py], tr: Translator) -> Py | None:
568
+ if len(args) == 1 and args[0].python_container:
569
+ return Py(f"sorted({args[0].code})", Kind.STATIC, shape="list")
570
+ return None
571
+
572
+
573
+ def _values(args: list[Py], tr: Translator) -> Py | None:
574
+ if len(args) == 1 and args[0].python_container:
575
+ kind = Kind.CONSTRUCTS if args[0].kind is Kind.CONSTRUCTS else Kind.MODULES if args[0].kind is Kind.MODULES else args[0].kind
576
+ return Py(f"[value for _, value in sorted({args[0].operand()}.items())]", kind, binding=args[0].binding, shape="list", module=args[0].module, module_outputs=args[0].module_outputs)
577
+ return None
578
+
579
+
580
+ def _element(args: list[Py], tr: Translator) -> Py | None:
581
+ if len(args) == 2 and args[0].python_container and args[1].static:
582
+ container = args[0]
583
+ kind = Kind.CONSTRUCT if container.kind is Kind.CONSTRUCTS else container.kind
584
+ return Py(f"{container.operand()}[{args[1].operand(PRECEDENCE['%'])} % len({container.code})]", kind, binding=container.binding)
585
+ return None
586
+
587
+
588
+ def _contains(args: list[Py], tr: Translator) -> Py | None:
589
+ if len(args) == 2 and _static(*args):
590
+ return Py(f"{args[1].operand(6)} in {args[0].operand(6)}", Kind.STATIC, precedence=PRECEDENCE["in"], negation=f"{args[1].operand(6)} not in {args[0].operand(6)}")
591
+ return None
592
+
593
+
594
+ def _toset(args: list[Py], tr: Translator) -> Py | None:
595
+ if len(args) == 1 and args[0].python_container:
596
+ if args[0].static:
597
+ return Py(f"sorted(set({args[0].code}))", Kind.STATIC, shape="set")
598
+ return Py(args[0].code, args[0].kind, precedence=args[0].precedence, shape="set", binding=args[0].binding)
599
+ return None
600
+
601
+
602
+ def _tolist(args: list[Py], tr: Translator) -> Py | None:
603
+ if len(args) == 1 and args[0].python_container:
604
+ return Py(f"list({args[0].code})", args[0].kind, shape="list", binding=args[0].binding)
605
+ return None
606
+
607
+
608
+ def _tomap(args: list[Py], tr: Translator) -> Py | None:
609
+ if len(args) == 1 and args[0].python_container:
610
+ return Py(f"dict({args[0].code})", args[0].kind, shape="map", binding=args[0].binding)
611
+ return None
612
+
613
+
614
+ def _builtin(name: str, *, variadic: bool = True) -> Callable[[list[Py], Translator], Py | None]:
615
+ def translate(args: list[Py], tr: Translator) -> Py | None:
616
+ if args and _static(*args) and (variadic or len(args) == 1):
617
+ return Py(f"{name}({', '.join(arg.code for arg in args)})", Kind.STATIC)
618
+ return None
619
+
620
+ return translate
621
+
622
+
623
+ def _replace(args: list[Py], tr: Translator) -> Py | None:
624
+ # Terraform treats a substring between slashes as a regular expression
625
+ if len(args) == 3 and _static(*args) and args[1].code.startswith('"') and not args[1].code.startswith('"/'):
626
+ return Py(f"{args[0].operand()}.replace({args[1].code}, {args[2].code})", Kind.STATIC)
627
+ return None
628
+
629
+
630
+ def _range(args: list[Py], tr: Translator) -> Py | None:
631
+ if 1 <= len(args) <= 3 and _static(*args):
632
+ return Py(f"list(range({', '.join(arg.code for arg in args)}))", Kind.STATIC, shape="list")
633
+ return None
634
+
635
+
636
+ def _jsonencode(args: list[Py], tr: Translator) -> Py | None:
637
+ if len(args) == 1 and args[0].static:
638
+ tr.import_name("json", "")
639
+ return Py(f'_nf_json.dumps({args[0].code}, sort_keys=True, separators=(",", ":"))', Kind.STATIC)
640
+ return None
641
+
642
+
643
+ def _format(args: list[Py], tr: Translator) -> Py | None:
644
+ if not args or not _static(*args) or not args[0].code.startswith('"'):
645
+ return None
646
+ pattern = args[0].code
647
+ if any(verb in pattern for verb in ("%v", "%#v", "%t", "%q", "%[")):
648
+ return None
649
+ if len(args) == 1:
650
+ return Py(f"{pattern} % ()", Kind.STATIC, precedence=PRECEDENCE["%"])
651
+ return Py(f"{pattern} % ({', '.join(arg.code for arg in args[1:])},)", Kind.STATIC, precedence=PRECEDENCE["%"])
652
+
653
+
654
+ def _file(args: list[Py], tr: Translator) -> Py | None:
655
+ if len(args) == 1 and args[0].static:
656
+ tr.import_name("pathlib", "Path")
657
+ return Py(f"_nf_Path({args[0].code}).read_text()", Kind.STATIC)
658
+ return None
659
+
660
+
661
+ def _tostring(args: list[Py], tr: Translator) -> Py | None:
662
+ if len(args) == 1 and args[0].static:
663
+ tr.helpers.add("tf_tostring")
664
+ return Py(f"_nf_tf_tostring({args[0].code})", Kind.STATIC)
665
+ return None
666
+
667
+
668
+ def _sort(args: list[Py], tr: Translator) -> Py | None:
669
+ if len(args) == 1 and args[0].static:
670
+ return Py(f"sorted({args[0].code})", Kind.STATIC, shape="list")
671
+ return None
672
+
673
+
674
+ PYTHON_FUNCTIONS: dict[str, Callable[[list[Py], Translator], Py | None]] = {
675
+ "length": _length,
676
+ "upper": _method("upper"),
677
+ "lower": _method("lower"),
678
+ "trimspace": _method("strip"),
679
+ "join": _join,
680
+ "split": _split,
681
+ "concat": _concat,
682
+ "merge": _merge,
683
+ "lookup": _lookup,
684
+ "keys": _keys,
685
+ "values": _values,
686
+ "element": _element,
687
+ "contains": _contains,
688
+ "toset": _toset,
689
+ "tolist": _tolist,
690
+ "tomap": _tomap,
691
+ "min": _builtin("min"),
692
+ "max": _builtin("max"),
693
+ "abs": _builtin("abs", variadic=False),
694
+ "replace": _replace,
695
+ "range": _range,
696
+ "jsonencode": _jsonencode,
697
+ "format": _format,
698
+ "file": _file,
699
+ "tostring": _tostring,
700
+ "sort": _sort,
701
+ }