python2rust 0.1.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 (102) hide show
  1. python2rust/__init__.py +8 -0
  2. python2rust/__main__.py +5 -0
  3. python2rust/_core.py +44 -0
  4. python2rust/agent/__init__.py +0 -0
  5. python2rust/agent/agents.py +333 -0
  6. python2rust/agent/apply.py +516 -0
  7. python2rust/agent/finish.py +295 -0
  8. python2rust/agent/fixers.py +229 -0
  9. python2rust/agent/loop.py +441 -0
  10. python2rust/agent/patches.py +1165 -0
  11. python2rust/agent/port.py +579 -0
  12. python2rust/agent/prompts/judge_v2.md +96 -0
  13. python2rust/agent/review.py +34 -0
  14. python2rust/agent/rustlex.py +232 -0
  15. python2rust/cli/__init__.py +0 -0
  16. python2rust/cli/doctor.py +62 -0
  17. python2rust/cli/inputs.py +105 -0
  18. python2rust/cli/main.py +1162 -0
  19. python2rust/cli/ops.py +642 -0
  20. python2rust/cli/workflow.py +178 -0
  21. python2rust/core/__init__.py +38 -0
  22. python2rust/core/config.py +263 -0
  23. python2rust/core/constructs.py +124 -0
  24. python2rust/core/diagnostics.py +280 -0
  25. python2rust/core/emit/__init__.py +5 -0
  26. python2rust/core/emit/crates.py +51 -0
  27. python2rust/core/emit/render.py +561 -0
  28. python2rust/core/emit/schema.py +168 -0
  29. python2rust/core/emit/translate.py +304 -0
  30. python2rust/core/frontend/__init__.py +1 -0
  31. python2rust/core/frontend/module.py +896 -0
  32. python2rust/core/frontend/names.py +129 -0
  33. python2rust/core/frontend/project.py +277 -0
  34. python2rust/core/frontend/project_imports.py +173 -0
  35. python2rust/core/frontend/symbols.py +132 -0
  36. python2rust/core/frontend/walrus.py +59 -0
  37. python2rust/core/ir/__init__.py +1 -0
  38. python2rust/core/ir/nodes.py +675 -0
  39. python2rust/core/ir/rtypes.py +122 -0
  40. python2rust/core/ir/types.py +326 -0
  41. python2rust/core/lower/__init__.py +1 -0
  42. python2rust/core/lower/calls.py +1125 -0
  43. python2rust/core/lower/context.py +223 -0
  44. python2rust/core/lower/exceptions.py +317 -0
  45. python2rust/core/lower/exprs.py +845 -0
  46. python2rust/core/lower/fstrings.py +141 -0
  47. python2rust/core/lower/funcs.py +276 -0
  48. python2rust/core/lower/lowerer.py +366 -0
  49. python2rust/core/lower/modelcalls.py +195 -0
  50. python2rust/core/lower/models.py +645 -0
  51. python2rust/core/lower/stmts.py +722 -0
  52. python2rust/core/lower/testing.py +601 -0
  53. python2rust/core/lower/validation.py +253 -0
  54. python2rust/core/passes/__init__.py +1 -0
  55. python2rust/core/passes/aliasing.py +311 -0
  56. python2rust/core/passes/analysis.py +207 -0
  57. python2rust/core/passes/devirt.py +329 -0
  58. python2rust/core/passes/ownership.py +259 -0
  59. python2rust/core/passes/raises.py +275 -0
  60. python2rust/core/rt_lib.rs +2071 -0
  61. python2rust/data/README.md +81 -0
  62. python2rust/data/py2many_builtins.toml +4744 -0
  63. python2rust/errors.py +28 -0
  64. python2rust/py.typed +0 -0
  65. python2rust/report/__init__.py +0 -0
  66. python2rust/report/constructs.py +31 -0
  67. python2rust/report/contract.py +688 -0
  68. python2rust/report/corpus.py +323 -0
  69. python2rust/report/explain.py +168 -0
  70. python2rust/report/schemas.py +914 -0
  71. python2rust/server/__init__.py +0 -0
  72. python2rust/server/mcp_server.py +289 -0
  73. python2rust/server/mcp_workflow.py +100 -0
  74. python2rust/skill/SKILL.md +214 -0
  75. python2rust/verify/__init__.py +0 -0
  76. python2rust/verify/check.py +1135 -0
  77. python2rust/verify/equiv/__init__.py +1264 -0
  78. python2rust/verify/equiv/compare.py +455 -0
  79. python2rust/verify/equiv/harness.py +505 -0
  80. python2rust/verify/equiv/judge.py +358 -0
  81. python2rust/verify/equiv/procs.py +255 -0
  82. python2rust/verify/equiv/runner.py +248 -0
  83. python2rust/verify/equiv/types.py +543 -0
  84. python2rust/verify/keystore.py +76 -0
  85. python2rust/verify/ladder.py +396 -0
  86. python2rust/verify/sandbox.py +370 -0
  87. python2rust/verify/testrun.py +280 -0
  88. python2rust/workflow/__init__.py +0 -0
  89. python2rust/workflow/brief.py +312 -0
  90. python2rust/workflow/interview.py +366 -0
  91. python2rust/workflow/layout.py +103 -0
  92. python2rust/workflow/planner.py +409 -0
  93. python2rust/workflow/project.py +134 -0
  94. python2rust/workflow/schemas.py +265 -0
  95. python2rust/workflow/state.py +392 -0
  96. python2rust/workflow/staticscan.py +209 -0
  97. python2rust-0.1.0.dist-info/METADATA +395 -0
  98. python2rust-0.1.0.dist-info/RECORD +102 -0
  99. python2rust-0.1.0.dist-info/WHEEL +4 -0
  100. python2rust-0.1.0.dist-info/entry_points.txt +4 -0
  101. python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
