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.
- python2rust/__init__.py +8 -0
- python2rust/__main__.py +5 -0
- python2rust/_core.py +44 -0
- python2rust/agent/__init__.py +0 -0
- python2rust/agent/agents.py +333 -0
- python2rust/agent/apply.py +516 -0
- python2rust/agent/finish.py +295 -0
- python2rust/agent/fixers.py +229 -0
- python2rust/agent/loop.py +441 -0
- python2rust/agent/patches.py +1165 -0
- python2rust/agent/port.py +579 -0
- python2rust/agent/prompts/judge_v2.md +96 -0
- python2rust/agent/review.py +34 -0
- python2rust/agent/rustlex.py +232 -0
- python2rust/cli/__init__.py +0 -0
- python2rust/cli/doctor.py +62 -0
- python2rust/cli/inputs.py +105 -0
- python2rust/cli/main.py +1162 -0
- python2rust/cli/ops.py +642 -0
- python2rust/cli/workflow.py +178 -0
- python2rust/core/__init__.py +38 -0
- python2rust/core/config.py +263 -0
- python2rust/core/constructs.py +124 -0
- python2rust/core/diagnostics.py +280 -0
- python2rust/core/emit/__init__.py +5 -0
- python2rust/core/emit/crates.py +51 -0
- python2rust/core/emit/render.py +561 -0
- python2rust/core/emit/schema.py +168 -0
- python2rust/core/emit/translate.py +304 -0
- python2rust/core/frontend/__init__.py +1 -0
- python2rust/core/frontend/module.py +896 -0
- python2rust/core/frontend/names.py +129 -0
- python2rust/core/frontend/project.py +277 -0
- python2rust/core/frontend/project_imports.py +173 -0
- python2rust/core/frontend/symbols.py +132 -0
- python2rust/core/frontend/walrus.py +59 -0
- python2rust/core/ir/__init__.py +1 -0
- python2rust/core/ir/nodes.py +675 -0
- python2rust/core/ir/rtypes.py +122 -0
- python2rust/core/ir/types.py +326 -0
- python2rust/core/lower/__init__.py +1 -0
- python2rust/core/lower/calls.py +1125 -0
- python2rust/core/lower/context.py +223 -0
- python2rust/core/lower/exceptions.py +317 -0
- python2rust/core/lower/exprs.py +845 -0
- python2rust/core/lower/fstrings.py +141 -0
- python2rust/core/lower/funcs.py +276 -0
- python2rust/core/lower/lowerer.py +366 -0
- python2rust/core/lower/modelcalls.py +195 -0
- python2rust/core/lower/models.py +645 -0
- python2rust/core/lower/stmts.py +722 -0
- python2rust/core/lower/testing.py +601 -0
- python2rust/core/lower/validation.py +253 -0
- python2rust/core/passes/__init__.py +1 -0
- python2rust/core/passes/aliasing.py +311 -0
- python2rust/core/passes/analysis.py +207 -0
- python2rust/core/passes/devirt.py +329 -0
- python2rust/core/passes/ownership.py +259 -0
- python2rust/core/passes/raises.py +275 -0
- python2rust/core/rt_lib.rs +2071 -0
- python2rust/data/README.md +81 -0
- python2rust/data/py2many_builtins.toml +4744 -0
- python2rust/errors.py +28 -0
- python2rust/py.typed +0 -0
- python2rust/report/__init__.py +0 -0
- python2rust/report/constructs.py +31 -0
- python2rust/report/contract.py +688 -0
- python2rust/report/corpus.py +323 -0
- python2rust/report/explain.py +168 -0
- python2rust/report/schemas.py +914 -0
- python2rust/server/__init__.py +0 -0
- python2rust/server/mcp_server.py +289 -0
- python2rust/server/mcp_workflow.py +100 -0
- python2rust/skill/SKILL.md +214 -0
- python2rust/verify/__init__.py +0 -0
- python2rust/verify/check.py +1135 -0
- python2rust/verify/equiv/__init__.py +1264 -0
- python2rust/verify/equiv/compare.py +455 -0
- python2rust/verify/equiv/harness.py +505 -0
- python2rust/verify/equiv/judge.py +358 -0
- python2rust/verify/equiv/procs.py +255 -0
- python2rust/verify/equiv/runner.py +248 -0
- python2rust/verify/equiv/types.py +543 -0
- python2rust/verify/keystore.py +76 -0
- python2rust/verify/ladder.py +396 -0
- python2rust/verify/sandbox.py +370 -0
- python2rust/verify/testrun.py +280 -0
- python2rust/workflow/__init__.py +0 -0
- python2rust/workflow/brief.py +312 -0
- python2rust/workflow/interview.py +366 -0
- python2rust/workflow/layout.py +103 -0
- python2rust/workflow/planner.py +409 -0
- python2rust/workflow/project.py +134 -0
- python2rust/workflow/schemas.py +265 -0
- python2rust/workflow/state.py +392 -0
- python2rust/workflow/staticscan.py +209 -0
- python2rust-0.1.0.dist-info/METADATA +395 -0
- python2rust-0.1.0.dist-info/RECORD +102 -0
- python2rust-0.1.0.dist-info/WHEEL +4 -0
- python2rust-0.1.0.dist-info/entry_points.txt +4 -0
- python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
- python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
"""The interview behind `python2rust init`: the questions, answer validation, and the project TOML.
|
|
2
|
+
|
|
3
|
+
The agent asks the human; this module only describes the questions (`questions_doc`), checks the
|
|
4
|
+
answers (`resolve`) and turns them into `python2rust.toml` (`render_toml`). Nothing here is interactive.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from python2rust.agent.agents import BACKENDS
|
|
14
|
+
from python2rust.errors import UsageError
|
|
15
|
+
|
|
16
|
+
Option = tuple[str, str, str] # (value, label, consequence)
|
|
17
|
+
|
|
18
|
+
_REVIEW_AREAS: dict[str, tuple[str, list[str]]] = {
|
|
19
|
+
"auth": ("authentication and authorisation", [r"\b(jwt|oauth|bcrypt|passlib|login|password|api_key)\b"]),
|
|
20
|
+
"crypto": ("cryptography and secrets", [r"\b(hashlib|hmac|secrets|cryptography|ssl)\b"]),
|
|
21
|
+
"sql-writes": ("SQL that writes", [r"\b(INSERT|UPDATE|DELETE|DROP)\b.*\b(INTO|SET|FROM|TABLE)\b"]),
|
|
22
|
+
"network": ("network calls", [r"\b(socket|requests|httpx|urllib|aiohttp|smtplib)\b"]),
|
|
23
|
+
"subprocess": ("subprocesses and shell", [r"\b(subprocess|os\.system|os\.popen)\b"]),
|
|
24
|
+
"file-writes": ("file writes and deletes", [r"\.(write_text|write_bytes|unlink|rmtree)\(", r"\bopen\([^)]*['\"][wax]"]),
|
|
25
|
+
} # fmt: skip
|
|
26
|
+
REVIEW_AREAS = tuple(_REVIEW_AREAS)
|
|
27
|
+
|
|
28
|
+
_YES_NO: list[Option] = [
|
|
29
|
+
("yes", "yes", "allowed"),
|
|
30
|
+
("no", "no", "not allowed"),
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _q(
|
|
35
|
+
id: str, question: str, why: str, options: list[Option], default: Any, ask_human: bool,
|
|
36
|
+
*, kind: str = "choice", only_if: dict[str, list[str]] | None = None, pattern: str | None = None,
|
|
37
|
+
) -> dict[str, Any]: # fmt: skip
|
|
38
|
+
return {
|
|
39
|
+
"id": id,
|
|
40
|
+
"question": question,
|
|
41
|
+
"why_it_matters": why,
|
|
42
|
+
"kind": kind,
|
|
43
|
+
"options": [{"value": v, "label": lab, "consequence": c} for v, lab, c in options],
|
|
44
|
+
"default": default,
|
|
45
|
+
"ask_human": ask_human,
|
|
46
|
+
"only_if": only_if,
|
|
47
|
+
"pattern": pattern,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_ON_BACKEND = {"backend": ["cmd", "anthropic", "openai", "azure"]}
|
|
52
|
+
|
|
53
|
+
QUESTIONS: list[dict[str, Any]] = [
|
|
54
|
+
_q("goal", "What is the goal of this port?",
|
|
55
|
+
"It decides how much of the code is ported and how strict the checks are.",
|
|
56
|
+
[("full-port", "retire the Python: port everything in scope", "every unit is ported and verified; Python is deleted last"),
|
|
57
|
+
("hot-path", "hot paths or a library: port a few modules, keep the rest", "only the units you scope are ported; the rest stays Python behind a bridge"),
|
|
58
|
+
("service", "rewrite a service", "ports behaviour at the service boundary; HTTP and async choices matter most"),
|
|
59
|
+
("prototype", "learn or prototype", "fast and approximate; stops at drafts, nothing is claimed verified")],
|
|
60
|
+
"full-port", True),
|
|
61
|
+
_q("scope", "Which paths or modules should be ported?",
|
|
62
|
+
"Only these are planned. Everything else is left alone.",
|
|
63
|
+
[(".", "the whole project", "all modules found below the project root"),
|
|
64
|
+
("src", "the src directory", "only modules below src/")],
|
|
65
|
+
["."], True, kind="list"),
|
|
66
|
+
_q("keep_python", "Which paths or modules must stay Python?",
|
|
67
|
+
"Units that import them need a bridge or a port of the same API; the plan flags them.",
|
|
68
|
+
[("", "nothing", "everything in scope is ported")],
|
|
69
|
+
[], False, kind="list"),
|
|
70
|
+
_q("equivalence", "How equal must the Rust output be to the Python output?",
|
|
71
|
+
"It sets the comparison used by `verify --level equiv`.",
|
|
72
|
+
[("strict", "strict: byte for byte", "no normalisation; ordering, float text and error text must match"),
|
|
73
|
+
("functional", "functional: same meaning", "canonical JSON, float tolerance and the [equivalence] rules in python2rust.toml"),
|
|
74
|
+
("functional-judge", "functional, plus an AI judge for the leftovers", "outputs the rules cannot settle go to a model; needs a backend; judged passes are queued for review")],
|
|
75
|
+
"functional", True),
|
|
76
|
+
_q("float_tolerance", "How close must two floats be to count as equal?",
|
|
77
|
+
"Floats are compared exactly unless you choose a relative tolerance; a tolerance can hide a real "
|
|
78
|
+
"rounding difference, so pick one only for a reason.",
|
|
79
|
+
[("exact", "exact: identical floats only", "no tolerance; the default"),
|
|
80
|
+
("1e-9", "relative 1e-9", "tiny rounding differences count as equal"),
|
|
81
|
+
("1e-6", "relative 1e-6", "looser; summation order may differ")],
|
|
82
|
+
"exact", False, kind="text", only_if={"equivalence": ["functional", "functional-judge"]},
|
|
83
|
+
pattern=r"exact|\d+(\.\d+)?([eE][-+]?\d+)?"),
|
|
84
|
+
_q("oracles", "Where do trusted examples of correct behaviour come from?",
|
|
85
|
+
"Equivalence is only as good as its inputs. Passing ported tests alone proves little.",
|
|
86
|
+
[("existing-tests", "the project's tests", "asserts in test files seed the cases"),
|
|
87
|
+
("doctests", "doctests", "docstring examples seed the cases"),
|
|
88
|
+
("generated-cases", "generated inputs", "edge and random values from the type annotations"),
|
|
89
|
+
("recorded-captures", "recorded real inputs", "you provide captures; replay them through both sides"),
|
|
90
|
+
("openapi-contract", "an OpenAPI contract", "diffed against the Rust service with `python2rust contract`")],
|
|
91
|
+
["existing-tests", "doctests", "generated-cases"], True, kind="multi"),
|
|
92
|
+
_q("run_python", "May python2rust run your Python code to compare outputs?",
|
|
93
|
+
"Equivalence testing executes your modules (top-level code included) in a child process with best-effort limits. "
|
|
94
|
+
"Even with `yes`, nothing runs unless the command itself carries `--run-python`.",
|
|
95
|
+
[("yes", "yes, I trust this code", "the briefs show `done UNIT --run-python`; only a run with that flag executes your code"),
|
|
96
|
+
("no", "no, never run it", "nothing is executed; `done` records the unit at the tier that ran and says equivalence was not verified")],
|
|
97
|
+
"no", True),
|
|
98
|
+
_q("backend", "May code be sent to a model, and which one?",
|
|
99
|
+
"Nothing leaves this machine unless you choose a backend. It receives function source and compiler output.",
|
|
100
|
+
[("none", "no model: dry run", "tasks are printed for the calling agent; nothing is sent"),
|
|
101
|
+
("cmd", "a command you run (for example `claude -p`)", "task JSON goes to that command"),
|
|
102
|
+
("anthropic", "Anthropic API", "function source and errors are sent to Anthropic"),
|
|
103
|
+
("openai", "OpenAI-compatible API", "function source and errors are sent to that endpoint"),
|
|
104
|
+
("azure", "Azure OpenAI deployment", "function source and errors are sent to that deployment")],
|
|
105
|
+
"none", True),
|
|
106
|
+
_q("agent_cmd", "Which command is the model backend?",
|
|
107
|
+
"It is run on this machine with the task JSON on stdin.",
|
|
108
|
+
[("claude -p", "claude -p", "uses the local Claude CLI")],
|
|
109
|
+
"claude -p", True, kind="text", only_if={"backend": ["cmd"]}),
|
|
110
|
+
_q("model", "Which model name?", "Empty means the backend's default.",
|
|
111
|
+
[("", "backend default", "no model name is passed")],
|
|
112
|
+
"", False, kind="text", only_if={"backend": ["anthropic", "openai", "azure"]}),
|
|
113
|
+
_q("budget_tokens", "Token budget for model calls (0 = no cap)?",
|
|
114
|
+
"The repair loop stops when it is spent.",
|
|
115
|
+
[("500000", "500000", "a few modules"), ("0", "no cap", "can get expensive")],
|
|
116
|
+
500000, True, kind="int", only_if=_ON_BACKEND),
|
|
117
|
+
_q("budget_seconds", "Time budget in seconds for the repair loop (0 = no cap)?",
|
|
118
|
+
"Bounds wall-clock time per `port` run.",
|
|
119
|
+
[("3600", "3600", "one hour"), ("0", "no cap", "runs until done or out of tokens")],
|
|
120
|
+
3600, True, kind="int", only_if=_ON_BACKEND),
|
|
121
|
+
_q("crate_name", "What is the Rust crate called?",
|
|
122
|
+
"Used for Cargo.toml and the output directory rust/<name>.",
|
|
123
|
+
[("ported", "ported", "generic placeholder")],
|
|
124
|
+
"ported", False, kind="text", pattern=r"^[a-z][a-z0-9_-]*$"),
|
|
125
|
+
_q("crate_layout", "How should the crates be laid out?",
|
|
126
|
+
"Decides where lib.rs and main.rs go.",
|
|
127
|
+
[("lib", "one library crate", "everything below one lib.rs"),
|
|
128
|
+
("lib-bin", "library plus a binary", "adds a thin main.rs"),
|
|
129
|
+
("workspace", "a workspace of crates", "one crate per top-level package")],
|
|
130
|
+
"lib", False),
|
|
131
|
+
_q("error_style", "How should Python exceptions become Rust errors?",
|
|
132
|
+
"It shapes every fallible signature.",
|
|
133
|
+
[("crate-enum", "one error enum for the crate", "simple signatures; one place to add variants"),
|
|
134
|
+
("per-module", "one error type per module", "tight types; more conversions")],
|
|
135
|
+
"crate-enum", False),
|
|
136
|
+
_q("int_overflow", "What happens when integer arithmetic overflows?",
|
|
137
|
+
"Python ints never overflow; Rust ints do. Equivalence reports the difference.",
|
|
138
|
+
[("checked", "checked: overflow is an error", "closest to Python for failures, small cost"),
|
|
139
|
+
("wrapping", "wrapping: wrap around", "fast; silently differs from Python"),
|
|
140
|
+
("native", "native: plain operators", "panics in debug, wraps in release")],
|
|
141
|
+
"checked", False),
|
|
142
|
+
_q("ordering", "How should dicts and sets be ordered?",
|
|
143
|
+
"Python dicts keep insertion order. Output order matters for strict equivalence.",
|
|
144
|
+
[("insertion", "insertion-ordered maps and sets (IndexMap, IndexSet)", "matches Python dicts; one extra crate"),
|
|
145
|
+
("maps-ordered", "ordered maps, unordered sets", "IndexMap plus HashSet; set output order is not stable"),
|
|
146
|
+
("hash", "std HashMap and HashSet", "fastest; iteration order differs from Python")],
|
|
147
|
+
"insertion", False),
|
|
148
|
+
_q("async_http", "Which async and HTTP stack?",
|
|
149
|
+
"Only matters for code with async functions or HTTP.",
|
|
150
|
+
[("tokio-axum-reqwest", "tokio + axum + reqwest", "the common async stack"),
|
|
151
|
+
("sync", "synchronous, no runtime", "async functions become blocking calls"),
|
|
152
|
+
("todo", "leave it as TODO", "async and HTTP code stays a todo!() for a human")],
|
|
153
|
+
"tokio-axum-reqwest", False),
|
|
154
|
+
_q("review_areas", "Which areas must a human review before they count as done?",
|
|
155
|
+
"Flagged todos are never closed by an agent alone.",
|
|
156
|
+
[(a, label, "needs_review, queued for a human") for a, (label, _) in _REVIEW_AREAS.items()],
|
|
157
|
+
list(REVIEW_AREAS), True, kind="multi"),
|
|
158
|
+
_q("commit_policy", "When should the agent commit?",
|
|
159
|
+
"Controls how reviewable the history is.",
|
|
160
|
+
[("unit", "one commit per unit", "easy to review and revert"),
|
|
161
|
+
("file", "one commit per file", "finer history, more commits"),
|
|
162
|
+
("none", "never commit", "you commit yourself")],
|
|
163
|
+
"unit", False),
|
|
164
|
+
_q("output_tier", "How far must each unit be finished?",
|
|
165
|
+
"It decides which ladder rungs `done` requires.",
|
|
166
|
+
[("draft", "draft: compiles", "cargo check, no todo!() left"),
|
|
167
|
+
("verified", "verified: compiles and gives the same output", "adds the equivalence rung when you allowed running Python and `done` gets --run-python"),
|
|
168
|
+
("production", "production: verified, clippy clean, tests pass", "adds clippy and cargo test")],
|
|
169
|
+
"verified", True),
|
|
170
|
+
] # fmt: skip
|
|
171
|
+
|
|
172
|
+
BY_ID = {q["id"]: q for q in QUESTIONS}
|
|
173
|
+
_SPLIT = re.compile(r"\s*,\s*")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def questions_doc() -> dict[str, Any]:
|
|
177
|
+
from python2rust.cli.ops import envelope
|
|
178
|
+
|
|
179
|
+
return envelope(
|
|
180
|
+
"init",
|
|
181
|
+
mode="questions",
|
|
182
|
+
ok=True,
|
|
183
|
+
instructions=(
|
|
184
|
+
"Ask the human every question in ONE message: show each question, its options with "
|
|
185
|
+
"their consequences, and the default. Questions with ask_human=true must be answered "
|
|
186
|
+
"by the human; never answer them yourself. For the others, show the default and let "
|
|
187
|
+
"the human override it. Then run `python2rust init --answers FILE.json` "
|
|
188
|
+
"(or repeated `--answer id=value`). Skip questions whose only_if does not hold."
|
|
189
|
+
),
|
|
190
|
+
questions=QUESTIONS,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# --- validation ---------------------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _fail(qid: str, value: Any, expected: str) -> UsageError:
|
|
198
|
+
return UsageError(f"invalid answer for {qid!r}: {value!r}; {expected}")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _as_list(qid: str, value: Any) -> list[str]:
|
|
202
|
+
if isinstance(value, str):
|
|
203
|
+
value = [v for v in _SPLIT.split(value.strip()) if v] if value.strip() else []
|
|
204
|
+
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
|
205
|
+
raise _fail(qid, value, "expected a list of strings (or a comma-separated string)")
|
|
206
|
+
return value
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def check_answer(q: dict[str, Any], value: Any) -> Any:
|
|
210
|
+
"""The normalised answer, or a UsageError naming the question id and the allowed values."""
|
|
211
|
+
qid, kind = q["id"], q["kind"]
|
|
212
|
+
allowed = [o["value"] for o in q["options"]]
|
|
213
|
+
if kind == "choice":
|
|
214
|
+
if not isinstance(value, str) or value not in allowed:
|
|
215
|
+
raise _fail(qid, value, f"allowed values: {', '.join(allowed)}")
|
|
216
|
+
return value
|
|
217
|
+
if kind == "multi":
|
|
218
|
+
items = _as_list(qid, value)
|
|
219
|
+
bad = [v for v in items if v not in allowed]
|
|
220
|
+
if bad:
|
|
221
|
+
raise _fail(qid, bad[0], f"allowed values: {', '.join(allowed)} (a list of these)")
|
|
222
|
+
return sorted(set(items), key=allowed.index)
|
|
223
|
+
if kind == "list":
|
|
224
|
+
return _as_list(qid, value)
|
|
225
|
+
if kind == "int":
|
|
226
|
+
if isinstance(value, str) and value.strip().isdigit():
|
|
227
|
+
value = int(value)
|
|
228
|
+
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
|
229
|
+
raise _fail(qid, value, "expected a non-negative integer")
|
|
230
|
+
return value
|
|
231
|
+
if not isinstance(value, str) or (q["default"] and not value.strip()):
|
|
232
|
+
raise _fail(qid, value, "expected a non-empty string")
|
|
233
|
+
if q["pattern"] and not re.fullmatch(q["pattern"], value):
|
|
234
|
+
raise _fail(qid, value, f"must match {q['pattern']}")
|
|
235
|
+
if qid == "float_tolerance" and value.strip() != "exact" and not 0 <= float(value) < 1:
|
|
236
|
+
raise _fail(qid, value, "a tolerance must be 0 <= x < 1 (or `exact`)")
|
|
237
|
+
return value.strip()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def applies(q: dict[str, Any], values: dict[str, Any]) -> bool:
|
|
241
|
+
cond = q["only_if"]
|
|
242
|
+
return not cond or all(values.get(k) in allowed for k, allowed in cond.items())
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def parse_pairs(pairs: list[str]) -> dict[str, Any]:
|
|
246
|
+
out: dict[str, Any] = {}
|
|
247
|
+
for pair in pairs:
|
|
248
|
+
key, sep, value = pair.partition("=")
|
|
249
|
+
if not sep or not key:
|
|
250
|
+
raise UsageError(f"--answer expects id=value, got {pair!r}")
|
|
251
|
+
out[key.strip()] = value
|
|
252
|
+
return out
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def resolve(given: dict[str, Any], *, defaults: bool) -> tuple[dict[str, Any], dict[str, str]]:
|
|
256
|
+
"""Validate `given` against the questions; returns (answers, source per id).
|
|
257
|
+
|
|
258
|
+
A source is `answer`, `default` (taken) or `skipped` (the question's only_if did not hold).
|
|
259
|
+
A missing ask_human answer is an error unless `defaults` is set.
|
|
260
|
+
"""
|
|
261
|
+
unknown = sorted(set(given) - set(BY_ID))
|
|
262
|
+
if unknown:
|
|
263
|
+
raise UsageError(
|
|
264
|
+
f"unknown question id {unknown[0]!r}; known ids: {', '.join(q['id'] for q in QUESTIONS)}"
|
|
265
|
+
)
|
|
266
|
+
values: dict[str, Any] = {}
|
|
267
|
+
sources: dict[str, str] = {}
|
|
268
|
+
missing: list[str] = []
|
|
269
|
+
for q in QUESTIONS:
|
|
270
|
+
qid = q["id"]
|
|
271
|
+
if qid in given:
|
|
272
|
+
values[qid], sources[qid] = check_answer(q, given[qid]), "answer"
|
|
273
|
+
elif not applies(q, values):
|
|
274
|
+
values[qid], sources[qid] = q["default"], "skipped"
|
|
275
|
+
else:
|
|
276
|
+
values[qid], sources[qid] = q["default"], "default"
|
|
277
|
+
if q["ask_human"] and not defaults:
|
|
278
|
+
missing.append(qid)
|
|
279
|
+
if missing:
|
|
280
|
+
raise UsageError(
|
|
281
|
+
f"unanswered question(s) that need a human decision: {', '.join(missing)}. Ask the human "
|
|
282
|
+
"(`python2rust init --questions --json`), or pass --defaults if they said to use the defaults"
|
|
283
|
+
)
|
|
284
|
+
if values["equivalence"] == "functional-judge" and values["backend"] == "none":
|
|
285
|
+
raise UsageError(
|
|
286
|
+
"invalid answers: equivalence 'functional-judge' needs a model backend, but backend is 'none'"
|
|
287
|
+
)
|
|
288
|
+
return values, sources
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def warnings_for(values: dict[str, Any]) -> list[str]:
|
|
292
|
+
out = []
|
|
293
|
+
if values["output_tier"] != "draft" and values["run_python"] == "no":
|
|
294
|
+
out.append(
|
|
295
|
+
f"output_tier {values['output_tier']!r} normally includes the equivalence rung, but "
|
|
296
|
+
"run_python is 'no': `done` will record that equivalence was NOT verified"
|
|
297
|
+
)
|
|
298
|
+
if values["goal"] == "prototype" and values["output_tier"] != "draft":
|
|
299
|
+
out.append(
|
|
300
|
+
"goal 'prototype' with a stricter output_tier than 'draft': check this is intended"
|
|
301
|
+
)
|
|
302
|
+
return out
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# --- python2rust.toml ---------------------------------------------------------------------------
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _toml(value: Any) -> str:
|
|
309
|
+
if isinstance(value, bool):
|
|
310
|
+
return "true" if value else "false"
|
|
311
|
+
if isinstance(value, list):
|
|
312
|
+
return "[" + ", ".join(_toml(v) for v in value) + "]"
|
|
313
|
+
return json.dumps(value) # strings and numbers: JSON escapes are valid TOML
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def review_patterns(areas: list[str]) -> list[str]:
|
|
317
|
+
return [p for a in areas for p in _REVIEW_AREAS[a][1]]
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def render_toml(v: dict[str, Any]) -> str:
|
|
321
|
+
strict = v["equivalence"] == "strict"
|
|
322
|
+
rel = 0.0 if strict or v["float_tolerance"] == "exact" else float(v["float_tolerance"])
|
|
323
|
+
tol = f"{{ rel = {rel!r}, abs = 0.0 }}"
|
|
324
|
+
lines = [
|
|
325
|
+
"# python2rust project config, written by `python2rust init`; pass it with --config.",
|
|
326
|
+
"# Core options first, then tables owned by the CLI ([patch_gate], [equivalence], [agent]).",
|
|
327
|
+
"format = true",
|
|
328
|
+
"vendor_runtime = false",
|
|
329
|
+
f"int_overflow = {_toml(v['int_overflow'])}",
|
|
330
|
+
f"set_type = {_toml('hashset' if v['ordering'] == 'hash' else 'indexset')}",
|
|
331
|
+
"review_patterns = [",
|
|
332
|
+
*(f" {_toml(p)}," for p in review_patterns(v["review_areas"])),
|
|
333
|
+
"]",
|
|
334
|
+
"",
|
|
335
|
+
"[patch_gate]",
|
|
336
|
+
"allow = [] # anti-cheat rules a human chose to relax; empty = full gate",
|
|
337
|
+
"",
|
|
338
|
+
"[equivalence]",
|
|
339
|
+
f"error_text_ignore = {_toml(not strict)}",
|
|
340
|
+
"# A difference caused by a Python int beyond i64 fails the function (the default). Only a",
|
|
341
|
+
'# human relaxes it: bigint = "report" lists such inputs instead of failing.',
|
|
342
|
+
'bigint = "fail"',
|
|
343
|
+
f"float_tolerance = {tol}",
|
|
344
|
+
"",
|
|
345
|
+
"[agent]",
|
|
346
|
+
f"backend = {_toml(v['backend'])}",
|
|
347
|
+
f"model = {_toml(v['model'])}",
|
|
348
|
+
f"cmd = {_toml(v['agent_cmd'] if v['backend'] == 'cmd' else '')}",
|
|
349
|
+
f"budget_tokens = {_toml(v['budget_tokens'])}",
|
|
350
|
+
f"budget_seconds = {_toml(v['budget_seconds'])}",
|
|
351
|
+
f"judge = {_toml(v['equivalence'] == 'functional-judge')}",
|
|
352
|
+
"",
|
|
353
|
+
]
|
|
354
|
+
return "\n".join(lines)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def agent_flags(v: dict[str, Any]) -> list[str]:
|
|
358
|
+
"""CLI flags selecting the chosen backend (empty for `none`: a dry run that sends nothing)."""
|
|
359
|
+
if v["backend"] not in BACKENDS or v["backend"] == "none":
|
|
360
|
+
return []
|
|
361
|
+
flags = ["--agent", v["backend"]]
|
|
362
|
+
if v["backend"] == "cmd":
|
|
363
|
+
flags += ["--agent-cmd", v["agent_cmd"]]
|
|
364
|
+
elif v["model"]:
|
|
365
|
+
flags += ["--model", v["model"]]
|
|
366
|
+
return flags
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Where a project's top-level packages live, so module names start at the package.
|
|
2
|
+
|
|
3
|
+
`src/shop/cart.py` is the module `shop.cart` however the scope was chosen (`.` or `src`). The source
|
|
4
|
+
roots come from `pyproject.toml` (setuptools, hatch, uv's build backend, poetry), else from the
|
|
5
|
+
src layout itself: `src/` holding a package. Anything outside a source root is named from the scope
|
|
6
|
+
directory, as in a flat layout.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
import tomllib
|
|
13
|
+
from pathlib import Path, PurePosixPath
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _norm(name: str) -> str:
|
|
18
|
+
return re.sub(r"[-_.]+", "_", name).lower()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _strings(value: Any) -> list[str]:
|
|
22
|
+
if isinstance(value, str):
|
|
23
|
+
return [value]
|
|
24
|
+
if isinstance(value, list):
|
|
25
|
+
return [v for v in value if isinstance(v, str)]
|
|
26
|
+
if isinstance(value, dict): # hatch `sources` may be {"src": ""}
|
|
27
|
+
return [k for k in value if isinstance(k, str)]
|
|
28
|
+
return []
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _get(doc: Any, *keys: str) -> Any:
|
|
32
|
+
for k in keys:
|
|
33
|
+
doc = doc.get(k) if isinstance(doc, dict) else None
|
|
34
|
+
return doc
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _parent(path: str) -> str:
|
|
38
|
+
return str(PurePosixPath(path).parent)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def declared_roots(doc: dict[str, Any]) -> list[str]:
|
|
42
|
+
"""Directories (relative to the project) that pyproject.toml says hold the top-level packages."""
|
|
43
|
+
out: list[str] = []
|
|
44
|
+
package_dir = _get(doc, "tool", "setuptools", "package-dir")
|
|
45
|
+
if isinstance(package_dir, dict):
|
|
46
|
+
for pkg, where in package_dir.items():
|
|
47
|
+
if not isinstance(where, str):
|
|
48
|
+
continue
|
|
49
|
+
if pkg == "":
|
|
50
|
+
out.append(where)
|
|
51
|
+
elif PurePosixPath(where).name == str(pkg).rpartition(".")[2]:
|
|
52
|
+
out.append(_parent(where)) # {"shop": "lib/shop"}: lib holds shop
|
|
53
|
+
out += _strings(_get(doc, "tool", "setuptools", "packages", "find", "where"))
|
|
54
|
+
for build in (
|
|
55
|
+
_get(doc, "tool", "hatch", "build"),
|
|
56
|
+
_get(doc, "tool", "hatch", "build", "targets", "wheel"),
|
|
57
|
+
):
|
|
58
|
+
out += [_parent(p) for p in _strings(_get(build, "packages"))]
|
|
59
|
+
out += _strings(_get(build, "sources"))
|
|
60
|
+
for pkg in _get(doc, "tool", "poetry", "packages") or []:
|
|
61
|
+
if isinstance(pkg, dict) and isinstance(pkg.get("from"), str):
|
|
62
|
+
out.append(pkg["from"])
|
|
63
|
+
uv = _get(doc, "tool", "uv", "build-backend")
|
|
64
|
+
if isinstance(uv, dict) or _get(doc, "build-system", "build-backend") == "uv_build":
|
|
65
|
+
out.append(str(uv.get("module-root", "src")) if isinstance(uv, dict) else "src")
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _package_names(doc: dict[str, Any]) -> list[str]:
|
|
70
|
+
names = _strings(_get(doc, "tool", "uv", "build-backend", "module-name"))
|
|
71
|
+
project = _get(doc, "project", "name")
|
|
72
|
+
return names + ([_norm(project)] if isinstance(project, str) else [])
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def source_roots(root: Path) -> tuple[list[Path], list[str]]:
|
|
76
|
+
"""(source root directories below `root`, deepest first; warnings). Never includes `root`."""
|
|
77
|
+
root = root.resolve()
|
|
78
|
+
warnings: list[str] = []
|
|
79
|
+
doc: dict[str, Any] = {}
|
|
80
|
+
pyproject = root / "pyproject.toml"
|
|
81
|
+
if pyproject.is_file():
|
|
82
|
+
try:
|
|
83
|
+
doc = tomllib.loads(pyproject.read_text(encoding="utf-8"))
|
|
84
|
+
except (OSError, ValueError) as exc:
|
|
85
|
+
warnings.append(f"pyproject.toml is unreadable ({exc}); using the directory layout")
|
|
86
|
+
found: list[Path] = []
|
|
87
|
+
for rel in declared_roots(doc):
|
|
88
|
+
d = (root / rel).resolve()
|
|
89
|
+
if d.is_dir() and d != root and d.is_relative_to(root) and d not in found:
|
|
90
|
+
found.append(d)
|
|
91
|
+
src = root / "src"
|
|
92
|
+
if not found and src.is_dir():
|
|
93
|
+
names = _package_names(doc)
|
|
94
|
+
if any((p / "__init__.py").is_file() for p in src.iterdir() if p.is_dir()) or any(
|
|
95
|
+
(src / n).is_dir() for n in names
|
|
96
|
+
):
|
|
97
|
+
found.append(src.resolve())
|
|
98
|
+
return sorted(found, key=lambda p: len(p.parts), reverse=True), warnings
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def base_for(file: Path, roots: list[Path], fallback: Path) -> Path:
|
|
102
|
+
"""The directory `file`'s module name is counted from: its source root, else `fallback`."""
|
|
103
|
+
return next((r for r in roots if file.is_relative_to(r)), fallback)
|