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,178 @@
|
|
|
1
|
+
"""CLI wiring for the workflow commands: init, plan, next, done, status."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from python2rust.cli.main import Outcome
|
|
10
|
+
from python2rust.errors import UsageError
|
|
11
|
+
from python2rust.workflow import interview
|
|
12
|
+
from python2rust.workflow import state as workflow
|
|
13
|
+
|
|
14
|
+
Add = Callable[[str, Callable[[argparse.Namespace], Outcome], str], argparse.ArgumentParser]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _project_opt(p: argparse.ArgumentParser) -> None:
|
|
18
|
+
p.add_argument("--project", default=".", metavar="DIR", help="project root (default: .)")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def register(add: Add, cargo_opts: Callable[[argparse.ArgumentParser], None]) -> None:
|
|
22
|
+
p = add(
|
|
23
|
+
"init", cmd_init, "the interview: print the questions, or apply answers (python2rust.toml)"
|
|
24
|
+
)
|
|
25
|
+
p.add_argument("--questions", action="store_true", help="print the questions as JSON")
|
|
26
|
+
p.add_argument(
|
|
27
|
+
"--answers", metavar="FILE", help="JSON object {question id: answer}; - for stdin"
|
|
28
|
+
)
|
|
29
|
+
p.add_argument(
|
|
30
|
+
"--answer", action="append", default=[], metavar="ID=VALUE", help="one answer (repeatable)"
|
|
31
|
+
)
|
|
32
|
+
p.add_argument(
|
|
33
|
+
"--defaults", action="store_true", help="take the default for every unanswered question"
|
|
34
|
+
)
|
|
35
|
+
p.add_argument(
|
|
36
|
+
"--force", action="store_true", help="replace an existing python2rust.toml and state"
|
|
37
|
+
)
|
|
38
|
+
_project_opt(p)
|
|
39
|
+
|
|
40
|
+
p = add("plan", cmd_plan, "units in dependency order, with size, tests, risks and difficulty")
|
|
41
|
+
p.add_argument(
|
|
42
|
+
"paths",
|
|
43
|
+
nargs="*",
|
|
44
|
+
metavar="SRC",
|
|
45
|
+
help="python files or directories (default: the scope answer)",
|
|
46
|
+
)
|
|
47
|
+
_project_opt(p)
|
|
48
|
+
|
|
49
|
+
p = add(
|
|
50
|
+
"next",
|
|
51
|
+
cmd_next,
|
|
52
|
+
"the next unit to port, as a self-contained brief (also refreshes PORTING.md)",
|
|
53
|
+
)
|
|
54
|
+
p.add_argument(
|
|
55
|
+
"--markdown", action="store_true", help="print the brief as markdown (the non-JSON default)"
|
|
56
|
+
)
|
|
57
|
+
_project_opt(p)
|
|
58
|
+
|
|
59
|
+
p = add("done", cmd_done, "record a unit as done if the rungs of the chosen output tier pass")
|
|
60
|
+
p.add_argument("unit", metavar="UNIT", help="a unit id from the plan")
|
|
61
|
+
p.add_argument(
|
|
62
|
+
"--reviewed",
|
|
63
|
+
action="store_true",
|
|
64
|
+
help="a human reviewed the queued items (never set it yourself)",
|
|
65
|
+
)
|
|
66
|
+
p.add_argument(
|
|
67
|
+
"--accept-not-clean",
|
|
68
|
+
action="store_true",
|
|
69
|
+
help="a human accepts items the translator counts not clean (a TODO, drift or behaviour it "
|
|
70
|
+
"does not enforce); recorded as a caveat (never set it yourself)",
|
|
71
|
+
)
|
|
72
|
+
p.add_argument(
|
|
73
|
+
"--run-python",
|
|
74
|
+
action="store_true",
|
|
75
|
+
help="allow EXECUTING the user's Python (sandboxed child process) for the equivalence rung; "
|
|
76
|
+
"without it that rung is not run and the unit is recorded at the tier that did run",
|
|
77
|
+
)
|
|
78
|
+
_project_opt(p)
|
|
79
|
+
cargo_opts(p)
|
|
80
|
+
|
|
81
|
+
p = add(
|
|
82
|
+
"status", cmd_status, "phase, current unit, blockers, the exact next command, review queue"
|
|
83
|
+
)
|
|
84
|
+
_project_opt(p)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def cmd_init(args: argparse.Namespace) -> Outcome:
|
|
88
|
+
given = bool(args.answers or args.answer or args.defaults)
|
|
89
|
+
if args.questions:
|
|
90
|
+
if given or args.force:
|
|
91
|
+
raise UsageError("--questions only prints the questions; give no answers with it")
|
|
92
|
+
doc = interview.questions_doc()
|
|
93
|
+
lines = []
|
|
94
|
+
for q in doc["questions"]:
|
|
95
|
+
lines.append(
|
|
96
|
+
f"{q['id']}{' [ask the human]' if q['ask_human'] else ''}: {q['question']}"
|
|
97
|
+
)
|
|
98
|
+
lines += [
|
|
99
|
+
f" {o['value'] or '(empty)'}: {o['label']} - {o['consequence']}"
|
|
100
|
+
for o in q["options"]
|
|
101
|
+
]
|
|
102
|
+
lines.append(f" default: {q['default']}")
|
|
103
|
+
return Outcome(doc, 0, "\n".join(lines) + "\n")
|
|
104
|
+
if not given:
|
|
105
|
+
raise UsageError(
|
|
106
|
+
"give --questions, or answers: --answers FILE, --answer id=value, --defaults"
|
|
107
|
+
)
|
|
108
|
+
answers: dict[str, Any] = workflow.load_answers_file(args.answers) if args.answers else {}
|
|
109
|
+
answers |= interview.parse_pairs(args.answer)
|
|
110
|
+
doc, code = workflow.init_apply(args.project, answers, defaults=args.defaults, force=args.force)
|
|
111
|
+
text = "wrote " + ", ".join(doc["files_written"]) + "\n"
|
|
112
|
+
note = "next: " + doc["next_command"]
|
|
113
|
+
for w in doc["warnings"]:
|
|
114
|
+
note += f"\nwarning: {w}"
|
|
115
|
+
if doc["needs_human_confirmation"]:
|
|
116
|
+
note += "\nthese need a human but took the default: " + ", ".join(
|
|
117
|
+
doc["needs_human_confirmation"]
|
|
118
|
+
)
|
|
119
|
+
return Outcome(doc, code, text, note)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cmd_plan(args: argparse.Namespace) -> Outcome:
|
|
123
|
+
doc, code = workflow.plan_project(args.project, args.paths)
|
|
124
|
+
lines = [
|
|
125
|
+
f"{u['order']:>3} {u['id']} {u['difficulty']['level']}({u['difficulty']['score']}) "
|
|
126
|
+
f"no-todo {u['coverage']['no_todo_pct']}% tests {len(u['tests'])} deps {len(u['depends_on'])}"
|
|
127
|
+
for u in doc["units"]
|
|
128
|
+
]
|
|
129
|
+
s = doc["summary"]
|
|
130
|
+
note = f"{s['units']} unit(s) from {s['modules']} module(s), {s['cycles']} cycle(s); wrote .python2rust/plan.json"
|
|
131
|
+
for w in doc["warnings"]:
|
|
132
|
+
note += f"\nwarning: {w}"
|
|
133
|
+
for bad in doc["unparsable"]:
|
|
134
|
+
note += f"\nerror: {bad['file']}: {bad['error']}"
|
|
135
|
+
return Outcome(doc, code, "\n".join(lines) + ("\n" if lines else ""), note)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def cmd_next(args: argparse.Namespace) -> Outcome:
|
|
139
|
+
doc, code = workflow.next_unit(args.project)
|
|
140
|
+
unit = doc["unit"]["id"] if doc["unit"] else None
|
|
141
|
+
return Outcome(doc, code, doc["markdown"], f"next unit: {unit}" if unit else "no unit left")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def cmd_done(args: argparse.Namespace) -> Outcome:
|
|
145
|
+
cargo = {
|
|
146
|
+
"deps_from": args.deps_from,
|
|
147
|
+
"offline": args.offline,
|
|
148
|
+
"timeout": args.timeout,
|
|
149
|
+
"target_dir": args.target_dir,
|
|
150
|
+
}
|
|
151
|
+
doc, code = workflow.done_unit(
|
|
152
|
+
args.project,
|
|
153
|
+
args.unit,
|
|
154
|
+
reviewed=args.reviewed,
|
|
155
|
+
run_python=args.run_python,
|
|
156
|
+
accept_not_clean=args.accept_not_clean,
|
|
157
|
+
**cargo,
|
|
158
|
+
)
|
|
159
|
+
if doc["recorded"]:
|
|
160
|
+
text = f"done: {args.unit} (tier {doc['tier']}, asked for {doc['requested_tier']})\n"
|
|
161
|
+
else:
|
|
162
|
+
text = "".join(
|
|
163
|
+
f"missing: {m['rung']}: {m['file']}: {m['reason']}\n" for m in doc["missing"]
|
|
164
|
+
)
|
|
165
|
+
note = "".join(f"not verified: {n['rung']}: {n['reason']}\n" for n in doc["not_verified"])
|
|
166
|
+
note += f"next: {doc['next_command']}" if doc["next_command"] else "all units are done"
|
|
167
|
+
return Outcome(doc, code, text, note)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def cmd_status(args: argparse.Namespace) -> Outcome:
|
|
171
|
+
doc, code = workflow.status_project(args.project)
|
|
172
|
+
p = doc["progress"]
|
|
173
|
+
lines = [f"phase: {doc['phase']}", f"current unit: {doc['current_unit'] or '-'}"]
|
|
174
|
+
lines += [f"units: {p['units_done']}/{p['units_total']} done"]
|
|
175
|
+
lines += [f"blocker: {b}" for b in doc["blockers"]]
|
|
176
|
+
lines += [f"open question: {q['id']}: {q['question']}" for q in doc["open_questions"]]
|
|
177
|
+
lines += [f"next: {doc['next_command'] or '-'}"]
|
|
178
|
+
return Outcome(doc, code, "\n".join(lines) + "\n")
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""python2rust core: a typed-Python to Rust translator (stdlib `ast` frontend, typed Rust IR, emitter)."""
|
|
2
|
+
|
|
3
|
+
from .config import Config, load_config
|
|
4
|
+
from .constructs import CONSTRUCTS, Construct
|
|
5
|
+
from .diagnostics import DIAGNOSTIC_CODES, Diagnostic, Todo
|
|
6
|
+
from .emit.crates import CrateSpec, render_dependencies
|
|
7
|
+
from .emit.schema import render_api_docs
|
|
8
|
+
from .emit.translate import (
|
|
9
|
+
DriftEntry,
|
|
10
|
+
TranslateResult,
|
|
11
|
+
format_rust,
|
|
12
|
+
runtime_source,
|
|
13
|
+
translate_source,
|
|
14
|
+
)
|
|
15
|
+
from .frontend.project import ModuleInfo, ProjectResult, translate_project
|
|
16
|
+
from .lower.testing import TestEntry
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"CONSTRUCTS",
|
|
20
|
+
"DIAGNOSTIC_CODES",
|
|
21
|
+
"Config",
|
|
22
|
+
"Construct",
|
|
23
|
+
"CrateSpec",
|
|
24
|
+
"Diagnostic",
|
|
25
|
+
"DriftEntry",
|
|
26
|
+
"ModuleInfo",
|
|
27
|
+
"ProjectResult",
|
|
28
|
+
"TestEntry",
|
|
29
|
+
"Todo",
|
|
30
|
+
"TranslateResult",
|
|
31
|
+
"format_rust",
|
|
32
|
+
"load_config",
|
|
33
|
+
"render_api_docs",
|
|
34
|
+
"render_dependencies",
|
|
35
|
+
"runtime_source",
|
|
36
|
+
"translate_project",
|
|
37
|
+
"translate_source",
|
|
38
|
+
]
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""User configuration (TOML): import/library/type maps and review patterns."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import tomllib
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
DEFAULT_REVIEW_PATTERNS: tuple[str, ...] = (
|
|
10
|
+
r"(?i)(auth|token|password|secret|credential)",
|
|
11
|
+
r"(?i)\b(insert|update|delete)\b.*\b(into|from|set)\b",
|
|
12
|
+
r"(?i)\b(requests|httpx|urllib|aiohttp)\b",
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
# Name as written in Python source -> template. `{0}`, `{1}` are lowered positional arguments.
|
|
16
|
+
DEFAULT_LIBRARY_MAP: dict[str, dict[str, str]] = {
|
|
17
|
+
"json.loads": {
|
|
18
|
+
"rust": "rt::json_loads({0}.as_str())",
|
|
19
|
+
"returns": "value",
|
|
20
|
+
"raises": "JSONDecodeError",
|
|
21
|
+
},
|
|
22
|
+
"json.dumps": {"rust": "rt::json_dumps(&{0})", "returns": "str", "coerce": "value"},
|
|
23
|
+
"uuid.uuid4": {"rust": "uuid::Uuid::new_v4()", "returns": "type:uuid::Uuid"},
|
|
24
|
+
"time.time": {
|
|
25
|
+
"rust": "std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs_f64()",
|
|
26
|
+
"returns": "float",
|
|
27
|
+
},
|
|
28
|
+
"time.monotonic": {"rust": "rt::monotonic()", "returns": "float"},
|
|
29
|
+
"time.perf_counter": {"rust": "rt::monotonic()", "returns": "float"},
|
|
30
|
+
"time.sleep": {
|
|
31
|
+
"rust": "std::thread::sleep(std::time::Duration::from_secs_f64({0} as f64))",
|
|
32
|
+
"returns": "unit",
|
|
33
|
+
},
|
|
34
|
+
"html.escape": {"rust": "rt::html_escape({0}.as_str())", "returns": "str", "params": "s"},
|
|
35
|
+
"urllib.parse.quote": {
|
|
36
|
+
"rust": "rt::url_quote({0}.as_str(), {1}.as_str())",
|
|
37
|
+
"returns": "str",
|
|
38
|
+
"params": "string, safe='/'",
|
|
39
|
+
},
|
|
40
|
+
"urllib.parse.quote_plus": {
|
|
41
|
+
"rust": "rt::url_quote_plus({0}.as_str(), {1}.as_str())",
|
|
42
|
+
"returns": "str",
|
|
43
|
+
"params": "string, safe=''",
|
|
44
|
+
},
|
|
45
|
+
"urllib.parse.unquote": {
|
|
46
|
+
"rust": "rt::url_unquote({0}.as_str())",
|
|
47
|
+
"returns": "str",
|
|
48
|
+
"params": "string",
|
|
49
|
+
},
|
|
50
|
+
"urllib.parse.urlencode": {
|
|
51
|
+
"rust": "rt::urlencode({0}.iter())",
|
|
52
|
+
"returns": "str",
|
|
53
|
+
"params": "query",
|
|
54
|
+
},
|
|
55
|
+
"math.isfinite": {"rust": "({0} as f64).is_finite()", "returns": "bool"},
|
|
56
|
+
"math.isnan": {"rust": "({0} as f64).is_nan()", "returns": "bool"},
|
|
57
|
+
"math.isinf": {"rust": "({0} as f64).is_infinite()", "returns": "bool"},
|
|
58
|
+
"re.compile": {
|
|
59
|
+
"rust": "rt::re::Pattern::new({0}.as_str(), {1})",
|
|
60
|
+
"returns": "type:rt::re::Pattern",
|
|
61
|
+
"params": "pattern, flags=0",
|
|
62
|
+
"feature": "regex",
|
|
63
|
+
},
|
|
64
|
+
"re.IGNORECASE": {"rust": "2", "returns": "int"},
|
|
65
|
+
"re.I": {"rust": "2", "returns": "int"},
|
|
66
|
+
"re.MULTILINE": {"rust": "8", "returns": "int"},
|
|
67
|
+
"re.M": {"rust": "8", "returns": "int"},
|
|
68
|
+
"re.DOTALL": {"rust": "16", "returns": "int"},
|
|
69
|
+
"re.S": {"rust": "16", "returns": "int"},
|
|
70
|
+
"re.VERBOSE": {"rust": "64", "returns": "int"},
|
|
71
|
+
"re.X": {"rust": "64", "returns": "int"},
|
|
72
|
+
"re.search": {
|
|
73
|
+
"rust": "rt::re::search({0}.as_str(), {1}.as_str())",
|
|
74
|
+
"returns": "option:type:rt::re::Match",
|
|
75
|
+
"raises": "error",
|
|
76
|
+
"feature": "regex",
|
|
77
|
+
},
|
|
78
|
+
"re.match": {
|
|
79
|
+
"rust": "rt::re::match_({0}.as_str(), {1}.as_str())",
|
|
80
|
+
"returns": "option:type:rt::re::Match",
|
|
81
|
+
"raises": "error",
|
|
82
|
+
"feature": "regex",
|
|
83
|
+
},
|
|
84
|
+
"re.fullmatch": {
|
|
85
|
+
"rust": "rt::re::fullmatch({0}.as_str(), {1}.as_str())",
|
|
86
|
+
"returns": "option:type:rt::re::Match",
|
|
87
|
+
"raises": "error",
|
|
88
|
+
"feature": "regex",
|
|
89
|
+
},
|
|
90
|
+
"re.sub": {
|
|
91
|
+
"rust": "rt::re::sub({0}.as_str(), {1}.as_str(), {2}.as_str())",
|
|
92
|
+
"returns": "str",
|
|
93
|
+
"raises": "error",
|
|
94
|
+
"feature": "regex",
|
|
95
|
+
},
|
|
96
|
+
"re.findall": {
|
|
97
|
+
"rust": "rt::re::findall({0}.as_str(), {1}.as_str())",
|
|
98
|
+
"returns": "vec:str",
|
|
99
|
+
"raises": "error",
|
|
100
|
+
"feature": "regex",
|
|
101
|
+
},
|
|
102
|
+
"re.split": {
|
|
103
|
+
"rust": "rt::re::split({0}.as_str(), {1}.as_str())",
|
|
104
|
+
"returns": "vec:str",
|
|
105
|
+
"raises": "error",
|
|
106
|
+
"feature": "regex",
|
|
107
|
+
},
|
|
108
|
+
"hashlib.sha256": {
|
|
109
|
+
"rust": "rt::sha256({0}.as_slice())",
|
|
110
|
+
"returns": "type:rt::Digest",
|
|
111
|
+
"feature": "hash",
|
|
112
|
+
},
|
|
113
|
+
"hashlib.md5": {
|
|
114
|
+
"rust": "rt::md5({0}.as_slice())",
|
|
115
|
+
"returns": "type:rt::Digest",
|
|
116
|
+
"feature": "hash",
|
|
117
|
+
},
|
|
118
|
+
"base64.b64encode": {
|
|
119
|
+
"rust": "rt::b64::encode({0}.as_slice())",
|
|
120
|
+
"returns": "bytes",
|
|
121
|
+
"coerce": "bytes",
|
|
122
|
+
"feature": "base64",
|
|
123
|
+
},
|
|
124
|
+
"base64.urlsafe_b64encode": {
|
|
125
|
+
"rust": "rt::b64::urlsafe_encode({0}.as_slice())",
|
|
126
|
+
"returns": "bytes",
|
|
127
|
+
"coerce": "bytes",
|
|
128
|
+
"feature": "base64",
|
|
129
|
+
},
|
|
130
|
+
"base64.b64decode": {
|
|
131
|
+
"rust": "rt::b64::decode({0}.as_slice())",
|
|
132
|
+
"returns": "bytes",
|
|
133
|
+
"coerce": "bytes",
|
|
134
|
+
"raises": "ValueError",
|
|
135
|
+
"feature": "base64",
|
|
136
|
+
},
|
|
137
|
+
"base64.urlsafe_b64decode": {
|
|
138
|
+
"rust": "rt::b64::urlsafe_decode({0}.as_slice())",
|
|
139
|
+
"returns": "bytes",
|
|
140
|
+
"coerce": "bytes",
|
|
141
|
+
"raises": "ValueError",
|
|
142
|
+
"feature": "base64",
|
|
143
|
+
},
|
|
144
|
+
"asyncio.sleep": {
|
|
145
|
+
"rust": "tokio::time::sleep(std::time::Duration::from_secs_f64({0} as f64))",
|
|
146
|
+
"returns": "future",
|
|
147
|
+
},
|
|
148
|
+
"math.sqrt": {"rust": "({0} as f64).sqrt()", "returns": "float"},
|
|
149
|
+
"math.floor": {"rust": "rt::float_to_int(({0} as f64).floor())", "returns": "int"},
|
|
150
|
+
"math.ceil": {"rust": "rt::float_to_int(({0} as f64).ceil())", "returns": "int"},
|
|
151
|
+
"math.trunc": {"rust": "rt::float_to_int(({0} as f64).trunc())", "returns": "int"},
|
|
152
|
+
"math.pi": {"rust": "std::f64::consts::PI", "returns": "float"},
|
|
153
|
+
"math.e": {"rust": "std::f64::consts::E", "returns": "float"},
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# Rust types for common stdlib types (needs the chrono and uuid crates; Decimal stays a string, as in JSON).
|
|
158
|
+
DEFAULT_TYPE_MAP: dict[str, str] = {
|
|
159
|
+
"datetime": "chrono::DateTime<chrono::Utc>",
|
|
160
|
+
"date": "chrono::NaiveDate",
|
|
161
|
+
"UUID": "uuid::Uuid",
|
|
162
|
+
"Decimal": "String",
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass(frozen=True)
|
|
167
|
+
class Config:
|
|
168
|
+
"""Translation settings. Every field has a safe default.
|
|
169
|
+
|
|
170
|
+
Build one programmatically (`Config(format=False, int_overflow="wrapping")`) or load a TOML
|
|
171
|
+
file with `load_config(path)`. `format` is the one switch for rustfmt: when false the Rust text
|
|
172
|
+
is returned as emitted (`PY2RS031` is only reported when formatting was requested and failed).
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
import_map: dict[str, str] = field(default_factory=dict)
|
|
176
|
+
library_map: dict[str, dict[str, str]] = field(
|
|
177
|
+
default_factory=lambda: dict(DEFAULT_LIBRARY_MAP)
|
|
178
|
+
)
|
|
179
|
+
type_map: dict[str, str] = field(default_factory=lambda: dict(DEFAULT_TYPE_MAP))
|
|
180
|
+
review_patterns: tuple[str, ...] = DEFAULT_REVIEW_PATTERNS
|
|
181
|
+
profile: str | None = None # "fastapi" turns schema generation on by default
|
|
182
|
+
schema: str | None = None # "utoipa" | "none"; None = by profile
|
|
183
|
+
query_models: tuple[
|
|
184
|
+
str, ...
|
|
185
|
+
] = () # models used as query parameters: IntoParams instead of ToSchema
|
|
186
|
+
format: bool = True
|
|
187
|
+
vendor_runtime: bool = False
|
|
188
|
+
tests: bool = True # lower pytest/unittest tests and doctests to #[test] functions
|
|
189
|
+
exception_map: dict[str, str] = field(
|
|
190
|
+
default_factory=dict
|
|
191
|
+
) # exception class -> Rust ExcKind path
|
|
192
|
+
omit_none: bool = False # skip None fields when serialising (Pydantic itself writes null)
|
|
193
|
+
shared: str = (
|
|
194
|
+
"rc" # rc | arc | off: Python objects are Shared<T> handles (rc/arc) or plain values
|
|
195
|
+
)
|
|
196
|
+
devirtualize: bool = True # plain owned values for locals that are provably not aliased
|
|
197
|
+
assume_module_init: bool = False # import-time code is run by py2rs_main(): items stay clean
|
|
198
|
+
builtin_errors: str = "reachable" # reachable | always: which built-in errors are Results
|
|
199
|
+
i64_models: bool = False # accept that model ints are limited to i64 (otherwise: not clean)
|
|
200
|
+
# external model base classes: dotted name -> its model_config keys (e.g. {"extra": "forbid"})
|
|
201
|
+
model_bases: dict[str, dict] = field(default_factory=dict)
|
|
202
|
+
set_type: str = "indexset" # "indexset" | "btreeset" | "hashset" (Python sets are unordered)
|
|
203
|
+
int_overflow: str = (
|
|
204
|
+
"checked" # "checked" (panic on overflow) | "wrapping" | "native" (plain Rust operators)
|
|
205
|
+
)
|
|
206
|
+
max_source_bytes: int = 4_000_000
|
|
207
|
+
max_depth: int = 250 # AST nesting depth per top-level statement
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def schema_enabled(self) -> bool:
|
|
211
|
+
return (self.schema or ("utoipa" if self.profile == "fastapi" else "none")) == "utoipa"
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _library_entry(value: object) -> dict[str, str]:
|
|
215
|
+
if isinstance(value, str):
|
|
216
|
+
return {"rust": value}
|
|
217
|
+
if isinstance(value, dict):
|
|
218
|
+
return {str(k): str(v) for k, v in value.items()}
|
|
219
|
+
raise ValueError(f"library_map entries must be a string or a table, got {value!r}")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def load_config(path: str | None) -> Config:
|
|
223
|
+
"""Load a TOML config; `None` gives the defaults. Maps extend the built-in ones.
|
|
224
|
+
|
|
225
|
+
The file is shared with the CLI. The core reads the top-level keys listed in `Config` (profile,
|
|
226
|
+
schema, import_map, library_map, type_map, exception_map, model_bases, review_patterns, ...)
|
|
227
|
+
and the same keys inside an optional `[core]` table. Every other table (`[agent]`, `[judge]`,
|
|
228
|
+
the equivalence profile, `[patch_gate]`, ...) belongs to the CLI and is ignored here.
|
|
229
|
+
"""
|
|
230
|
+
if path is None:
|
|
231
|
+
return Config()
|
|
232
|
+
data = tomllib.loads(Path(path).read_text(encoding="utf-8"))
|
|
233
|
+
data = {**data, **data.get("core", {})} # keys of an explicit [core] table win
|
|
234
|
+
library = dict(DEFAULT_LIBRARY_MAP)
|
|
235
|
+
library.update({k: _library_entry(v) for k, v in data.get("library_map", {}).items()})
|
|
236
|
+
patterns = tuple(data.get("review_patterns", DEFAULT_REVIEW_PATTERNS))
|
|
237
|
+
return Config(
|
|
238
|
+
import_map={str(k): str(v) for k, v in data.get("import_map", {}).items()},
|
|
239
|
+
library_map=library,
|
|
240
|
+
type_map={
|
|
241
|
+
**DEFAULT_TYPE_MAP,
|
|
242
|
+
**{str(k): str(v) for k, v in data.get("type_map", {}).items()},
|
|
243
|
+
},
|
|
244
|
+
review_patterns=patterns,
|
|
245
|
+
profile=data.get("profile"),
|
|
246
|
+
schema=data.get("schema"),
|
|
247
|
+
query_models=tuple(data.get("query_models", ())),
|
|
248
|
+
format=bool(data.get("format", True)),
|
|
249
|
+
vendor_runtime=bool(data.get("vendor_runtime", False)),
|
|
250
|
+
tests=bool(data.get("tests", True)),
|
|
251
|
+
exception_map={str(k): str(v) for k, v in data.get("exception_map", {}).items()},
|
|
252
|
+
omit_none=bool(data.get("omit_none", False)),
|
|
253
|
+
shared=str(data.get("shared", "rc")),
|
|
254
|
+
devirtualize=bool(data.get("devirtualize", True)),
|
|
255
|
+
assume_module_init=bool(data.get("assume_module_init", False)),
|
|
256
|
+
builtin_errors=str(data.get("builtin_errors", "reachable")),
|
|
257
|
+
i64_models=bool(data.get("i64_models", False)),
|
|
258
|
+
model_bases={str(k): dict(v) for k, v in data.get("model_bases", {}).items()},
|
|
259
|
+
set_type=str(data.get("set_type", "indexset")),
|
|
260
|
+
int_overflow=str(data.get("int_overflow", "checked")),
|
|
261
|
+
max_source_bytes=int(data.get("max_source_bytes", 4_000_000)),
|
|
262
|
+
max_depth=int(data.get("max_depth", 250)),
|
|
263
|
+
)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""CONSTRUCTS: what python2rust translates, generated from the lowering tables themselves.
|
|
2
|
+
|
|
3
|
+
Each row is `{id, name, status, phase, codes}`; status is `supported`, `partial` (a subset of the
|
|
4
|
+
construct) or `todo` (always an explicit TODO with the listed stable codes). Because the rows come
|
|
5
|
+
from the handler methods (`expr_*`, `st_*`, `b_*`, `m_*`) and `STMT_CODES`, they cannot drift from
|
|
6
|
+
what the translator really does.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import TypedDict
|
|
12
|
+
|
|
13
|
+
from .config import DEFAULT_LIBRARY_MAP
|
|
14
|
+
from .lower.stmts import STMT_CODES, StmtLowerer
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Construct(TypedDict):
|
|
18
|
+
id: str
|
|
19
|
+
name: str
|
|
20
|
+
status: str
|
|
21
|
+
phase: str
|
|
22
|
+
codes: list[str]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# Handlers that exist but only cover a subset of the construct, with the codes their TODOs use.
|
|
26
|
+
PARTIAL = {
|
|
27
|
+
"expr.Call": ["PY2RS019", "PY2RS034"],
|
|
28
|
+
"expr.Subscript": ["PY2RS019", "PY2RS023", "PY2RS038"],
|
|
29
|
+
"expr.Compare": ["PY2RS038"],
|
|
30
|
+
"expr.BoolOp": ["PY2RS036"],
|
|
31
|
+
"expr.JoinedStr": ["PY2RS022"],
|
|
32
|
+
"expr.Attribute": ["PY2RS029"],
|
|
33
|
+
"expr.Lambda": ["PY2RS015"],
|
|
34
|
+
"expr.NamedExpr": ["PY2RS021"],
|
|
35
|
+
"expr.Name": ["PY2RS004"],
|
|
36
|
+
"stmt.Match": ["PY2RS020"],
|
|
37
|
+
"stmt.While": ["PY2RS003", "PY2RS021"],
|
|
38
|
+
"stmt.For": ["PY2RS003", "PY2RS039"],
|
|
39
|
+
"stmt.Assign": ["PY2RS003", "PY2RS040"],
|
|
40
|
+
"stmt.AugAssign": ["PY2RS038"],
|
|
41
|
+
"stmt.Delete": ["PY2RS003"],
|
|
42
|
+
"stmt.Import": ["PY2RS010"],
|
|
43
|
+
"stmt.ImportFrom": ["PY2RS010"],
|
|
44
|
+
# 0.2: lowered, with documented gaps
|
|
45
|
+
"expr.Await": ["PY2RS011"],
|
|
46
|
+
"stmt.Raise": ["PY2RS024"],
|
|
47
|
+
"stmt.Try": ["PY2RS012", "PY2RS024"],
|
|
48
|
+
"stmt.With": ["PY2RS025"],
|
|
49
|
+
}
|
|
50
|
+
PHASE_02 = frozenset({"expr.Await", "stmt.Raise", "stmt.Try", "stmt.With"})
|
|
51
|
+
TODO_EXPRS = {
|
|
52
|
+
"Yield": "PY2RS027",
|
|
53
|
+
"YieldFrom": "PY2RS027",
|
|
54
|
+
}
|
|
55
|
+
OTHER: list[Construct] = [
|
|
56
|
+
{"id": "model.BaseModel", "name": "Pydantic BaseModel", "status": "supported", "phase": "0.1", "codes": ["PY2RS017", "PY2RS043", "PY2RS049"]},
|
|
57
|
+
{"id": "model.dataclass", "name": "dataclass", "status": "supported", "phase": "0.1", "codes": []},
|
|
58
|
+
{"id": "model.TypedDict", "name": "TypedDict", "status": "supported", "phase": "0.1", "codes": []},
|
|
59
|
+
{"id": "model.NamedTuple", "name": "NamedTuple", "status": "supported", "phase": "0.1", "codes": []},
|
|
60
|
+
{"id": "model.NewType", "name": "NewType", "status": "supported", "phase": "0.1", "codes": []},
|
|
61
|
+
{"id": "model.Enum", "name": "Enum / StrEnum / IntEnum", "status": "supported", "phase": "0.1", "codes": ["PY2RS037"]},
|
|
62
|
+
{"id": "type.Literal", "name": "Literal (string) -> enum", "status": "supported", "phase": "0.1", "codes": ["PY2RS009"]},
|
|
63
|
+
{"id": "type.Union", "name": "Union / X | Y -> untagged enum", "status": "supported", "phase": "0.1", "codes": ["PY2RS008", "PY2RS009"]},
|
|
64
|
+
{"id": "type.alias", "name": "type alias / PEP 695 type", "status": "supported", "phase": "0.1", "codes": []},
|
|
65
|
+
{"id": "module.constant", "name": "module-level constant", "status": "partial", "phase": "0.1", "codes": ["PY2RS032"]},
|
|
66
|
+
{"id": "module.import", "name": "import (typing/pydantic/mapped/library)", "status": "partial", "phase": "0.1", "codes": ["PY2RS010"]},
|
|
67
|
+
{"id": "model.validator", "name": "validators and computed fields", "status": "todo", "phase": "0.2", "codes": ["PY2RS018"]},
|
|
68
|
+
{"id": "class.plain", "name": "plain class / methods", "status": "todo", "phase": "0.2", "codes": ["PY2RS013"]},
|
|
69
|
+
{"id": "func.async", "name": "async def / await of coroutines", "status": "partial", "phase": "0.2", "codes": ["PY2RS011"]},
|
|
70
|
+
{"id": "async.sleep", "name": "asyncio.sleep", "status": "supported", "phase": "0.2", "codes": []},
|
|
71
|
+
{"id": "async.gather", "name": "asyncio.gather", "status": "todo", "phase": "0.2", "codes": ["PY2RS019"]},
|
|
72
|
+
{"id": "async.create_task", "name": "asyncio.create_task", "status": "todo", "phase": "0.2", "codes": ["PY2RS019"]},
|
|
73
|
+
{"id": "async.sync_primitives", "name": "asyncio.Lock / Semaphore / Queue", "status": "todo", "phase": "0.2", "codes": ["PY2RS019"]},
|
|
74
|
+
{"id": "async.timeout", "name": "asyncio.wait_for / timeout", "status": "todo", "phase": "0.2", "codes": ["PY2RS019"]},
|
|
75
|
+
{"id": "exception.class", "name": "exception classes (kind tree)", "status": "partial", "phase": "0.2", "codes": ["PY2RS013"]},
|
|
76
|
+
{"id": "project.mode", "name": "multi-module projects", "status": "partial", "phase": "0.2", "codes": ["PY2RS054", "PY2RS055"]},
|
|
77
|
+
{"id": "test.pytest", "name": "pytest / unittest / doctest -> #[test]", "status": "partial", "phase": "0.2", "codes": ["PY2RS052", "PY2RS053"]},
|
|
78
|
+
{"id": "func.generator", "name": "generator function", "status": "todo", "phase": "0.2", "codes": ["PY2RS027"]},
|
|
79
|
+
{"id": "func.decorator", "name": "decorators", "status": "todo", "phase": "0.2", "codes": ["PY2RS014"]},
|
|
80
|
+
{"id": "func.variadic", "name": "*args / **kwargs parameters", "status": "partial", "phase": "0.1", "codes": ["PY2RS015", "PY2RS034"]},
|
|
81
|
+
{"id": "func.defaults", "name": "default arguments", "status": "partial", "phase": "0.1", "codes": ["PY2RS016", "PY2RS033"]},
|
|
82
|
+
] # fmt: skip
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def build_constructs() -> list[Construct]:
|
|
86
|
+
rows: list[Construct] = []
|
|
87
|
+
|
|
88
|
+
def add(cid: str, name: str, status: str, phase: str, codes: list[str]) -> None:
|
|
89
|
+
rows.append({"id": cid, "name": name, "status": status, "phase": phase, "codes": codes})
|
|
90
|
+
|
|
91
|
+
for attr in sorted(_inherited(StmtLowerer)):
|
|
92
|
+
kind, _, rest = attr.partition("_")
|
|
93
|
+
if kind == "expr" and rest and rest not in TODO_EXPRS:
|
|
94
|
+
cid = f"expr.{rest}"
|
|
95
|
+
codes = PARTIAL.get(cid)
|
|
96
|
+
phase = "0.2" if cid in PHASE_02 else "0.1"
|
|
97
|
+
add(cid, f"{rest} expression", "partial" if codes else "supported", phase, codes or [])
|
|
98
|
+
elif kind == "b" and rest:
|
|
99
|
+
add(f"builtin.{rest}", f"{rest}()", "supported", "0.1", ["PY2RS019"])
|
|
100
|
+
elif kind == "m" and rest.count("_") >= 1:
|
|
101
|
+
owner, _, method = rest.partition("_")
|
|
102
|
+
add(f"method.{owner}.{method}", f"{owner}.{method}()", "supported", "0.1", ["PY2RS019"])
|
|
103
|
+
for name, code in TODO_EXPRS.items():
|
|
104
|
+
add(f"expr.{name}", f"{name} expression", "todo", "0.2", [code])
|
|
105
|
+
for attr in sorted(a for a in dir(StmtLowerer) if a.startswith("st_")):
|
|
106
|
+
cid = f"stmt.{attr[3:]}"
|
|
107
|
+
codes = PARTIAL.get(cid)
|
|
108
|
+
phase = "0.2" if cid in PHASE_02 else "0.1"
|
|
109
|
+
add(cid, f"{attr[3:]} statement", "partial" if codes else "supported", phase, codes or [])
|
|
110
|
+
for stmt, (code, what) in sorted(STMT_CODES.items()):
|
|
111
|
+
add(f"stmt.{stmt}", what, "todo", "0.2", [code])
|
|
112
|
+
rows.extend(OTHER)
|
|
113
|
+
for module in sorted({name.split(".")[0] for name in DEFAULT_LIBRARY_MAP}):
|
|
114
|
+
add(
|
|
115
|
+
f"library.{module}", f"{module} (mapped functions only)", "partial", "0.2", ["PY2RS019"]
|
|
116
|
+
)
|
|
117
|
+
return rows
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _inherited(cls: type) -> set[str]:
|
|
121
|
+
return {name for base in cls.__mro__ for name in vars(base)}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
CONSTRUCTS: list[Construct] = build_constructs()
|