@@ -0,0 +1,129 @@
1
+ """Identifier handling: Rust keyword mangling and snake_case / CamelCase conversion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ RUST_KEYWORDS = frozenset(
8
+ [
9
+ "as",
10
+ "async",
11
+ "await",
12
+ "break",
13
+ "const",
14
+ "continue",
15
+ "crate",
16
+ "dyn",
17
+ "else",
18
+ "enum",
19
+ "extern",
20
+ "false",
21
+ "fn",
22
+ "for",
23
+ "if",
24
+ "impl",
25
+ "in",
26
+ "let",
27
+ "loop",
28
+ "match",
29
+ "mod",
30
+ "move",
31
+ "mut",
32
+ "pub",
33
+ "ref",
34
+ "return",
35
+ "self",
36
+ "Self",
37
+ "static",
38
+ "struct",
39
+ "super",
40
+ "trait",
41
+ "true",
42
+ "type",
43
+ "unsafe",
44
+ "use",
45
+ "where",
46
+ "while",
47
+ "abstract",
48
+ "become",
49
+ "box",
50
+ "do",
51
+ "final",
52
+ "macro",
53
+ "override",
54
+ "priv",
55
+ "try",
56
+ "typeof",
57
+ "unsized",
58
+ "virtual",
59
+ "yield",
60
+ "gen",
61
+ "union",
62
+ ]
63
+ )
64
+ _WORD = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+|[^\W_]+", re.UNICODE)
65
+
66
+
67
+ def _words(name: str) -> list[str]:
68
+ return _WORD.findall(name)
69
+
70
+
71
+ NOT_RAW = frozenset({"self", "Self", "super", "crate"}) # the only keywords that cannot be `r#`
72
+
73
+
74
+ def mangle(name: str) -> str:
75
+ """Make `name` a legal Rust identifier: keywords become raw identifiers (`r#type`)."""
76
+ if not name or name == "_": # `_` alone is not an identifier in Rust
77
+ return "underscore_"
78
+ if name[0].isdigit():
79
+ name = "_" + name
80
+ if name in NOT_RAW:
81
+ return name + "_"
82
+ return f"r#{name}" if name in RUST_KEYWORDS else name
83
+
84
+
85
+ def wire_name(rust: str) -> str:
86
+ """The name serde uses for a field: raw identifiers lose their `r#`."""
87
+ return rust.removeprefix("r#")
88
+
89
+
90
+ def fn_name(name: str) -> str:
91
+ """Function names stay as written when they are valid Rust; CamelCase-looking ones are snake_cased."""
92
+ if re.fullmatch(r"[^\W\d]\w*", name) and name == name.lower():
93
+ return mangle(name)
94
+ return snake(name)
95
+
96
+
97
+ def snake(name: str) -> str:
98
+ """`getHTTPResponse` -> `get_http_response`; leading underscores are dropped."""
99
+ stripped = name.lstrip("_")
100
+ if stripped.lower() == stripped: # already lower case (any script): keep as written
101
+ return mangle(stripped or "_")
102
+ words = _words(stripped)
103
+ return mangle("_".join(w.lower() for w in words) if words else name.strip("_") or "_")
104
+
105
+
106
+ def camel(name: str) -> str:
107
+ """`in_progress`/`IN_PROGRESS` -> `InProgress`; already-CamelCase names are kept."""
108
+ stripped = name.lstrip("_")
109
+ if stripped and "_" not in stripped and not stripped.isupper() and stripped[0].isupper():
110
+ return mangle(stripped)
111
+ words = _words(stripped)
112
+ return mangle("".join(w[:1].upper() + w[1:].lower() for w in words) if words else "Unnamed")
113
+
114
+
115
+ def const_name(name: str) -> str:
116
+ return mangle("_".join(w.upper() for w in _words(name.lstrip("_"))) or name)
117
+
118
+
119
+ def variant_name(value: str, index: int, taken: set[str]) -> str:
120
+ """CamelCase variant for an arbitrary string value (Literal members, Enum values)."""
121
+ words = [w for w in re.split(r"[^0-9A-Za-z]+", value) if w]
122
+ base = "".join(w[:1].upper() + w[1:] for w in words) or f"Variant{index}"
123
+ if base[0].isdigit():
124
+ base = "V" + base
125
+ base = mangle(base)
126
+ while base in taken:
127
+ base += str(index)
128
+ taken.add(base)
129
+ return base
@@ -0,0 +1,277 @@
1
+ """Project mode: translate a directory of Python modules into one Rust crate layout.
2
+
3
+ `translate_project(root, files, config)` parses every module, builds the import graph (cycles get a
4
+ diagnostic, PY2RS054), translates modules in dependency order so each one sees the symbols of the
5
+ modules it imports (functions, models, enums, constants, exceptions, aliases; relative imports,
6
+ `import a.b as m`, re-exports through `__init__.py`), and lays the result out as a crate:
7
+
8
+ lib.rs `pub mod a; pub mod top;`
9
+ a/mod.rs the translated `a/__init__.py` (if any) + `pub mod b;` declarations
10
+ a/b.rs the translated `a/b.py`
11
+ top.rs the translated `top.py`
12
+
13
+ `ProjectResult.layout` maps those relative paths (under the crate's `src/`) to file contents.
14
+ Imports of project modules become `use crate::a::b::name;` (`pub use` inside `__init__`);
15
+ imports of unknown project names or modules stay explicit TODOs (PY2RS055) naming the missing
16
+ module. Modules outside the project follow `import_map` / `library_map` as in single-file mode.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import ast
22
+ from collections.abc import Sequence
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+
26
+ from ..config import Config
27
+ from ..diagnostics import Diagnostic
28
+ from ..emit.crates import CrateSpec, required_crates
29
+ from ..emit.translate import TranslateResult, translate_source
30
+ from ..passes.raises import collect_catchable
31
+ from .names import mangle
32
+ from .symbols import ProjectContext, ProjectIndex
33
+
34
+ SKIP_DIRS = {"__pycache__", "venv", "node_modules", "site-packages", "build", "dist"}
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ModuleInfo:
39
+ name: str # dotted Python module name
40
+ path: str # relative Python path (posix)
41
+ rust_module: str # crate-relative module path, e.g. `crate::a::b`
42
+ rust_path: str # relative file under src/, e.g. `a/b.rs` or `a/mod.rs`
43
+ is_package: bool
44
+ depends_on: tuple[str, ...] # project modules this one imports
45
+ external_imports: tuple[str, ...] # root names of imports outside the project
46
+ in_cycle: bool = False
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ProjectResult:
51
+ """Per-file results, the crate layout and project-level facts (all keyed deterministically)."""
52
+
53
+ files: dict[str, TranslateResult] # relative Python path -> result
54
+ modules: tuple[ModuleInfo, ...] # dependency order (dependencies first)
55
+ layout: dict[str, str] # relative path under src/ -> Rust source
56
+ diagnostics: tuple[Diagnostic, ...] # project-level: cycles
57
+ stats: dict[str, int] # summed per-file stats + modules / edges / cycles / unresolved.*
58
+ dependencies: tuple[str, ...] = field(default=()) # names of the crates the code uses
59
+ required_features: tuple[str, ...] = () # python2rust-rt features needed by any module
60
+ required_crates: dict[str, CrateSpec] = field(default_factory=dict) # merged crate specs
61
+
62
+
63
+ def _module_name(rel: Path) -> tuple[str, bool]:
64
+ parts = list(rel.with_suffix("").parts)
65
+ package = parts[-1] == "__init__"
66
+ if package:
67
+ parts.pop()
68
+ return ".".join(parts), package
69
+
70
+
71
+ def _collect(root: Path, files: Sequence[str | Path] | None) -> list[Path]:
72
+ if files is None:
73
+ found = [
74
+ p for p in sorted(root.rglob("*.py"))
75
+ if not any(part in SKIP_DIRS or part.startswith(".") for part in p.relative_to(root).parts)
76
+ ] # fmt: skip
77
+ return found
78
+ out: list[Path] = []
79
+ for f in files:
80
+ text = str(f)
81
+ if any(c in text for c in "*?["):
82
+ out += sorted(p for p in root.glob(text) if p.is_file())
83
+ else:
84
+ out.append(root / text if not Path(text).is_absolute() else Path(text))
85
+ return sorted(dict.fromkeys(out))
86
+
87
+
88
+ def _imports(
89
+ tree: ast.Module, module: str, is_package: bool, index: ProjectIndex
90
+ ) -> tuple[set[str], set[str]]:
91
+ """(project modules imported, external root names) of one parsed module."""
92
+ ctx = ProjectContext(index, module, is_package)
93
+ inside: set[str] = set()
94
+ outside: set[str] = set()
95
+ for node in ast.walk(tree):
96
+ if isinstance(node, ast.Import):
97
+ for a in node.names:
98
+ (inside if a.name in index.names else outside).add(
99
+ a.name if a.name in index.names else a.name.split(".")[0]
100
+ )
101
+ elif isinstance(node, ast.ImportFrom):
102
+ target = ctx.absolute(node.module, node.level)
103
+ if target is None or target not in index.names:
104
+ if target:
105
+ outside.add(target.split(".")[0])
106
+ continue
107
+ inside.add(target)
108
+ inside |= {
109
+ f"{target}.{a.name}" for a in node.names if f"{target}.{a.name}" in index.names
110
+ }
111
+ inside.discard(module)
112
+ return inside, outside - {n.split(".")[0] for n in inside}
113
+
114
+
115
+ def _order(names: list[str], edges: dict[str, set[str]]) -> tuple[list[str], list[list[str]]]:
116
+ """Dependency order (dependencies first) and the import cycles (strongly connected components)."""
117
+ index_of: dict[str, int] = {}
118
+ low: dict[str, int] = {}
119
+ stack: list[str] = []
120
+ on_stack: set[str] = set()
121
+ order: list[str] = []
122
+ cycles: list[list[str]] = []
123
+ counter = 0
124
+ for start in names:
125
+ if start in index_of:
126
+ continue
127
+ work = [(start, iter(sorted(edges[start])))]
128
+ index_of[start] = low[start] = counter
129
+ counter += 1
130
+ stack.append(start)
131
+ on_stack.add(start)
132
+ while work:
133
+ node, it = work[-1]
134
+ advanced = False
135
+ for nxt in it:
136
+ if nxt not in index_of:
137
+ index_of[nxt] = low[nxt] = counter
138
+ counter += 1
139
+ stack.append(nxt)
140
+ on_stack.add(nxt)
141
+ work.append((nxt, iter(sorted(edges[nxt]))))
142
+ advanced = True
143
+ break
144
+ if nxt in on_stack:
145
+ low[node] = min(low[node], index_of[nxt])
146
+ if advanced:
147
+ continue
148
+ work.pop()
149
+ if work:
150
+ parent = work[-1][0]
151
+ low[parent] = min(low[parent], low[node])
152
+ if low[node] == index_of[node]:
153
+ comp = []
154
+ while True:
155
+ top = stack.pop()
156
+ on_stack.discard(top)
157
+ comp.append(top)
158
+ if top == node:
159
+ break
160
+ comp.sort()
161
+ order += comp # components complete dependencies-first
162
+ if len(comp) > 1:
163
+ cycles.append(comp)
164
+ return order, cycles
165
+
166
+
167
+ def _rust_path(name: str, is_package: bool) -> str:
168
+ parts = [mangle(p).removeprefix("r#") for p in name.split(".")]
169
+ return "/".join([*parts, "mod.rs"]) if is_package else "/".join(parts) + ".rs"
170
+
171
+
172
+ def _layout(
173
+ infos: list[ModuleInfo], files: dict[str, TranslateResult], names: set[str], packages: set[str]
174
+ ) -> dict[str, str]:
175
+ layout: dict[str, str] = {}
176
+ children: dict[str, list[str]] = {"": []}
177
+ for name in sorted(names):
178
+ parent = name.rpartition(".")[0]
179
+ children.setdefault(parent, []).append(name)
180
+ for info in infos:
181
+ layout[info.rust_path] = files[info.path].rust
182
+ for parent, kids in children.items():
183
+ decls = "".join(f"pub mod {mangle(k.rpartition('.')[2])};\n" for k in kids)
184
+ if parent == "":
185
+ layout["lib.rs"] = "// Generated by python2rust: the crate root.\n" + decls
186
+ else:
187
+ path = _rust_path(parent, True)
188
+ body = layout.get(path, f"// Generated by python2rust: package {parent}.\n")
189
+ layout[path] = body.rstrip("\n") + "\n\n" + decls
190
+ return layout
191
+
192
+
193
+ def translate_project(
194
+ root: str | Path,
195
+ files: Sequence[str | Path] | None = None,
196
+ config: Config | None = None,
197
+ ) -> ProjectResult:
198
+ """Translate the Python modules under `root` (all `*.py` by default, or `files`/globs)."""
199
+ cfg = config or Config()
200
+ base = Path(root).resolve()
201
+ paths = _collect(base, files)
202
+ modules: dict[str, tuple[Path, str, bool]] = {} # name -> (path, relative posix, is_package)
203
+ for p in paths:
204
+ rel = p.resolve().relative_to(base)
205
+ name, package = _module_name(rel)
206
+ if name:
207
+ modules[name] = (p, rel.as_posix(), package)
208
+ names = set(modules)
209
+ packages = {n for n, (_, _, pkg) in modules.items() if pkg}
210
+ for n in list(names): # parent packages without an __init__.py still exist as Rust modules
211
+ parent = n.rpartition(".")[0]
212
+ while parent:
213
+ names.add(parent)
214
+ parent = parent.rpartition(".")[0]
215
+ index = ProjectIndex(names=names, packages=packages)
216
+ sources: dict[str, str] = {}
217
+ edges: dict[str, set[str]] = {n: set() for n in modules}
218
+ external: dict[str, set[str]] = {}
219
+ for name, (path, _rel, package) in modules.items():
220
+ text = path.read_text(encoding="utf-8", errors="replace")
221
+ sources[name] = text
222
+ try:
223
+ tree = ast.parse(text, filename=str(path))
224
+ except SyntaxError, ValueError, RecursionError, MemoryError:
225
+ external[name] = set()
226
+ continue
227
+ inside, outside = _imports(tree, name, package, index)
228
+ edges[name] = {m for m in inside if m in modules}
229
+ external[name] = outside
230
+ order, cycles = _order(sorted(modules), edges)
231
+ diagnostics = [
232
+ Diagnostic(
233
+ "PY2RS054", "warning", f"import cycle: {' -> '.join([*comp, comp[0]])}",
234
+ modules[comp[0]][1], 1, 0, "cycle", "move shared definitions into a third module",
235
+ )
236
+ for comp in cycles
237
+ ] # fmt: skip
238
+ cyclic = {m for comp in cycles for m in comp}
239
+ for tree_name in modules:
240
+ index.catchable |= collect_catchable(ast.parse(sources[tree_name]))
241
+ results: dict[str, TranslateResult] = {}
242
+ for name in order:
243
+ path, rel, package = modules[name]
244
+ results[name] = translate_source(
245
+ sources[name], rel, cfg, project=ProjectContext(index, name, package)
246
+ )
247
+ infos = [
248
+ ModuleInfo(
249
+ name, modules[name][1], index.rust_path(name), _rust_path(name, modules[name][2]),
250
+ modules[name][2], tuple(sorted(edges[name])), tuple(sorted(external[name])), name in cyclic,
251
+ )
252
+ for name in order
253
+ ] # fmt: skip
254
+ by_path = {modules[n][1]: results[n] for n in order}
255
+ layout = _layout(infos, by_path, names, packages)
256
+ stats: dict[str, int] = {}
257
+ for r in results.values():
258
+ for k, v in r.stats.items():
259
+ stats[k] = stats.get(k, 0) + v
260
+ stats.update(
261
+ modules=len(modules), edges=sum(len(e) for e in edges.values()), cycles=len(cycles)
262
+ )
263
+ stats["modules_clean"] = sum(1 for r in results.values() if r.stats["todo_count"] == 0)
264
+ crates: dict[str, CrateSpec] = {}
265
+ for r in results.values():
266
+ for crate, spec in r.required_crates.items():
267
+ merged = crates.setdefault(crate, {"version": spec["version"], "features": []})
268
+ merged["features"] = sorted({*merged["features"], *spec["features"]})
269
+ features = tuple(sorted({f for r in results.values() for f in r.required_features}))
270
+ if "python2rust-rt" in crates:
271
+ crates["python2rust-rt"]["features"] = list(features)
272
+ glue_crates = required_crates("".join(layout.values()), set(features)) # lib.rs/mod.rs add none
273
+ crates = {**glue_crates, **crates}
274
+ return ProjectResult(
275
+ by_path, tuple(infos), layout, tuple(diagnostics), stats, tuple(sorted(crates)), features,
276
+ dict(sorted(crates.items())),
277
+ ) # fmt: skip
@@ -0,0 +1,173 @@
1
+ """Imports that resolve inside the project: bring symbols into the module's tables and `use` them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import dataclasses
7
+
8
+ from ..ir import nodes as ir
9
+ from ..ir.rtypes import RType
10
+ from ..lower.context import Ctx
11
+ from ..lower.funcs import todo_item
12
+ from .names import const_name, fn_name
13
+ from .symbols import ModuleSymbols, Symbol
14
+
15
+
16
+ def _type_names(ty: RType) -> set[str]:
17
+ return {ty.name} | {n for a in ty.args for n in _type_names(a)}
18
+
19
+
20
+ def _signature_types(sym: Symbol) -> set[str]:
21
+ """Rust type names mentioned by an imported symbol (so the importer can `use` them too)."""
22
+ obj = sym.obj
23
+ out: set[str] = set()
24
+ if sym.kind == "func":
25
+ out |= _type_names(obj.ret)
26
+ for p in obj.params:
27
+ out |= _type_names(p.ty)
28
+ elif sym.kind == "model":
29
+ out |= {obj.rust}
30
+ for f in obj.fields.values():
31
+ out |= _type_names(f.ty)
32
+ if obj.newtype is not None:
33
+ out |= _type_names(obj.newtype)
34
+ elif sym.kind == "enum":
35
+ out.add(obj.rust)
36
+ elif sym.kind in ("alias", "const"):
37
+ out |= _type_names(obj if sym.kind == "alias" else obj.ty)
38
+ return out
39
+
40
+
41
+ def _use(ctx: Ctx, module: str, rust_name: str, alias: str | None = None) -> None:
42
+ proj = ctx.project
43
+ assert proj is not None
44
+ path = f"{proj.index.rust_path(module)}::{rust_name}"
45
+ line = f"{'pub ' if proj.is_package else ''}use {path}{f' as {alias}' if alias else ''};"
46
+ if line not in ctx.uses:
47
+ ctx.uses.append(line)
48
+
49
+
50
+ def use_defaults(ctx: Ctx, sym: Symbol) -> None:
51
+ """A struct literal built here may call the `default_*` helpers of the model's home module."""
52
+ for f in sym.obj.fields.values():
53
+ d = f.default
54
+ if (
55
+ isinstance(d, ir.Call)
56
+ and isinstance(d.func, ir.Path)
57
+ and d.func.path.startswith("default_")
58
+ ):
59
+ _use(ctx, sym.module, d.func.path)
60
+
61
+
62
+ def _merge_enums(ctx: Ctx, home: ModuleSymbols) -> None:
63
+ ctx.lit_enums.update(home.lit_enums)
64
+ ctx.unions.update(home.unions)
65
+
66
+
67
+ def bring_in(ctx: Ctx, sym: Symbol, local: str) -> None:
68
+ """Make `sym` visible in this module under `local` (tables + a `use`)."""
69
+ proj = ctx.project
70
+ assert proj is not None
71
+ home = proj.index.modules.get(sym.module)
72
+ obj = sym.obj
73
+ ctx.imported_names.add(local)
74
+ ctx.reexports[local] = (sym.module, sym.name)
75
+ if sym.kind == "module":
76
+ ctx.module_aliases[local] = sym.module
77
+ last = sym.module.split(".")[-1]
78
+ parent = sym.module.rpartition(".")[0]
79
+ _use(ctx, parent, fn_name(last), None if local == last else local) if parent else None
80
+ return
81
+ assert home is not None
82
+ if sym.kind == "func":
83
+ rust = fn_name(local) if local != sym.name else obj.rust
84
+ ctx.sigs[local] = dataclasses.replace(obj, rust=rust)
85
+ _use(ctx, sym.module, obj.rust, None if rust == obj.rust else rust)
86
+ elif sym.kind == "model":
87
+ ctx.models[local] = obj
88
+ use_defaults(ctx, sym)
89
+ elif sym.kind == "enum":
90
+ ctx.enums[local] = obj
91
+ elif sym.kind == "const":
92
+ ctx.consts[local] = obj
93
+ _use(ctx, sym.module, obj.accessor or const_name(sym.name))
94
+ elif sym.kind == "exception":
95
+ ctx.exceptions[local] = obj
96
+ _use(ctx, sym.module, const_name(sym.name))
97
+ elif sym.kind == "alias":
98
+ ctx.aliases[local] = obj
99
+ if sym.name in home.alias_meta:
100
+ ctx.alias_meta[local] = home.alias_meta[sym.name]
101
+ for ty in sorted(_signature_types(sym) & home.types): # types the signature mentions
102
+ _use(ctx, sym.module, ty)
103
+ _merge_enums(ctx, home)
104
+
105
+
106
+ def unresolved(ctx: Ctx, node: ast.AST, what: str) -> ir.Item:
107
+ module = what.split(" ")[0]
108
+ ctx.unresolved[module] = ctx.unresolved.get(module, 0) + 1
109
+ return todo_item(ctx, "PY2RS055", node, f"import {what}", "import")
110
+
111
+
112
+ def note_dependency(ctx: Ctx, module: str) -> None:
113
+ """Python runs the import-time code of a module (and its parent packages) when it is imported."""
114
+ assert ctx.project is not None
115
+ parts = module.split(".")
116
+ for i in range(1, len(parts) + 1):
117
+ prefix = ".".join(parts[:i])
118
+ if prefix in ctx.project.index.names and prefix not in ctx.init_deps:
119
+ ctx.init_deps.append(prefix)
120
+
121
+
122
+ def project_import(
123
+ ctx: Ctx, node: ast.Import | ast.ImportFrom, alias: ast.alias
124
+ ) -> list[ir.Item] | None:
125
+ """Items for one imported name, or None when it is not a project import."""
126
+ proj = ctx.project
127
+ if proj is None:
128
+ return None
129
+ index = proj.index
130
+ if isinstance(node, ast.ImportFrom):
131
+ module = proj.absolute(node.module, node.level)
132
+ if module is None:
133
+ return [
134
+ unresolved(
135
+ ctx, node, f"{'.' * node.level}{node.module or ''} (beyond the project root)"
136
+ )
137
+ ]
138
+ if module in index.names:
139
+ note_dependency(ctx, module)
140
+ if module not in index.names:
141
+ if node.level == 0 and module.split(".")[0] not in index.roots:
142
+ return None
143
+ return [unresolved(ctx, node, f"{module} (module is not in the project)")]
144
+ if alias.name == "*":
145
+ return [unresolved(ctx, node, f"{module}.* (star imports are not resolved)")]
146
+ sym = index.lookup(module, alias.name)
147
+ if sym is None:
148
+ return [unresolved(ctx, node, f"{module}.{alias.name} (not defined by {module})")]
149
+ if sym.kind == "module": # `from app import tool` imports the module app.tool
150
+ note_dependency(ctx, f"{module}.{alias.name}")
151
+ bring_in(ctx, sym, alias.asname or alias.name)
152
+ return []
153
+ name = alias.name
154
+ if name not in index.names:
155
+ return (
156
+ None
157
+ if name.split(".")[0] not in index.roots
158
+ else [unresolved(ctx, node, f"{name} (module is not in the project)")]
159
+ )
160
+ note_dependency(ctx, name)
161
+ if alias.asname:
162
+ ctx.module_aliases[alias.asname] = name
163
+ ctx.imported_names.add(alias.asname)
164
+ path = f"{index.rust_path(name)}"
165
+ ctx.uses.append(f"use {path} as {alias.asname};")
166
+ return []
167
+ root = name.split(".")[0] # `import a.b.c` binds `a`
168
+ ctx.module_aliases[root] = root
169
+ ctx.imported_names.add(root)
170
+ line = f"use {index.rust_path(root)};"
171
+ if line not in ctx.uses:
172
+ ctx.uses.append(line)
173
+ return []