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.
- netherframe/generation/__init__.py +31 -0
- netherframe/generation/api.py +306 -0
- netherframe/generation/batch.py +65 -0
- netherframe/generation/convert/__init__.py +6 -0
- netherframe/generation/convert/bindings.py +180 -0
- netherframe/generation/convert/converter.py +365 -0
- netherframe/generation/convert/emitter.py +972 -0
- netherframe/generation/convert/expressions.py +701 -0
- netherframe/generation/convert/hcl_ast.py +721 -0
- netherframe/generation/convert/module_fetch.py +135 -0
- netherframe/generation/convert/module_source.py +200 -0
- netherframe/generation/convert/python_code.py +152 -0
- netherframe/generation/discovered_code.py +777 -0
- netherframe/generation/functions/__init__.py +8 -0
- netherframe/generation/functions/generator.py +369 -0
- netherframe/generation/import_specs.py +179 -0
- netherframe/generation/imports.py +169 -0
- netherframe/generation/nf_alias_shims.py +104 -0
- netherframe/generation/providers/__init__.py +1 -0
- netherframe/generation/providers/build_backend.py +90 -0
- netherframe/generation/providers/cli.py +274 -0
- netherframe/generation/providers/code_generator.py +2128 -0
- netherframe/generation/providers/codegen_support.py +542 -0
- netherframe/generation/providers/logging.py +22 -0
- netherframe/generation/providers/output_transaction.py +85 -0
- netherframe/generation/providers/package_output.py +440 -0
- netherframe/generation/providers/release.py +155 -0
- netherframe/generation/providers/schema_generation.py +220 -0
- netherframe/generation/providers/schema_loading.py +10 -0
- netherframe/generation/providers/schema_native.py +97 -0
- netherframe/generation/providers/schema_parser.py +563 -0
- netherframe/generation/py.typed +0 -0
- netherframe_generation-0.3.0.dist-info/METADATA +66 -0
- netherframe_generation-0.3.0.dist-info/RECORD +68 -0
- netherframe_generation-0.3.0.dist-info/WHEEL +4 -0
- netherframe_generation-0.3.0.dist-info/licenses/LICENSE +21 -0
- nf/generation/__init__.py +4 -0
- nf/generation/api.py +4 -0
- nf/generation/batch.py +4 -0
- nf/generation/convert/__init__.py +4 -0
- nf/generation/convert/bindings.py +4 -0
- nf/generation/convert/converter.py +4 -0
- nf/generation/convert/emitter.py +4 -0
- nf/generation/convert/expressions.py +4 -0
- nf/generation/convert/hcl_ast.py +4 -0
- nf/generation/convert/module_fetch.py +4 -0
- nf/generation/convert/module_source.py +4 -0
- nf/generation/convert/python_code.py +4 -0
- nf/generation/discovered_code.py +4 -0
- nf/generation/functions/__init__.py +4 -0
- nf/generation/functions/generator.py +4 -0
- nf/generation/import_specs.py +4 -0
- nf/generation/imports.py +4 -0
- nf/generation/nf_alias_shims.py +4 -0
- nf/generation/providers/__init__.py +4 -0
- nf/generation/providers/build_backend.py +4 -0
- nf/generation/providers/cli.py +4 -0
- nf/generation/providers/code_generator.py +4 -0
- nf/generation/providers/codegen_support.py +4 -0
- nf/generation/providers/logging.py +4 -0
- nf/generation/providers/output_transaction.py +4 -0
- nf/generation/providers/package_output.py +4 -0
- nf/generation/providers/release.py +4 -0
- nf/generation/providers/schema_generation.py +4 -0
- nf/generation/providers/schema_loading.py +4 -0
- nf/generation/providers/schema_native.py +4 -0
- nf/generation/providers/schema_parser.py +4 -0
- nf/generation/py.typed +0 -0
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
"""Write one Terraform module as a Python module.
|
|
2
|
+
|
|
3
|
+
The root module becomes a ``Stack`` subclass whose keyword arguments are the module's variables;
|
|
4
|
+
a local child module becomes a plain class that builds its constructs into a given stack, with
|
|
5
|
+
``nf_prefix`` before their ``nf_id`` (netherframe has no module layer, so a module's resources
|
|
6
|
+
live in its caller's stack) and its outputs as attributes.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
from .bindings import ArgumentBinding, BindingResolver, BlockBinding, ConstructBinding
|
|
16
|
+
from .expressions import Iterator, Scope, Todo, Translator, Untranslatable, terraform_text
|
|
17
|
+
from .hcl_ast import Block, Body, Call, Expr, Literal, Name, ObjectExpr, Template, TupleExpr, object_to_bodies, traversal
|
|
18
|
+
from .module_source import (
|
|
19
|
+
LocalValue,
|
|
20
|
+
ModuleSource,
|
|
21
|
+
body_expressions,
|
|
22
|
+
ignore_changes_names,
|
|
23
|
+
is_local_source,
|
|
24
|
+
module_source_text,
|
|
25
|
+
normalize_source,
|
|
26
|
+
provider_reference,
|
|
27
|
+
references,
|
|
28
|
+
topological_order,
|
|
29
|
+
)
|
|
30
|
+
from .python_code import Kind, Names, Py, join_kinds, literal, quote
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
# Attributes of `Stack` a root module's constructs must not replace
|
|
36
|
+
_STACK_ATTRIBUTES = frozenset(
|
|
37
|
+
{
|
|
38
|
+
"nf_id",
|
|
39
|
+
"nf_scope",
|
|
40
|
+
"nf_path",
|
|
41
|
+
"synth",
|
|
42
|
+
"outputs",
|
|
43
|
+
"resources",
|
|
44
|
+
"providers",
|
|
45
|
+
"variables",
|
|
46
|
+
"backend",
|
|
47
|
+
"node",
|
|
48
|
+
"children",
|
|
49
|
+
"app",
|
|
50
|
+
"add_dependency",
|
|
51
|
+
"dependencies",
|
|
52
|
+
},
|
|
53
|
+
)
|
|
54
|
+
# Fixed constructor arguments; helpers and imports live in the reserved _nf_ namespace.
|
|
55
|
+
_SCOPE_NAMES = frozenset({"self", "scope", "nf_scope", "nf_id", "nf_prefix"})
|
|
56
|
+
_RESOURCE_META = frozenset({"count", "for_each", "provider", "depends_on", "lifecycle", "provisioner", "connection"})
|
|
57
|
+
_MODULE_META = frozenset({"source", "version", "count", "for_each", "providers", "depends_on"})
|
|
58
|
+
_SUPPORT_MODULE = "_support"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class ModuleInfo:
|
|
63
|
+
"""A module of the converted tree: its source, Python module and class."""
|
|
64
|
+
|
|
65
|
+
source: ModuleSource
|
|
66
|
+
rel: str # its directory relative to the root module ("." for the root)
|
|
67
|
+
python_module: str # "main" or "modules.<name>"
|
|
68
|
+
class_name: str
|
|
69
|
+
is_root: bool
|
|
70
|
+
# Variable name -> the kind of value its callers pass (child modules)
|
|
71
|
+
argument_kinds: dict[str, Kind] = field(default_factory=dict)
|
|
72
|
+
outputs: dict[str, str] = field(default_factory=dict) # output name -> attribute
|
|
73
|
+
default_id: str = "main" # the root stack's default nf_id
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class EmittedModule:
|
|
78
|
+
code: str
|
|
79
|
+
todos: list[Todo]
|
|
80
|
+
counts: dict[str, int]
|
|
81
|
+
typed: dict[str, int] # "typed" / "generic" construct counts
|
|
82
|
+
generic_types: set[str]
|
|
83
|
+
helpers: set[str]
|
|
84
|
+
# Each managed resource's Terraform address in the module and its nf_id, ``[*]`` / ``{*}`` for
|
|
85
|
+
# a loop's instance key: (``aws_instance.web[*]``, ``aws_instance``, ``web_{*}``)
|
|
86
|
+
adoptions: list[tuple[str, str, str]] = field(default_factory=list)
|
|
87
|
+
# Each converted module call: (name, whether it loops, the module called)
|
|
88
|
+
module_calls: list[tuple[str, bool, ModuleInfo]] = field(default_factory=list)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass
|
|
92
|
+
class _Context:
|
|
93
|
+
"""A statement's context: the loop variables in scope and the scope/nf_id expressions."""
|
|
94
|
+
|
|
95
|
+
scope: Scope
|
|
96
|
+
indent: int = 2
|
|
97
|
+
id_suffix: str = "" # "_{index}" / "_{key}" in a loop
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ModuleEmitter:
|
|
101
|
+
"""Converts one module (see the module docstring)."""
|
|
102
|
+
|
|
103
|
+
def __init__(self, info: ModuleInfo, modules: dict[Path, ModuleInfo], resolver: BindingResolver, *, inherited_sources: dict[str, str] | None = None) -> None:
|
|
104
|
+
self.info = info
|
|
105
|
+
self.module = info.source
|
|
106
|
+
self.modules = modules
|
|
107
|
+
self.resolver = resolver
|
|
108
|
+
# A module without its own required_providers entry for a name uses its caller's
|
|
109
|
+
self.sources = {**(inherited_sources or {}), **self.module.required_providers()}
|
|
110
|
+
self.lines: list[str] = []
|
|
111
|
+
self.counts: dict[str, int] = {}
|
|
112
|
+
self.typed = {"typed": 0, "generic": 0}
|
|
113
|
+
self.generic_types: set[str] = set()
|
|
114
|
+
self.local_names = Names(set(_SCOPE_NAMES))
|
|
115
|
+
self.attribute_names = Names(set(_STACK_ATTRIBUTES) if info.is_root else set(info.outputs.values()))
|
|
116
|
+
self.owner = "self"
|
|
117
|
+
self.scope_code = "self" if info.is_root else "scope"
|
|
118
|
+
resource_types = self.module.resource_types
|
|
119
|
+
self.scope = Scope({}, {}, {}, {}, {}, resource_types, info.rel, self.local_names)
|
|
120
|
+
if not info.is_root:
|
|
121
|
+
provider_names = set(self.sources)
|
|
122
|
+
for block in [*self.module.resources, *self.module.data, *self.module.ephemeral]:
|
|
123
|
+
provider_names.add(provider_reference(block.body.get("provider")) or block.labels[0].split("_")[0])
|
|
124
|
+
self.scope.providers.update({name: f"self._nf_providers.get({quote(name)})" for name in provider_names})
|
|
125
|
+
self.tr = Translator(self.scope)
|
|
126
|
+
self.adoptions: list[tuple[str, str, str]] = []
|
|
127
|
+
self.module_calls: list[tuple[str, bool, ModuleInfo]] = []
|
|
128
|
+
|
|
129
|
+
# --- Helpers -----------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
def _count(self, what: str) -> None:
|
|
132
|
+
self.counts[what] = self.counts.get(what, 0) + 1
|
|
133
|
+
|
|
134
|
+
def _emit(self, indent: int, line: str = "") -> None:
|
|
135
|
+
self.lines.append(f"{' ' * indent}{line}" if line else "")
|
|
136
|
+
|
|
137
|
+
def _todo_lines(self, indent: int, todos: list[Todo]) -> None:
|
|
138
|
+
for todo in todos:
|
|
139
|
+
self._emit(indent, f"# TODO(nf convert): {todo.reason}")
|
|
140
|
+
for line in _dedent_source(todo.hcl):
|
|
141
|
+
self._emit(indent, f"# {line}".rstrip())
|
|
142
|
+
|
|
143
|
+
def _take_todos(self, start: int) -> list[Todo]:
|
|
144
|
+
"""The TODO markers since ``start``, to write before a statement (they stay in the report)."""
|
|
145
|
+
return self.tr.todos[start:]
|
|
146
|
+
|
|
147
|
+
def _todo(self, reason: str, hcl: str = "", file: str = "", line: int = 0) -> Todo:
|
|
148
|
+
todo = Todo(reason, hcl, file, line)
|
|
149
|
+
self.tr.todos.append(todo)
|
|
150
|
+
return todo
|
|
151
|
+
|
|
152
|
+
def _provider_source(self, local_name: str) -> str:
|
|
153
|
+
return normalize_source(self.sources.get(local_name, f"hashicorp/{local_name}"))
|
|
154
|
+
|
|
155
|
+
def _id(self, name: str, ctx: _Context) -> str:
|
|
156
|
+
if self.info.is_root and not ctx.id_suffix:
|
|
157
|
+
return quote(name)
|
|
158
|
+
prefix = "" if self.info.is_root else "{nf_prefix}"
|
|
159
|
+
return f'f"{prefix}{name}{ctx.id_suffix}"'
|
|
160
|
+
|
|
161
|
+
def _class_ref(self, binding: ConstructBinding) -> str:
|
|
162
|
+
self.tr.import_name(binding.import_module, binding.class_name)
|
|
163
|
+
return f"_nf_{binding.class_name}"
|
|
164
|
+
|
|
165
|
+
# --- Entry point -------------------------------------------------------------------------
|
|
166
|
+
|
|
167
|
+
def emit(self) -> EmittedModule:
|
|
168
|
+
self.tr.file = ""
|
|
169
|
+
body_start = len(self.lines)
|
|
170
|
+
parameters = self._parameters()
|
|
171
|
+
self._body()
|
|
172
|
+
body = self.lines[body_start:]
|
|
173
|
+
self.lines = self._header(parameters) + body
|
|
174
|
+
code = "\n".join(self.lines).rstrip() + "\n"
|
|
175
|
+
return EmittedModule(code, self.tr.todos, self.counts, self.typed, self.generic_types, self.tr.helpers, self.adoptions, self.module_calls)
|
|
176
|
+
|
|
177
|
+
# --- Variables ---------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
def _parameters(self) -> list[str]:
|
|
180
|
+
"""The variables as keyword parameters; fills the scope's variables."""
|
|
181
|
+
parameters: list[str] = []
|
|
182
|
+
self._defaults: list[tuple[str, str]] = []
|
|
183
|
+
self._variable_docs: list[str] = []
|
|
184
|
+
for block in self.module.variables:
|
|
185
|
+
name = block.labels[0]
|
|
186
|
+
python = self.local_names.allocate(name)
|
|
187
|
+
argument_kind = self.info.argument_kinds.get(name, Kind.STATIC)
|
|
188
|
+
type_expr = block.body.get("type")
|
|
189
|
+
annotation, shape = python_type(type_expr)
|
|
190
|
+
default = block.body.get("default")
|
|
191
|
+
default_py = self.tr.translate(default, context=f"variable {name} default") if default is not None else None
|
|
192
|
+
if shape is None and default is not None:
|
|
193
|
+
shape = {TupleExpr: "list", ObjectExpr: "map"}.get(type(default))
|
|
194
|
+
if annotation == "Any" and isinstance(default, Literal) and default.value is not None:
|
|
195
|
+
annotation = type(default.value).__name__
|
|
196
|
+
if argument_kind is Kind.MIXED: # callers pass collections holding runtime values
|
|
197
|
+
annotation = re.sub(r"^(list|dict)\[(str, )?.*\]$", lambda match: f"{match.group(1)}[{match.group(2) or ''}Any]", annotation)
|
|
198
|
+
if argument_kind is Kind.RUNTIME and annotation != "Any":
|
|
199
|
+
self.tr.import_name("netherframe.core", "RuntimeValue")
|
|
200
|
+
annotation = f"{annotation} | _nf_RuntimeValue[{annotation}]"
|
|
201
|
+
annotation = re.sub(r"\bAny\b", "_nf_Any", annotation)
|
|
202
|
+
if default_py is not None:
|
|
203
|
+
if default_py.code == "None":
|
|
204
|
+
parameters.append(f"{python}: {annotation} | None = None")
|
|
205
|
+
elif isinstance(default, (TupleExpr, ObjectExpr)) or default_py.code.startswith(("[", "{")):
|
|
206
|
+
parameters.append(f"{python}: {annotation} | None = None")
|
|
207
|
+
self._defaults.append((python, default_py.code))
|
|
208
|
+
else:
|
|
209
|
+
parameters.append(f"{python}: {annotation} = {default_py.code}")
|
|
210
|
+
else:
|
|
211
|
+
parameters.append(f"{python}: {annotation}")
|
|
212
|
+
kind = argument_kind if argument_kind is not Kind.STATIC else Kind.STATIC
|
|
213
|
+
self.scope.variables[name] = Py(python, kind, shape=shape)
|
|
214
|
+
description = block.body.get("description")
|
|
215
|
+
if isinstance(description, Literal) and description.value:
|
|
216
|
+
self._variable_docs.append(f"{python}: {description.value}")
|
|
217
|
+
self._count("variables")
|
|
218
|
+
return parameters
|
|
219
|
+
|
|
220
|
+
# --- Body --------------------------------------------------------------------------------
|
|
221
|
+
|
|
222
|
+
def _body(self) -> None:
|
|
223
|
+
ctx = _Context(self.scope)
|
|
224
|
+
self._todo_lines(2, list(self.tr.todos))
|
|
225
|
+
for python, default in self._defaults:
|
|
226
|
+
self._emit(2, f"if {python} is None:")
|
|
227
|
+
self._emit(3, f"{python} = {default}")
|
|
228
|
+
for block in self.module.variables:
|
|
229
|
+
for validation in block.body.blocks_of("validation"):
|
|
230
|
+
self._validation(block, validation, ctx)
|
|
231
|
+
for block in self.module.terraform:
|
|
232
|
+
self._terraform(block)
|
|
233
|
+
for block in self.module.other:
|
|
234
|
+
start = len(self.tr.todos)
|
|
235
|
+
self._todo(f"{block.type} blocks are not converted", block.source, block.file, block.line)
|
|
236
|
+
self._todo_lines(2, self._take_todos(start))
|
|
237
|
+
|
|
238
|
+
# Unconverted modules are known up front: whatever reads their outputs becomes a TODO
|
|
239
|
+
self._unconverted: dict[str, str] = {}
|
|
240
|
+
for block in self.module.modules:
|
|
241
|
+
if self._child_info(module_source_text(block) or "", block.labels[0]) is None:
|
|
242
|
+
name = block.labels[0]
|
|
243
|
+
self._unconverted[name] = self.attribute_names.allocate(name)
|
|
244
|
+
self.scope.modules[name] = Py(f"{self.owner}.{self._unconverted[name]}", Kind.MODULE)
|
|
245
|
+
items = self._items()
|
|
246
|
+
keys = list(items)
|
|
247
|
+
dependencies = {key: deps for key, (_, deps) in items.items()}
|
|
248
|
+
for key in topological_order(keys, dependencies):
|
|
249
|
+
kind, value = items[key][0]
|
|
250
|
+
self.tr.file = value.file
|
|
251
|
+
if isinstance(value, LocalValue):
|
|
252
|
+
self._local(value, ctx)
|
|
253
|
+
elif kind == "provider":
|
|
254
|
+
self._provider(value, ctx)
|
|
255
|
+
elif kind in {"resource", "data", "ephemeral"}:
|
|
256
|
+
self._construct(kind, value, ctx)
|
|
257
|
+
elif kind == "module":
|
|
258
|
+
self._module_call(value, ctx)
|
|
259
|
+
for block in self.module.outputs:
|
|
260
|
+
self.tr.file = block.file
|
|
261
|
+
self._output(block, ctx)
|
|
262
|
+
if len(self.lines) == 0 or all(not line.strip() for line in self.lines):
|
|
263
|
+
self._emit(2, "pass")
|
|
264
|
+
|
|
265
|
+
def _validation(self, variable: Block, validation: Block, ctx: _Context) -> None:
|
|
266
|
+
"""A variable's validation as a Python check, when its condition is a Python value."""
|
|
267
|
+
name = variable.labels[0]
|
|
268
|
+
condition = validation.body.get("condition")
|
|
269
|
+
message = validation.body.get("error_message")
|
|
270
|
+
start = len(self.tr.todos)
|
|
271
|
+
condition_py = self.tr.translate(condition, ctx.scope, context=f"variable {name} validation") if condition is not None else None
|
|
272
|
+
message_py = self.tr.translate(message, ctx.scope, context=f"variable {name} validation") if message is not None else None
|
|
273
|
+
del self.tr.todos[start:] # a validation either converts whole or is one TODO
|
|
274
|
+
if condition_py is None or not condition_py.static or (message_py is not None and not message_py.static):
|
|
275
|
+
self._todo(f"variable {name}: validation is not converted", validation.source, variable.file, validation.line)
|
|
276
|
+
self._todo_lines(2, self._take_todos(start))
|
|
277
|
+
return
|
|
278
|
+
self._emit(2, f"if {condition_py.negated()}:")
|
|
279
|
+
self._emit(3, f"raise ValueError({message_py.code if message_py is not None else quote(f'invalid value for {name}')})")
|
|
280
|
+
|
|
281
|
+
def _items(self) -> dict[str, tuple[tuple[str, Block | LocalValue], set[str]]]:
|
|
282
|
+
"""The module's items by key, with the keys each depends on."""
|
|
283
|
+
types = self.module.resource_types
|
|
284
|
+
items: dict[str, tuple[tuple[str, Block | LocalValue], set[str]]] = {}
|
|
285
|
+
provider_keys: dict[str, str] = {}
|
|
286
|
+
for block in self.module.providers:
|
|
287
|
+
local_name = block.labels[0]
|
|
288
|
+
alias = block.body.get("alias")
|
|
289
|
+
reference = f"{local_name}.{alias.value}" if isinstance(alias, Literal) else local_name
|
|
290
|
+
key = f"provider.{reference}"
|
|
291
|
+
provider_keys[reference] = key
|
|
292
|
+
items[key] = (("provider", block), references(body_expressions(block.body), types))
|
|
293
|
+
for local in self.module.locals:
|
|
294
|
+
items[f"local.{local.name}"] = (("local", local), references([local.attribute.value], types))
|
|
295
|
+
for kind, blocks in (("resource", self.module.resources), ("data", self.module.data), ("ephemeral", self.module.ephemeral)):
|
|
296
|
+
for block in blocks:
|
|
297
|
+
prefix = "resource" if kind == "resource" else kind
|
|
298
|
+
key = f"{prefix}.{block.labels[0]}.{block.labels[1]}"
|
|
299
|
+
deps = references(body_expressions(block.body), types)
|
|
300
|
+
provider = provider_reference(block.body.get("provider")) or block.labels[0].split("_")[0]
|
|
301
|
+
if provider in provider_keys:
|
|
302
|
+
deps.add(provider_keys[provider])
|
|
303
|
+
items[key] = ((kind, block), deps)
|
|
304
|
+
for block in self.module.modules:
|
|
305
|
+
# An unconverted module's arguments are kept as text: it depends on nothing
|
|
306
|
+
deps = set() if block.labels[0] in self._unconverted else references(body_expressions(block.body), types)
|
|
307
|
+
if block.labels[0] not in self._unconverted:
|
|
308
|
+
mapping = block.body.get("providers")
|
|
309
|
+
inherited = [provider_reference(value) for _, value in mapping.items] if isinstance(mapping, ObjectExpr) else [name for name in provider_keys if "." not in name]
|
|
310
|
+
deps.update(provider_keys[name] for name in inherited if name in provider_keys)
|
|
311
|
+
items[f"module.{block.labels[0]}"] = (("module", block), deps)
|
|
312
|
+
# References to an unconverted module are text: they need nothing defined first
|
|
313
|
+
unconverted_keys = {f"module.{name}" for name in self._unconverted}
|
|
314
|
+
return {key: (item, deps - unconverted_keys) for key, (item, deps) in items.items()}
|
|
315
|
+
|
|
316
|
+
def _terraform(self, block: Block) -> None:
|
|
317
|
+
for inner in block.body.blocks:
|
|
318
|
+
if inner.type in {"backend", "cloud"}:
|
|
319
|
+
start = len(self.tr.todos)
|
|
320
|
+
self._todo(f"terraform {inner.type} is not converted: configure state with a netherframe backend", inner.source, block.file, inner.line)
|
|
321
|
+
self._todo_lines(2, self._take_todos(start))
|
|
322
|
+
|
|
323
|
+
# --- Providers ---------------------------------------------------------------------------
|
|
324
|
+
|
|
325
|
+
def _provider(self, block: Block, ctx: _Context) -> None:
|
|
326
|
+
local_name = block.labels[0]
|
|
327
|
+
binding = self.resolver.provider(local_name, self._provider_source(local_name))
|
|
328
|
+
alias = block.body.get("alias")
|
|
329
|
+
alias_name = alias.value if isinstance(alias, Literal) and isinstance(alias.value, str) else None
|
|
330
|
+
reference = f"{local_name}.{alias_name}" if alias_name else local_name
|
|
331
|
+
attribute = self.attribute_names.allocate(f"provider_{local_name}{'_' + alias_name if alias_name else ''}")
|
|
332
|
+
start = len(self.tr.todos)
|
|
333
|
+
arguments = [f"nf_scope={self.scope_code}", f"nf_id={self._id(local_name + ('_' + alias_name if alias_name else ''), ctx)}"]
|
|
334
|
+
if not binding.typed:
|
|
335
|
+
arguments.append(f"nf_type={quote(local_name)}")
|
|
336
|
+
argument_lines = self._arguments(block.body, binding.arguments, ctx, skip={"alias", "version"}, what=f"provider {reference}", file=block.file)
|
|
337
|
+
if alias_name:
|
|
338
|
+
self.tr.import_name("netherframe.core", "ProviderSettings")
|
|
339
|
+
argument_lines.append(([], f"nf_provider_settings=_nf_ProviderSettings(alias={quote(alias_name)})"))
|
|
340
|
+
self._track(binding, local_name)
|
|
341
|
+
self._statement(ctx, f"{self.owner}.{attribute} = {self._class_ref(binding)}(", arguments, argument_lines, start)
|
|
342
|
+
self.scope.providers[reference] = f"{self.owner}.{attribute}"
|
|
343
|
+
self._count("providers")
|
|
344
|
+
|
|
345
|
+
def _track(self, binding: ConstructBinding, tf_type: str) -> None:
|
|
346
|
+
if binding.typed:
|
|
347
|
+
self.typed["typed"] += 1
|
|
348
|
+
else:
|
|
349
|
+
self.typed["generic"] += 1
|
|
350
|
+
self.generic_types.add(tf_type)
|
|
351
|
+
|
|
352
|
+
# --- Locals ------------------------------------------------------------------------------
|
|
353
|
+
|
|
354
|
+
def _local(self, local: LocalValue, ctx: _Context) -> None:
|
|
355
|
+
start = len(self.tr.todos)
|
|
356
|
+
python = self.local_names.allocate(local.name)
|
|
357
|
+
value = self.tr.translate(local.attribute.value, ctx.scope, context=f"local.{local.name}")
|
|
358
|
+
self._todo_lines(ctx.indent, self._take_todos(start))
|
|
359
|
+
self._emit(ctx.indent, f"{python} = {value.code}")
|
|
360
|
+
self.scope.locals[local.name] = Py(python, value.kind, binding=value.binding, shape=value.shape, module=value.module, module_outputs=value.module_outputs)
|
|
361
|
+
self._count("locals")
|
|
362
|
+
|
|
363
|
+
# --- Resources and data sources ----------------------------------------------------------
|
|
364
|
+
|
|
365
|
+
def _construct(self, kind: str, block: Block, ctx: _Context) -> None:
|
|
366
|
+
tf_type, name = block.labels[0], block.labels[1]
|
|
367
|
+
address = f"{tf_type}.{name}" if kind == "resource" else f"{kind}.{tf_type}.{name}"
|
|
368
|
+
binding_kind = {"resource": "resource", "data": "data_source", "ephemeral": "ephemeral_resource"}[kind]
|
|
369
|
+
provider_ref = provider_reference(block.body.get("provider"))
|
|
370
|
+
provider_local = (provider_ref or tf_type).split(".")[0] if provider_ref else tf_type.split("_")[0]
|
|
371
|
+
binding = self.resolver.construct(tf_type, binding_kind, self._provider_source(provider_local))
|
|
372
|
+
self._track(binding, tf_type)
|
|
373
|
+
stem = tf_type.split("_", 1)[1] if "_" in tf_type else tf_type
|
|
374
|
+
suffix = {"resource": "", "data": "_data", "ephemeral": "_ephemeral"}[kind]
|
|
375
|
+
attribute = self.attribute_names.allocate(f"{stem}_{name}{suffix}")
|
|
376
|
+
target = f"{self.owner}.{attribute}"
|
|
377
|
+
class_ref = self._class_ref(binding)
|
|
378
|
+
start = len(self.tr.todos)
|
|
379
|
+
|
|
380
|
+
count = block.body.get("count")
|
|
381
|
+
for_each = block.body.get("for_each")
|
|
382
|
+
loop_ctx, loop_header, _ = self._loop(count, for_each, ctx, address)
|
|
383
|
+
container_kind = Kind.CONSTRUCTS if loop_header else Kind.CONSTRUCT
|
|
384
|
+
shape = None if not loop_header else ("map" if for_each is not None else "list")
|
|
385
|
+
|
|
386
|
+
inner = loop_ctx
|
|
387
|
+
arguments = [f"nf_scope={self.scope_code}", f"nf_id={self._id(name, inner)}"]
|
|
388
|
+
if not binding.typed:
|
|
389
|
+
arguments.append(f"nf_type={quote(tf_type)}")
|
|
390
|
+
argument_lines = self._arguments(block.body, binding.arguments, inner, skip=_RESOURCE_META, what=address, file=block.file)
|
|
391
|
+
argument_lines.extend(self._meta_arguments(kind, block, inner, address))
|
|
392
|
+
|
|
393
|
+
if loop_header:
|
|
394
|
+
annotation = f"dict[str, {class_ref}]" if for_each is not None else f"list[{class_ref}]"
|
|
395
|
+
self._todo_lines(ctx.indent, self._take_todos(start))
|
|
396
|
+
start = len(self.tr.todos)
|
|
397
|
+
self._emit(ctx.indent, f"{target}: {annotation} = {{}}" if for_each is not None else f"{target}: {annotation} = []")
|
|
398
|
+
self._emit(ctx.indent, loop_header)
|
|
399
|
+
head = f"{target}[{inner.scope.iterators['each'].key.code}] = {class_ref}(" if for_each is not None else f"{target}.append({class_ref}("
|
|
400
|
+
self._statement(inner, head, arguments, argument_lines, start, close=")" if for_each is not None else "))")
|
|
401
|
+
else:
|
|
402
|
+
self._statement(ctx, f"{target} = {class_ref}(", arguments, argument_lines, start)
|
|
403
|
+
self.scope.constructs[address] = Py(target, container_kind, binding=binding, shape=shape)
|
|
404
|
+
if kind == "resource":
|
|
405
|
+
# Where Terraform's state keeps it, and the nf_id it gets: for adoption manifests
|
|
406
|
+
self.adoptions.append((address + ("[*]" if loop_header else ""), tf_type, name + ("_{*}" if loop_header else "")))
|
|
407
|
+
if not self.info.is_root:
|
|
408
|
+
if loop_header:
|
|
409
|
+
members = f"{target}.values()" if for_each is not None else target
|
|
410
|
+
self._emit(ctx.indent, f"self._nf_resources.extend({members})")
|
|
411
|
+
else:
|
|
412
|
+
self._emit(ctx.indent, f"self._nf_resources.append({target})")
|
|
413
|
+
self._count({"resource": "resources", "data": "data sources", "ephemeral": "ephemeral resources"}[kind])
|
|
414
|
+
|
|
415
|
+
def _loop(self, count: Expr | None, for_each: Expr | None, ctx: _Context, what: str) -> tuple[_Context, str | None, Py | None]:
|
|
416
|
+
"""The loop header of ``count`` / ``for_each``, and the context of its body."""
|
|
417
|
+
if for_each is None:
|
|
418
|
+
if count is None:
|
|
419
|
+
return ctx, None, None
|
|
420
|
+
return self._count_loop(count, ctx, what)
|
|
421
|
+
scope = ctx.scope
|
|
422
|
+
value = self.tr.translate(for_each, scope, context=f"{what} for_each")
|
|
423
|
+
if not value.python_container:
|
|
424
|
+
self._todo(f"{what}: for_each is not known before apply here; the loop needs a Python value", for_each.source.strip(), self.tr.file, for_each.line)
|
|
425
|
+
key = self.local_names.allocate("key")
|
|
426
|
+
self.local_names.taken.discard(key)
|
|
427
|
+
element_kind = Kind.CONSTRUCT if value.kind is Kind.CONSTRUCTS else (Kind.STATIC if value.static else Kind.MIXED)
|
|
428
|
+
if value.shape == "map":
|
|
429
|
+
item = self.local_names.allocate("value")
|
|
430
|
+
self.local_names.taken.discard(item)
|
|
431
|
+
header = f"for {key}, {item} in {value.operand()}.items():"
|
|
432
|
+
iterators = {"each": Iterator(Py(key, Kind.STATIC), Py(item, element_kind, binding=value.binding))}
|
|
433
|
+
elif value.shape in {"set", "list"}:
|
|
434
|
+
header = f"for {key} in {value.operand()}:"
|
|
435
|
+
iterators = {"each": Iterator(Py(key, Kind.STATIC), Py(key, Kind.STATIC))}
|
|
436
|
+
else:
|
|
437
|
+
item = self.local_names.allocate("value")
|
|
438
|
+
self.local_names.taken.discard(item)
|
|
439
|
+
self.tr.helpers.add("each")
|
|
440
|
+
header = f"for {key}, {item} in _nf_each({value.code}):"
|
|
441
|
+
iterators = {"each": Iterator(Py(key, Kind.STATIC), Py(item, element_kind, binding=value.binding))}
|
|
442
|
+
body = _Context(scope.child(iterators=iterators), ctx.indent + 1, f"_{{{key}}}")
|
|
443
|
+
return body, header, value
|
|
444
|
+
|
|
445
|
+
def _count_loop(self, count: Expr, ctx: _Context, what: str) -> tuple[_Context, str, Py]:
|
|
446
|
+
value = self.tr.translate(count, ctx.scope, context=f"{what} count")
|
|
447
|
+
if not value.static:
|
|
448
|
+
self._todo(f"{what}: count is not known before apply here; the loop needs a Python value", count.source.strip(), self.tr.file, count.line)
|
|
449
|
+
index = self.local_names.allocate("index")
|
|
450
|
+
self.local_names.taken.discard(index)
|
|
451
|
+
iterators = {"count": Iterator(Py(index, Kind.STATIC), None)}
|
|
452
|
+
body = _Context(ctx.scope.child(iterators=iterators), ctx.indent + 1, f"_{{{index}}}")
|
|
453
|
+
return body, f"for {index} in range({value.code}):", value
|
|
454
|
+
|
|
455
|
+
def _statement(self, ctx: _Context, head: str, fixed: list[str], arguments: list[tuple[list[Todo], str]], start: int, *, close: str = ")") -> None:
|
|
456
|
+
"""``head`` + keyword arguments, TODO markers of the arguments placed before each."""
|
|
457
|
+
statement_todos = [todo for todo in self.tr.todos[start:] if not any(todo is argument_todo for todos, _ in arguments for argument_todo in todos)]
|
|
458
|
+
self._todo_lines(ctx.indent, statement_todos)
|
|
459
|
+
self._emit(ctx.indent, head)
|
|
460
|
+
for argument in fixed:
|
|
461
|
+
self._emit(ctx.indent + 1, f"{argument},")
|
|
462
|
+
for todos, argument in arguments:
|
|
463
|
+
self._todo_lines(ctx.indent + 1, todos)
|
|
464
|
+
if argument:
|
|
465
|
+
self._emit(ctx.indent + 1, f"{argument},")
|
|
466
|
+
self._emit(ctx.indent, close)
|
|
467
|
+
|
|
468
|
+
def _arguments(self, body: Body, binding: ArgumentBinding, ctx: _Context, *, skip: frozenset[str] | set[str], what: str, file: str) -> list[tuple[list[Todo], str]]:
|
|
469
|
+
"""The keyword arguments of a body's attributes and blocks, each with its TODO markers."""
|
|
470
|
+
result: list[tuple[list[Todo], str]] = []
|
|
471
|
+
block_names: list[str] = []
|
|
472
|
+
for block in body.blocks:
|
|
473
|
+
if block.type == "dynamic" and block.labels:
|
|
474
|
+
name = block.labels[0]
|
|
475
|
+
elif block.type in skip:
|
|
476
|
+
continue
|
|
477
|
+
else:
|
|
478
|
+
name = block.type
|
|
479
|
+
if name not in block_names:
|
|
480
|
+
block_names.append(name)
|
|
481
|
+
for name, attribute in body.attributes.items():
|
|
482
|
+
if name in skip:
|
|
483
|
+
continue
|
|
484
|
+
nested = binding.block(name) if binding.typed else None
|
|
485
|
+
bodies = object_to_bodies(attribute.value) if nested is not None else None
|
|
486
|
+
if nested is not None and bodies is not None: # JSON writes blocks as objects
|
|
487
|
+
result.append(self._block_argument(name, [(None, nested_body) for nested_body in bodies], nested, binding, ctx, what, file))
|
|
488
|
+
continue
|
|
489
|
+
start = len(self.tr.todos)
|
|
490
|
+
value = self.tr.translate(attribute.value, ctx.scope, context=f"{what}.{name}")
|
|
491
|
+
todos = self.tr.todos[start:]
|
|
492
|
+
if not binding.known(name):
|
|
493
|
+
todos.append(self._todo(f"{what}: {name} is not an argument of {binding.class_path}", "", file, attribute.line))
|
|
494
|
+
result.append((list(todos), f"{binding.parameter(name)}={self._argument_code(value)}"))
|
|
495
|
+
for name in block_names:
|
|
496
|
+
blocks = [block for block in body.blocks if (block.type == name and block.type != "dynamic") or (block.type == "dynamic" and block.labels[:1] == [name])]
|
|
497
|
+
nested = binding.block(name) if binding.typed else None
|
|
498
|
+
result.append(self._block_argument(name, [(block, block.body) for block in blocks], nested, binding, ctx, what, file))
|
|
499
|
+
return result
|
|
500
|
+
|
|
501
|
+
def _block_argument(self, name: str, blocks: list[tuple[Block | None, Body]], nested: BlockBinding | None, binding: ArgumentBinding, ctx: _Context, what: str, file: str) -> tuple[list[Todo], str]:
|
|
502
|
+
"""A nested block argument: block class instances (or dicts), dynamic blocks as comprehensions."""
|
|
503
|
+
start = len(self.tr.todos)
|
|
504
|
+
items: list[str] = [] # list items (`X(...)` or `*[... for ...]`)
|
|
505
|
+
labelled: list[tuple[str, str]] = []
|
|
506
|
+
for block, body in blocks:
|
|
507
|
+
if block is not None and block.type == "dynamic":
|
|
508
|
+
comprehension = self._dynamic(block, nested, ctx, what, file)
|
|
509
|
+
if comprehension is not None:
|
|
510
|
+
items.append(f"*{comprehension}")
|
|
511
|
+
continue
|
|
512
|
+
code = self._block_value(body, nested, ctx, f"{what}.{name}", file)
|
|
513
|
+
if nested is not None and nested.nesting == "map" and block is not None and block.labels:
|
|
514
|
+
labelled.append((block.labels[0], code))
|
|
515
|
+
else:
|
|
516
|
+
items.append(code)
|
|
517
|
+
parameter = binding.parameter(name)
|
|
518
|
+
todos = list(self.tr.todos[start:])
|
|
519
|
+
if not binding.known(name):
|
|
520
|
+
todos.append(self._todo(f"{what}: {name} is not an argument of {binding.class_path}", "", file, 0))
|
|
521
|
+
if labelled:
|
|
522
|
+
return todos, f"{parameter}={{{', '.join(f'{quote(label)}: {code}' for label, code in labelled)}}}"
|
|
523
|
+
single = nested is not None and nested.nesting == "single"
|
|
524
|
+
# An attribute HCL writes as blocks (attributes as blocks) is a list
|
|
525
|
+
as_list = nested is None and binding.typed and binding.annotations.get(parameter, "").startswith("list[")
|
|
526
|
+
if len(items) == 1 and items[0].startswith("*") and not single:
|
|
527
|
+
return todos, f"{parameter}={items[0][1:]}"
|
|
528
|
+
if len(items) == 1 and not items[0].startswith("*") and (single or (nested is None and not as_list)):
|
|
529
|
+
return todos, f"{parameter}={items[0]}"
|
|
530
|
+
if single and len(items) == 1:
|
|
531
|
+
return todos, f"{parameter}=next(iter([{items[0]}]), None)"
|
|
532
|
+
return todos, f"{parameter}=[{', '.join(items)}]"
|
|
533
|
+
|
|
534
|
+
def _block_value(self, body: Body, nested: BlockBinding | None, ctx: _Context, what: str, file: str) -> str:
|
|
535
|
+
if nested is not None and nested.class_path is not None:
|
|
536
|
+
arguments = self._arguments(body, nested.arguments, ctx, skip=set(), what=what, file=file)
|
|
537
|
+
return f"_nf_{nested.class_path}({', '.join(code for _, code in arguments)})"
|
|
538
|
+
arguments = self._dict_entries(body, ctx, what, file)
|
|
539
|
+
return "{" + ", ".join(arguments) + "}"
|
|
540
|
+
|
|
541
|
+
def _dict_entries(self, body: Body, ctx: _Context, what: str, file: str) -> list[str]:
|
|
542
|
+
"""A block body as dict entries (a generic construct's blocks)."""
|
|
543
|
+
entries = []
|
|
544
|
+
for name, attribute in body.attributes.items():
|
|
545
|
+
value = self.tr.translate(attribute.value, ctx.scope, context=f"{what}.{name}")
|
|
546
|
+
entries.append(f"{quote(name)}: {self._argument_code(value)}")
|
|
547
|
+
grouped: dict[str, list[str]] = {}
|
|
548
|
+
for block in body.blocks:
|
|
549
|
+
if block.type == "dynamic" and block.labels:
|
|
550
|
+
comprehension = self._dynamic(block, None, ctx, what, file)
|
|
551
|
+
if comprehension is not None:
|
|
552
|
+
grouped.setdefault(block.labels[0], []).append(f"*{comprehension}")
|
|
553
|
+
continue
|
|
554
|
+
grouped.setdefault(block.type, []).append("{" + ", ".join(self._dict_entries(block.body, ctx, f"{what}.{block.type}", file)) + "}")
|
|
555
|
+
for name, values in grouped.items():
|
|
556
|
+
if len(values) == 1 and not values[0].startswith("*"):
|
|
557
|
+
entries.append(f"{quote(name)}: {values[0]}")
|
|
558
|
+
else:
|
|
559
|
+
entries.append(f"{quote(name)}: [{', '.join(values)}]")
|
|
560
|
+
return entries
|
|
561
|
+
|
|
562
|
+
def _dynamic(self, block: Block, nested: BlockBinding | None, ctx: _Context, what: str, file: str) -> str | None:
|
|
563
|
+
"""A ``dynamic`` block as a list comprehension, or None (with a TODO) when it cannot be."""
|
|
564
|
+
name = block.labels[0]
|
|
565
|
+
for_each = block.body.get("for_each")
|
|
566
|
+
content = block.body.blocks_of("content")
|
|
567
|
+
if for_each is None or len(content) != 1:
|
|
568
|
+
self._todo(f"{what}: dynamic {name} block without for_each or content", block.source, file, block.line)
|
|
569
|
+
return None
|
|
570
|
+
iterator_expr = block.body.get("iterator")
|
|
571
|
+
iterator = iterator_expr.name if isinstance(iterator_expr, Name) else name
|
|
572
|
+
iterable = self.tr.translate(for_each, ctx.scope, context=f"{what} dynamic {name} for_each")
|
|
573
|
+
if not iterable.python_container:
|
|
574
|
+
self._todo(f"{what}: dynamic {name} iterates over a runtime value", block.source, file, block.line)
|
|
575
|
+
return None
|
|
576
|
+
key = self.local_names.allocate(f"{iterator}_key")
|
|
577
|
+
value = self.local_names.allocate(f"{iterator}_value")
|
|
578
|
+
try:
|
|
579
|
+
element_kind = Kind.CONSTRUCT if iterable.kind is Kind.CONSTRUCTS else (Kind.STATIC if iterable.static else Kind.MIXED)
|
|
580
|
+
# A set's members are its keys too
|
|
581
|
+
key_py = Py(value, Kind.STATIC) if iterable.shape == "set" else Py(key, Kind.STATIC)
|
|
582
|
+
iterators = {iterator: Iterator(key_py, Py(value, element_kind, binding=iterable.binding))}
|
|
583
|
+
inner = _Context(ctx.scope.child(iterators=iterators), ctx.indent, ctx.id_suffix)
|
|
584
|
+
code = self._block_value(content[0].body, nested, inner, f"{what}.{name}", file)
|
|
585
|
+
uses_key = re.search(rf"\b{key}\b", code) is not None
|
|
586
|
+
if iterable.shape == "map":
|
|
587
|
+
loop = f"for {key}, {value} in {iterable.code}.items()" if uses_key else f"for {value} in {iterable.code}.values()"
|
|
588
|
+
elif iterable.shape in {"list", "set"}:
|
|
589
|
+
loop = f"for {key}, {value} in enumerate({iterable.code})" if uses_key else f"for {value} in {iterable.operand()}"
|
|
590
|
+
else:
|
|
591
|
+
self.tr.helpers.add("items")
|
|
592
|
+
loop = f"for {key}, {value} in _nf_items({iterable.code})"
|
|
593
|
+
return f"[{code} {loop}]"
|
|
594
|
+
finally:
|
|
595
|
+
self.local_names.taken.discard(key)
|
|
596
|
+
self.local_names.taken.discard(value)
|
|
597
|
+
|
|
598
|
+
def _meta_arguments(self, kind: str, block: Block, ctx: _Context, what: str) -> list[tuple[list[Todo], str]]:
|
|
599
|
+
"""``provider``, ``depends_on`` and ``lifecycle`` as keyword arguments; provisioners as TODO markers."""
|
|
600
|
+
result: list[tuple[list[Todo], str]] = []
|
|
601
|
+
body = block.body
|
|
602
|
+
provider = provider_reference(body.get("provider"))
|
|
603
|
+
if provider is None and not self.info.is_root:
|
|
604
|
+
provider = block.labels[0].split("_")[0]
|
|
605
|
+
if provider is not None:
|
|
606
|
+
if provider in self.scope.providers:
|
|
607
|
+
provider_code = self.scope.providers[provider]
|
|
608
|
+
if provider_code.startswith("self._nf_providers.get("):
|
|
609
|
+
local_name = provider.split(".", 1)[0]
|
|
610
|
+
binding = self.resolver.provider(local_name, self._provider_source(local_name))
|
|
611
|
+
class_ref = self._class_ref(binding)
|
|
612
|
+
self.tr.helpers.add("module_provider")
|
|
613
|
+
provider_code = f"_nf_module_provider(self._nf_providers, {quote(provider)}, {class_ref})"
|
|
614
|
+
result.append(([], f"nf_provider={provider_code}"))
|
|
615
|
+
else:
|
|
616
|
+
result.append(([self._todo(f"{what}: provider {provider} is not configured in this module (pass it from the caller)", f"provider = {provider}", block.file, block.line)], "nf_provider=None"))
|
|
617
|
+
depends_on = body.get("depends_on")
|
|
618
|
+
if depends_on is not None:
|
|
619
|
+
result.append(self._depends_on(depends_on, ctx, what, block.file))
|
|
620
|
+
for lifecycle in body.blocks_of("lifecycle"):
|
|
621
|
+
result.append(self._lifecycle(kind, lifecycle, ctx, what, block.file))
|
|
622
|
+
for inner in body.blocks:
|
|
623
|
+
if inner.type in {"provisioner", "connection"}:
|
|
624
|
+
label = f' "{inner.labels[0]}"' if inner.labels else ""
|
|
625
|
+
todo = self._todo(f"{what}: {inner.type}{label} is not converted (run it as a netherframe runtime function or outside the stack)", inner.source, block.file, inner.line)
|
|
626
|
+
result.append(([todo], "")) # a TODO marker without an argument
|
|
627
|
+
return result
|
|
628
|
+
|
|
629
|
+
def _depends_on(self, expr: Expr, ctx: _Context, what: str, file: str) -> tuple[list[Todo], str]:
|
|
630
|
+
items = expr.items if isinstance(expr, TupleExpr) else (expr,)
|
|
631
|
+
codes: list[str] = []
|
|
632
|
+
todos: list[Todo] = []
|
|
633
|
+
for item in items:
|
|
634
|
+
try:
|
|
635
|
+
value = self.tr._expr(item, ctx.scope) # noqa: SLF001 - a reference, not a value
|
|
636
|
+
except Untranslatable as error:
|
|
637
|
+
todos.append(self._todo(f"{what}: depends_on {error}", item.source.strip(), file, item.line))
|
|
638
|
+
continue
|
|
639
|
+
if value.kind in {Kind.MODULE, Kind.MODULES}:
|
|
640
|
+
if value.module is None:
|
|
641
|
+
todos.append(self._todo(f"{what}: depends_on a module that is not converted", item.source.strip(), file, item.line))
|
|
642
|
+
continue
|
|
643
|
+
self.tr.helpers.add("module_resources")
|
|
644
|
+
codes.append(f"*_nf_module_resources({value.code}, include_dependencies=True)")
|
|
645
|
+
if value.kind is Kind.MODULES and value.module_dependencies is not None:
|
|
646
|
+
codes.append(f"*{value.module_dependencies}")
|
|
647
|
+
elif value.kind is Kind.CONSTRUCTS:
|
|
648
|
+
codes.append(f"*{value.code}.values()" if value.shape == "map" else f"*{value.code}")
|
|
649
|
+
elif value.kind is Kind.CONSTRUCT:
|
|
650
|
+
codes.append(value.code)
|
|
651
|
+
else:
|
|
652
|
+
todos.append(self._todo(f"{what}: depends_on {item.source.strip()} is not a construct", item.source.strip(), file, item.line))
|
|
653
|
+
return todos, f"depends_on=[{', '.join(codes)}]"
|
|
654
|
+
|
|
655
|
+
def _lifecycle(self, kind: str, block: Block, ctx: _Context, what: str, file: str) -> tuple[list[Todo], str]:
|
|
656
|
+
rules_class = "LifecycleRules" if kind == "resource" else "DataLifecycleRules"
|
|
657
|
+
self.tr.import_name("netherframe.core", rules_class)
|
|
658
|
+
arguments: list[str] = []
|
|
659
|
+
todos: list[Todo] = []
|
|
660
|
+
body = block.body
|
|
661
|
+
for name in ("create_before_destroy", "prevent_destroy"):
|
|
662
|
+
value = body.get(name)
|
|
663
|
+
if value is not None and kind == "resource":
|
|
664
|
+
start = len(self.tr.todos)
|
|
665
|
+
arguments.append(f"{name}={self.tr.translate(value, ctx.scope, context=f'{what} lifecycle.{name}').code}")
|
|
666
|
+
todos.extend(self.tr.todos[start:])
|
|
667
|
+
ignore = body.get("ignore_changes")
|
|
668
|
+
if ignore is not None and kind == "resource":
|
|
669
|
+
names = ignore_changes_names(ignore)
|
|
670
|
+
arguments.append(f"ignore_changes={literal(names)}")
|
|
671
|
+
replace = body.get("replace_triggered_by")
|
|
672
|
+
if replace is not None and kind == "resource":
|
|
673
|
+
codes = []
|
|
674
|
+
for item in replace.items if isinstance(replace, TupleExpr) else (replace,):
|
|
675
|
+
path = traversal(item)
|
|
676
|
+
try:
|
|
677
|
+
value = self.tr._expr(item, ctx.scope) if path and len(path[1]) <= 1 else None # noqa: SLF001
|
|
678
|
+
except Untranslatable:
|
|
679
|
+
value = None
|
|
680
|
+
codes.append(value.code if value is not None and value.kind is Kind.CONSTRUCT else quote(item.source.strip()))
|
|
681
|
+
arguments.append(f"replace_triggered_by=[{', '.join(codes)}]")
|
|
682
|
+
for condition_type in ("precondition", "postcondition"):
|
|
683
|
+
conditions = []
|
|
684
|
+
for condition in body.blocks_of(condition_type):
|
|
685
|
+
conditions.append(self._condition(condition, ctx, what, file, todos))
|
|
686
|
+
if conditions:
|
|
687
|
+
arguments.append(f"{condition_type}=[{', '.join(conditions)}]")
|
|
688
|
+
return todos, f"lifecycle=_nf_{rules_class}({', '.join(arguments)})"
|
|
689
|
+
|
|
690
|
+
def _condition(self, block: Block, ctx: _Context, what: str, file: str, todos: list[Todo]) -> str:
|
|
691
|
+
self.tr.import_name("netherframe.core", "Condition")
|
|
692
|
+
condition = block.body.get("condition")
|
|
693
|
+
message = block.body.get("error_message")
|
|
694
|
+
start = len(self.tr.todos)
|
|
695
|
+
if condition is None:
|
|
696
|
+
condition_code = "True"
|
|
697
|
+
elif _refers_to_self(condition):
|
|
698
|
+
condition_code = quote(terraform_text(condition))
|
|
699
|
+
else:
|
|
700
|
+
condition_code = self.tr.translate(condition, ctx.scope, context=f"{what} {block.type}").code
|
|
701
|
+
message_code = self.tr.translate(message, ctx.scope, context=f"{what} {block.type}").code if message is not None else '""'
|
|
702
|
+
todos.extend(self.tr.todos[start:])
|
|
703
|
+
return f"_nf_Condition(condition={condition_code}, error_message={message_code})"
|
|
704
|
+
|
|
705
|
+
# --- Modules -----------------------------------------------------------------------------
|
|
706
|
+
|
|
707
|
+
def _module_call(self, block: Block, ctx: _Context) -> None:
|
|
708
|
+
name = block.labels[0]
|
|
709
|
+
source = module_source_text(block) or ""
|
|
710
|
+
attribute = self._unconverted.get(name) or self.attribute_names.allocate(name)
|
|
711
|
+
target = f"{self.owner}.{attribute}"
|
|
712
|
+
start = len(self.tr.todos)
|
|
713
|
+
child = self._child_info(source, name)
|
|
714
|
+
count = block.body.get("count")
|
|
715
|
+
for_each = block.body.get("for_each")
|
|
716
|
+
if child is None:
|
|
717
|
+
if meta_value := block.body.get("providers"):
|
|
718
|
+
self._todo(f"module.{name}: providers is not converted for an unconverted module", f"providers = {meta_value.source.strip()}", block.file, block.line)
|
|
719
|
+
if meta_value := block.body.get("depends_on"):
|
|
720
|
+
self._todo(f"module.{name}: depends_on is not converted for an unconverted module", f"depends_on = {meta_value.source.strip()}", block.file, block.line)
|
|
721
|
+
version = block.body.get("version")
|
|
722
|
+
version_text = version.value if isinstance(version, Literal) else None
|
|
723
|
+
reason = "a registry or remote module is not converted" if not is_local_source(source) else "the local module has no Terraform files"
|
|
724
|
+
self._todo(f"module.{name}: {reason} (source {source}{', version ' + str(version_text) if version_text else ''})", block.source, block.file, block.line)
|
|
725
|
+
self.tr.helpers.add("UnconvertedModule")
|
|
726
|
+
# The arguments, as Terraform text: what porting the module starts from
|
|
727
|
+
inputs = [f"{quote(argument)}: {quote(terraform_text(value.value))}" for argument, value in block.body.attributes.items() if argument not in _MODULE_META]
|
|
728
|
+
self._todo_lines(ctx.indent, self._take_todos(start))
|
|
729
|
+
version_argument = f", version={quote(str(version_text))}" if version_text else ""
|
|
730
|
+
self._emit(ctx.indent, f"{target} = _nf_UnconvertedModule({quote(name)}, source={quote(source)}{version_argument}, inputs={{{', '.join(inputs)}}})")
|
|
731
|
+
self._count("module calls (not converted)")
|
|
732
|
+
return
|
|
733
|
+
loop_ctx, loop_header, _ = self._loop(count, for_each, ctx, f"module.{name}")
|
|
734
|
+
prefix_base = "" if self.info.is_root else "{nf_prefix}"
|
|
735
|
+
nf_prefix = f'f"{prefix_base}{name}{loop_ctx.id_suffix}_"' if (loop_header or not self.info.is_root) else quote(f"{name}_")
|
|
736
|
+
arguments: list[tuple[list[Todo], str]] = []
|
|
737
|
+
variables = {variable.labels[0] for variable in child.source.variables}
|
|
738
|
+
child_names = Names(set(_SCOPE_NAMES))
|
|
739
|
+
parameter_names = {variable.labels[0]: child_names.allocate(variable.labels[0]) for variable in child.source.variables}
|
|
740
|
+
for argument, value in block.body.attributes.items():
|
|
741
|
+
if argument in _MODULE_META:
|
|
742
|
+
continue
|
|
743
|
+
arg_start = len(self.tr.todos)
|
|
744
|
+
py = self.tr.translate(value.value, loop_ctx.scope, context=f"module.{name}.{argument}")
|
|
745
|
+
todos = list(self.tr.todos[arg_start:])
|
|
746
|
+
if argument not in variables:
|
|
747
|
+
todos.append(self._todo(f"module.{name}: {argument} is not a variable of {child.rel}", "", block.file, value.line))
|
|
748
|
+
continue
|
|
749
|
+
child.argument_kinds[argument] = max(child.argument_kinds.get(argument, Kind.STATIC), Kind.RUNTIME if py.kind in {Kind.RUNTIME, Kind.CONSTRUCT} else join_kinds(py.kind))
|
|
750
|
+
arguments.append((todos, f"{parameter_names[argument]}={py.code}"))
|
|
751
|
+
class_ref = f"_nf_{child.class_name}"
|
|
752
|
+
self.tr.import_name(_relative_import(self.info, child), child.class_name)
|
|
753
|
+
fixed = [self.scope_code, f"nf_prefix={nf_prefix}"]
|
|
754
|
+
providers = block.body.get("providers")
|
|
755
|
+
mapped_providers: dict[str, str] = {}
|
|
756
|
+
if providers is None:
|
|
757
|
+
mapped_providers = {key: code for key, code in self.scope.providers.items() if "." not in key}
|
|
758
|
+
elif isinstance(providers, ObjectExpr):
|
|
759
|
+
for key_expr, value_expr in providers.items:
|
|
760
|
+
key = provider_reference(key_expr) or (key_expr.value if isinstance(key_expr, Literal) and isinstance(key_expr.value, str) else None)
|
|
761
|
+
provider = provider_reference(value_expr)
|
|
762
|
+
if key is None or provider not in self.scope.providers:
|
|
763
|
+
self._todo(f"module.{name}: providers mapping needs configured provider references", providers.source, block.file, providers.line)
|
|
764
|
+
continue
|
|
765
|
+
mapped_providers[key] = self.scope.providers[provider]
|
|
766
|
+
else:
|
|
767
|
+
self._todo(f"module.{name}: providers must be a static provider mapping", providers.source, block.file, providers.line)
|
|
768
|
+
if mapped_providers:
|
|
769
|
+
fixed.append(f"_nf_providers={{{', '.join(f'{quote(key)}: {code}' for key, code in mapped_providers.items())}}}")
|
|
770
|
+
dependency_code = None
|
|
771
|
+
if dependency_expr := block.body.get("depends_on"):
|
|
772
|
+
_, argument = self._depends_on(dependency_expr, ctx, f"module.{name}", block.file)
|
|
773
|
+
dependency_code = argument.removeprefix("depends_on=")
|
|
774
|
+
self.tr.helpers.update({"module_resources", "add_module_dependencies"})
|
|
775
|
+
if loop_header and dependency_code is not None:
|
|
776
|
+
# A zero-instance module still carries its declaration's prerequisites.
|
|
777
|
+
dependency_target = f"self._nf_{target.removeprefix('self.')}_dependencies"
|
|
778
|
+
self._emit(ctx.indent, f"{dependency_target} = {dependency_code}")
|
|
779
|
+
dependency_code = dependency_target
|
|
780
|
+
if loop_header:
|
|
781
|
+
collection = "dict" if for_each is not None else "list"
|
|
782
|
+
self._todo_lines(ctx.indent, self._take_todos(start))
|
|
783
|
+
start = len(self.tr.todos)
|
|
784
|
+
self._emit(ctx.indent, f"{target}: {collection}[{'str, ' if for_each is not None else ''}{class_ref}] = {'{}' if for_each is not None else '[]'}")
|
|
785
|
+
self._emit(ctx.indent, loop_header)
|
|
786
|
+
if for_each is not None:
|
|
787
|
+
head = f"{target}[{loop_ctx.scope.iterators['each'].key.code}] = {class_ref}("
|
|
788
|
+
self._statement(loop_ctx, head, fixed, arguments, start)
|
|
789
|
+
instance = f"{target}[{loop_ctx.scope.iterators['each'].key.code}]"
|
|
790
|
+
else:
|
|
791
|
+
self._statement(loop_ctx, f"{target}.append({class_ref}(", fixed, arguments, start, close="))")
|
|
792
|
+
instance = f"{target}[-1]"
|
|
793
|
+
self.scope.modules[name] = Py(target, Kind.MODULES, module=child, module_outputs=child.outputs, module_dependencies=dependency_code, shape="map" if for_each is not None else "list")
|
|
794
|
+
else:
|
|
795
|
+
self._statement(ctx, f"{target} = {class_ref}(", fixed, arguments, start)
|
|
796
|
+
instance = target
|
|
797
|
+
self.scope.modules[name] = Py(target, Kind.MODULE, module=child, module_outputs=child.outputs)
|
|
798
|
+
if dependency_code is not None:
|
|
799
|
+
self._emit(loop_ctx.indent, f"_nf_add_module_dependencies({instance}, {dependency_code})")
|
|
800
|
+
if not self.info.is_root:
|
|
801
|
+
self.tr.helpers.add("module_resources")
|
|
802
|
+
self._emit(ctx.indent, f"self._nf_resources.extend(_nf_module_resources({target}))")
|
|
803
|
+
self._emit(ctx.indent, f"self._nf_depends_on.extend(_nf_module_resources({target}, include_dependencies=True))")
|
|
804
|
+
if loop_header and dependency_code is not None:
|
|
805
|
+
self._emit(ctx.indent, f"self._nf_depends_on.extend({dependency_code})")
|
|
806
|
+
self.module_calls.append((name, loop_header is not None, child))
|
|
807
|
+
self._count("module calls")
|
|
808
|
+
|
|
809
|
+
def _child_info(self, source: str, name: str) -> ModuleInfo | None:
|
|
810
|
+
if directory := self.module.resolved_modules.get(name):
|
|
811
|
+
return self.modules.get(directory)
|
|
812
|
+
if not is_local_source(source):
|
|
813
|
+
return None
|
|
814
|
+
directory = (self.module.directory / source).resolve()
|
|
815
|
+
return self.modules.get(directory)
|
|
816
|
+
|
|
817
|
+
def _argument_code(self, value: Py) -> str:
|
|
818
|
+
self.tr.import_name("netherframe.core.values.hcl_expressions", "hcl_value")
|
|
819
|
+
return f"_nf_hcl_value({value.code})"
|
|
820
|
+
|
|
821
|
+
# --- Outputs -----------------------------------------------------------------------------
|
|
822
|
+
|
|
823
|
+
def _output(self, block: Block, ctx: _Context) -> None:
|
|
824
|
+
name = block.labels[0]
|
|
825
|
+
value_expr = block.body.get("value")
|
|
826
|
+
start = len(self.tr.todos)
|
|
827
|
+
value = self.tr.translate(value_expr, ctx.scope, context=f"output {name}") if value_expr is not None else Py("None")
|
|
828
|
+
if value.kind in {Kind.CONSTRUCT, Kind.CONSTRUCTS, Kind.MODULE, Kind.MODULES} and self.info.is_root and value_expr is not None:
|
|
829
|
+
self.tr.todos.append(Todo(f"output {name}: a whole resource or module object as an output is not converted", value_expr.source.strip(), block.file, value_expr.line))
|
|
830
|
+
self.tr.import_name("netherframe.core.values.hcl_expressions", "RawHcl")
|
|
831
|
+
value = Py(f"_nf_RawHcl({quote(terraform_text(value_expr))})", Kind.RUNTIME)
|
|
832
|
+
for meta in ("depends_on", "precondition"):
|
|
833
|
+
if block.body.get(meta) is not None or block.body.blocks_of(meta):
|
|
834
|
+
self._todo(f"output {name}: {meta} is not converted", "", block.file, block.line)
|
|
835
|
+
if self.info.is_root:
|
|
836
|
+
self.tr.import_name("netherframe.core", "Output")
|
|
837
|
+
arguments = [f"nf_scope={self.scope_code}", f"nf_id={quote(name)}", f"value={self._argument_code(value)}"]
|
|
838
|
+
description = block.body.get("description")
|
|
839
|
+
if description is not None:
|
|
840
|
+
arguments.append(f"description={self.tr.translate(description, ctx.scope, context=f'output {name} description').code}")
|
|
841
|
+
sensitive = block.body.get("sensitive")
|
|
842
|
+
if isinstance(sensitive, Literal) and sensitive.value is True:
|
|
843
|
+
arguments.append("sensitive=True")
|
|
844
|
+
self._statement(ctx, "_nf_Output(", arguments, [], start)
|
|
845
|
+
else:
|
|
846
|
+
self._todo_lines(ctx.indent, self._take_todos(start))
|
|
847
|
+
attribute = self.info.outputs.get(name) or self.attribute_names.allocate(name)
|
|
848
|
+
self.info.outputs[name] = attribute
|
|
849
|
+
self._emit(ctx.indent, f"{self.owner}.{attribute} = {value.code}")
|
|
850
|
+
self._count("outputs")
|
|
851
|
+
|
|
852
|
+
# --- Header ------------------------------------------------------------------------------
|
|
853
|
+
|
|
854
|
+
def _header(self, parameters: list[str]) -> list[str]:
|
|
855
|
+
info = self.info
|
|
856
|
+
lines = [f'"""Netherframe conversion of the Terraform module {"at the root" if info.is_root else info.rel} (`nf convert`).', ""]
|
|
857
|
+
lines.append("Review every `TODO(nf convert)` marker: each one names what was not converted and quotes its HCL.")
|
|
858
|
+
lines.append('"""')
|
|
859
|
+
lines.append("")
|
|
860
|
+
lines.append("from __future__ import annotations")
|
|
861
|
+
lines.append("")
|
|
862
|
+
imports = set(self.tr.imports)
|
|
863
|
+
imports.add(("netherframe.core", "Stack"))
|
|
864
|
+
if info.is_root:
|
|
865
|
+
imports.add(("netherframe.core", "App"))
|
|
866
|
+
else:
|
|
867
|
+
imports.add(("netherframe.core", "Resource"))
|
|
868
|
+
imports.add(("netherframe.core", "Provider"))
|
|
869
|
+
if self.tr.helpers:
|
|
870
|
+
module = f".{_SUPPORT_MODULE}" if info.is_root else f"..{_SUPPORT_MODULE}"
|
|
871
|
+
imports.update((module, helper) for helper in self.tr.helpers)
|
|
872
|
+
plain = sorted(module for module, name in imports if not name)
|
|
873
|
+
lines.extend(f"import {module} as _nf_{module}" for module in plain)
|
|
874
|
+
if any("Any" in parameter for parameter in parameters):
|
|
875
|
+
imports.add(("typing", "Any"))
|
|
876
|
+
by_module: dict[str, set[str]] = {}
|
|
877
|
+
for module, name in imports:
|
|
878
|
+
if name:
|
|
879
|
+
by_module.setdefault(module, set()).add(name)
|
|
880
|
+
stdlib = [module for module in by_module if module in {"typing", "pathlib"}]
|
|
881
|
+
absolute = [module for module in by_module if module not in stdlib and not module.startswith(".")]
|
|
882
|
+
relative = [module for module in by_module if module.startswith(".")]
|
|
883
|
+
for group in (sorted(stdlib), sorted(absolute), sorted(relative)):
|
|
884
|
+
for module in group:
|
|
885
|
+
names = [f"{name} as _nf_{name}" for name in sorted(by_module[module])]
|
|
886
|
+
lines.append(f"from {module} import {', '.join(names)}")
|
|
887
|
+
if group:
|
|
888
|
+
lines.append("")
|
|
889
|
+
lines.extend(["", ""])
|
|
890
|
+
doc = [f" {line}" for line in self._class_doc()]
|
|
891
|
+
if info.is_root:
|
|
892
|
+
lines.append(f"class {info.class_name}(_nf_Stack):")
|
|
893
|
+
lines.extend(doc)
|
|
894
|
+
lines.append("")
|
|
895
|
+
signature = ["self", "*", "nf_scope: _nf_App", f"nf_id: str = {quote(info.default_id)}", *parameters]
|
|
896
|
+
lines.append(f" def __init__({', '.join(signature)}) -> None:")
|
|
897
|
+
lines.append(" super().__init__(nf_scope=nf_scope, nf_id=nf_id)")
|
|
898
|
+
else:
|
|
899
|
+
lines.append(f"class {info.class_name}:")
|
|
900
|
+
lines.extend(doc)
|
|
901
|
+
lines.append("")
|
|
902
|
+
signature = ["self", "scope: _nf_Stack", "*", "nf_prefix: str", "_nf_providers: dict[str, _nf_Provider | None] | None = None", *parameters]
|
|
903
|
+
lines.append(f" def __init__({', '.join(signature)}) -> None:")
|
|
904
|
+
lines.append(" self._nf_providers = _nf_providers or {}")
|
|
905
|
+
lines.append(" self._nf_resources: list[_nf_Resource] = []")
|
|
906
|
+
lines.append(" self._nf_depends_on: list[_nf_Resource] = []")
|
|
907
|
+
return lines
|
|
908
|
+
|
|
909
|
+
def _class_doc(self) -> list[str]:
|
|
910
|
+
info = self.info
|
|
911
|
+
if info.is_root:
|
|
912
|
+
summary = "The root Terraform module as a stack; its variables are keyword arguments."
|
|
913
|
+
else:
|
|
914
|
+
summary = "A Terraform module: builds its constructs into ``scope``, their ``nf_id`` prefixed by ``nf_prefix``; its outputs are attributes."
|
|
915
|
+
lines = ['"""' + summary]
|
|
916
|
+
if self._variable_docs:
|
|
917
|
+
lines.extend(["", "Args:"])
|
|
918
|
+
lines.extend(f" {doc}" for doc in self._variable_docs)
|
|
919
|
+
lines.append('"""')
|
|
920
|
+
return lines
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def _dedent_source(text: str) -> list[str]:
|
|
924
|
+
"""HCL source lines without the indentation of the block they came from.
|
|
925
|
+
|
|
926
|
+
A block's source starts at its first character, so its later lines keep the block's
|
|
927
|
+
indentation, which the closing line shows.
|
|
928
|
+
"""
|
|
929
|
+
lines = text.strip("\n").splitlines()
|
|
930
|
+
if len(lines) < 2:
|
|
931
|
+
return lines
|
|
932
|
+
indent = len(lines[-1]) - len(lines[-1].lstrip())
|
|
933
|
+
rest = [line[indent:] if line[:indent].strip() == "" else line.lstrip() for line in lines[1:]]
|
|
934
|
+
return [lines[0], *rest]
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _refers_to_self(expr: Expr) -> bool:
|
|
938
|
+
from .hcl_ast import walk
|
|
939
|
+
|
|
940
|
+
return any(isinstance(node, Name) and node.name == "self" for node in walk(expr))
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def _relative_import(caller: ModuleInfo, child: ModuleInfo) -> str:
|
|
944
|
+
name = child.python_module.rsplit(".", 1)[-1]
|
|
945
|
+
return f".modules.{name}" if caller.is_root else f".{name}"
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def python_type(type_expr: Expr | None) -> tuple[str, str | None]:
|
|
949
|
+
"""A variable's type constraint as a Python annotation, and its collection shape."""
|
|
950
|
+
if type_expr is None:
|
|
951
|
+
return "Any", None
|
|
952
|
+
if isinstance(type_expr, Template) and len(type_expr.parts) == 1 and isinstance(type_expr.parts[0], Expr):
|
|
953
|
+
type_expr = type_expr.parts[0]
|
|
954
|
+
if isinstance(type_expr, Name):
|
|
955
|
+
return {"string": "str", "number": "int", "bool": "bool", "any": "Any"}.get(type_expr.name, "Any"), None
|
|
956
|
+
if isinstance(type_expr, Call):
|
|
957
|
+
args = type_expr.args
|
|
958
|
+
inner = python_type(args[0])[0] if args else "Any"
|
|
959
|
+
match type_expr.name:
|
|
960
|
+
case "list":
|
|
961
|
+
return f"list[{inner}]", "list"
|
|
962
|
+
case "set":
|
|
963
|
+
return f"list[{inner}]", "set"
|
|
964
|
+
case "map":
|
|
965
|
+
return f"dict[str, {inner}]", "map"
|
|
966
|
+
case "object":
|
|
967
|
+
return "dict[str, Any]", "map"
|
|
968
|
+
case "tuple":
|
|
969
|
+
return "list[Any]", "list"
|
|
970
|
+
case "optional":
|
|
971
|
+
return inner, python_type(args[0])[1] if args else None
|
|
972
|
+
return "Any", None
|