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,280 @@
|
|
|
1
|
+
"""Diagnostic and TODO records, plus the registry of every PY2RS code.
|
|
2
|
+
|
|
3
|
+
Codes are never ad hoc: `Collector.diag` and `Collector.todo` refuse unregistered codes.
|
|
4
|
+
Codes are frozen at 0.1.0 (append-only afterwards).
|
|
5
|
+
|
|
6
|
+
TODO marker format (the contract tools such as `find_span` rely on). Every unfinished construct
|
|
7
|
+
is a real Rust `todo!()` whose message is
|
|
8
|
+
|
|
9
|
+
python2rust <ID> <CODE>: <construct> at <python file>:<python line>
|
|
10
|
+
|
|
11
|
+
for example `todo!("python2rust t3f9a1c2e PY2RS024: raise at m.py:12")`. `<ID>` is the stable TODO
|
|
12
|
+
id: `t` + 8 hex digits of sha256(code, construct, normalised snippet, enclosing item), with a
|
|
13
|
+
`-2`, `-3`... suffix for the n-th identical TODO inside the same enclosing item (so ids do not
|
|
14
|
+
depend on file order or line numbers). Statement and expression TODOs sit where the construct was;
|
|
15
|
+
item-level TODOs are a stub `fn py2rs_todo_<id>() { todo!("...") }`; an unmapped type is a
|
|
16
|
+
placeholder type `Py2rsUnmapped_<name> /* <same message> */` (no `todo!` fits in type position).
|
|
17
|
+
`Todo.rust_line` is the line of the `todo!(` token (or of the comment, for types).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import ast
|
|
23
|
+
import hashlib
|
|
24
|
+
from collections.abc import Generator
|
|
25
|
+
from contextlib import contextmanager
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
|
|
28
|
+
DIAGNOSTIC_CODES: dict[str, str] = {
|
|
29
|
+
"PY2RS001": "The Python source has a syntax error; no Rust could be produced.",
|
|
30
|
+
"PY2RS002": "The translator failed internally on this item; it was replaced by a todo!().",
|
|
31
|
+
"PY2RS003": "This statement kind is not supported yet and became a todo!().",
|
|
32
|
+
"PY2RS004": "This expression kind is not supported yet and became a todo!().",
|
|
33
|
+
"PY2RS005": "A type annotation could not be mapped to Rust; an undefined placeholder type marks it.",
|
|
34
|
+
"PY2RS006": "A parameter or return annotation is missing; the function cannot be translated.",
|
|
35
|
+
"PY2RS007": "Any/object/unparameterised containers map to serde_json::Value (type information is lost).",
|
|
36
|
+
"PY2RS008": "A union of several types became a generated #[serde(untagged)] enum.",
|
|
37
|
+
"PY2RS009": "A type mapping is lossy (int | float -> f64, int Literal -> i64, default None -> Option).",
|
|
38
|
+
"PY2RS010": "This import is not mapped yet; add it to import_map or library_map in the config.",
|
|
39
|
+
"PY2RS011": "async def / await is not translated yet (planned for 0.2).",
|
|
40
|
+
"PY2RS012": "try/except is not translated yet (planned for 0.2).",
|
|
41
|
+
"PY2RS013": "Class methods and plain classes are not translated yet (planned for 0.2).",
|
|
42
|
+
"PY2RS014": "A decorator was found; its runtime effect is not translated.",
|
|
43
|
+
"PY2RS015": "*args/**kwargs became a Vec/IndexMap parameter; callers must pack their arguments.",
|
|
44
|
+
"PY2RS016": "A default argument is filled in at each call site of a function in this module.",
|
|
45
|
+
"PY2RS017": "A Field/validator constraint is recorded as a doc comment but not enforced.",
|
|
46
|
+
"PY2RS018": "A model validator, computed property or nested Config class is not translated.",
|
|
47
|
+
"PY2RS019": "A call or method could not be resolved (unknown callee or receiver type).",
|
|
48
|
+
"PY2RS020": "This match pattern is not supported; the whole match became a todo!().",
|
|
49
|
+
"PY2RS021": "A walrus (:=) in this position cannot be hoisted into a let binding.",
|
|
50
|
+
"PY2RS022": "This f-string conversion or format spec is not supported.",
|
|
51
|
+
"PY2RS023": "Slicing with this step is not supported.",
|
|
52
|
+
"PY2RS024": "raise is not translated yet (exceptions are planned for 0.2).",
|
|
53
|
+
"PY2RS025": "with/async with is not translated yet (planned for 0.2).",
|
|
54
|
+
"PY2RS026": "Nested function and class definitions are not translated yet.",
|
|
55
|
+
"PY2RS027": "Generators (yield) are not translated yet.",
|
|
56
|
+
"PY2RS028": "global/nonlocal is not translated.",
|
|
57
|
+
"PY2RS029": "An attribute could not be resolved on this value.",
|
|
58
|
+
"PY2RS030": "The function matches a review pattern and needs human review.",
|
|
59
|
+
"PY2RS031": "rustfmt was unavailable or failed; the output is unformatted.",
|
|
60
|
+
"PY2RS032": "A module-level value cannot be expressed as a Rust const or static.",
|
|
61
|
+
"PY2RS033": "A mutable default argument is shared between calls in Python; here it is not.",
|
|
62
|
+
"PY2RS034": "Argument unpacking (*xs, **kw) at a call site is not supported.",
|
|
63
|
+
"PY2RS035": "This comprehension shape or loop target is not supported.",
|
|
64
|
+
"PY2RS036": "The truthiness or boolean operation needs a known type; the type is unknown.",
|
|
65
|
+
"PY2RS037": "An Enum member value is not supported.",
|
|
66
|
+
"PY2RS038": "This operator or operand combination is not supported.",
|
|
67
|
+
"PY2RS039": "A for-loop target is used after the loop; Rust scoping differs.",
|
|
68
|
+
"PY2RS040": "A mutable container is aliased and then mutated; Rust clones, Python shares.",
|
|
69
|
+
"PY2RS041": "Drift: int is i64 while Python ints are unbounded; overflow panics (checked) or wraps (wrapping/native).",
|
|
70
|
+
"PY2RS042": "Drift: str(float)/repr/format are emulated by the runtime crate and may differ in rare cases.",
|
|
71
|
+
"PY2RS043": "Drift: a model field is parsed differently from Pydantic (types other than int/float/bool/str are not coerced; dates and Decimal accept other formats).",
|
|
72
|
+
"PY2RS044": "Drift: Unicode-sensitive str methods (isdigit, lower, upper) follow Rust, not Python, rules.",
|
|
73
|
+
"PY2RS045": "Drift: IndexError/KeyError/ValueError/ZeroDivisionError become panics instead of exceptions.",
|
|
74
|
+
"PY2RS046": "Drift: float division by zero panics instead of raising ZeroDivisionError.",
|
|
75
|
+
"PY2RS047": "Drift: sorting and min/max compare with partial_cmp; NaN ordering can differ from Python.",
|
|
76
|
+
"PY2RS048": "A recursive or generic model needs manual work (Box indirection, schema recursion, type parameters).",
|
|
77
|
+
"PY2RS049": "Drift: a field constraint is documented in the schema but not validated at deserialisation.",
|
|
78
|
+
"PY2RS050": "The input exceeds a resource limit (size, nesting depth or parser memory); the affected part was not translated.",
|
|
79
|
+
"PY2RS051": "An identifier was renamed (snake_case) or made raw (r#keyword) to be valid Rust.",
|
|
80
|
+
"PY2RS052": "A test could not be translated to a Rust #[test]; it is listed as dropped.",
|
|
81
|
+
"PY2RS053": "Drift: a test, or part of an assertion, was not translated (test.dropped): the Rust oracle is weaker.",
|
|
82
|
+
"PY2RS054": "Python modules import each other in a cycle; the Rust modules reference each other too.",
|
|
83
|
+
"PY2RS055": "A project import could not be resolved (missing module, unknown name or star import).",
|
|
84
|
+
"PY2RS056": "Drift: Pydantic accepts integers beyond i64 and the Rust model rejects them; add ge/le bounds or set i64_models.",
|
|
85
|
+
"PY2RS057": "Drift: an int stored where a float is annotated stays an int in Python (prints 3, serialises 3) but is a float in Rust (3.0).",
|
|
86
|
+
"PY2RS058": "Drift: statements and values computed at import time run in py2rs_module_init() (once), not when the module is loaded.",
|
|
87
|
+
"PY2RS059": "Drift: a generator whose elements can raise is evaluated eagerly; a short-circuiting consumer (any/all/next) may raise where Python stops early.",
|
|
88
|
+
"PY2RS060": 'Python objects are Rc-based handles, so futures are not Send; set shared = "arc" for a multi-threaded async runtime.',
|
|
89
|
+
"PY2RS061": "Drift: a recursive call may reach Python's recursion limit; generated Rust uses its native stack.",
|
|
90
|
+
"PY2RS062": "A Python string literal contains a surrogate code point, which Rust strings cannot represent.",
|
|
91
|
+
"PY2RS063": "Drift: this loop uses a snapshot; Python can raise RuntimeError if its dict or set changes during iteration.",
|
|
92
|
+
}
|
|
93
|
+
DRIFT_CODES = frozenset(
|
|
94
|
+
{f"PY2RS04{i}" for i in (1, 2, 3, 4, 5, 6, 7, 9)}
|
|
95
|
+
| {"PY2RS053", "PY2RS056", "PY2RS057", "PY2RS058", "PY2RS059", "PY2RS061", "PY2RS063"}
|
|
96
|
+
)
|
|
97
|
+
# Behaviour that is dropped or not enforced: an item with one of these is never counted as clean.
|
|
98
|
+
UNENFORCED = frozenset(
|
|
99
|
+
{"PY2RS017", "PY2RS018", "PY2RS043", "PY2RS049", "PY2RS056", "PY2RS057", "PY2RS059", "PY2RS063"}
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class Diagnostic:
|
|
105
|
+
code: str
|
|
106
|
+
severity: str # "error" | "warning" | "info"
|
|
107
|
+
message: str
|
|
108
|
+
file: str
|
|
109
|
+
line: int
|
|
110
|
+
col: int
|
|
111
|
+
construct: str | None = None
|
|
112
|
+
hint: str | None = None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True)
|
|
116
|
+
class Todo:
|
|
117
|
+
id: str
|
|
118
|
+
code: str
|
|
119
|
+
file: str
|
|
120
|
+
line: int
|
|
121
|
+
python_snippet: str
|
|
122
|
+
rust_context: str
|
|
123
|
+
rust_line: int
|
|
124
|
+
kind: str
|
|
125
|
+
needs_review: bool
|
|
126
|
+
review_reason: str | None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass
|
|
130
|
+
class PendingTodo:
|
|
131
|
+
"""A TODO before the final Rust text exists (its Rust line is found after emission)."""
|
|
132
|
+
|
|
133
|
+
id: str
|
|
134
|
+
code: str
|
|
135
|
+
line: int
|
|
136
|
+
snippet: str
|
|
137
|
+
marker: str
|
|
138
|
+
kind: str
|
|
139
|
+
construct: str
|
|
140
|
+
enclosing: str
|
|
141
|
+
review_reason: str | None = None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def rust_escape(text: str) -> str:
|
|
145
|
+
"""Escape text for use inside a Rust string literal."""
|
|
146
|
+
out: list[str] = []
|
|
147
|
+
for ch in text:
|
|
148
|
+
if ch in '\\"':
|
|
149
|
+
out.append("\\" + ch)
|
|
150
|
+
elif ch in "\n\r\t\0":
|
|
151
|
+
out.append({"\n": "\\n", "\r": "\\r", "\t": "\\t", "\0": "\\0"}[ch])
|
|
152
|
+
elif ord(ch) < 32 or ord(ch) == 127:
|
|
153
|
+
out.append(f"\\u{{{ord(ch):x}}}")
|
|
154
|
+
else:
|
|
155
|
+
out.append(ch)
|
|
156
|
+
return "".join(out)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass
|
|
160
|
+
class Collector:
|
|
161
|
+
"""Per-translation sink for diagnostics and TODOs (no global state)."""
|
|
162
|
+
|
|
163
|
+
file: str
|
|
164
|
+
source: str
|
|
165
|
+
diagnostics: list[Diagnostic] = field(default_factory=list)
|
|
166
|
+
todos: list[PendingTodo] = field(default_factory=list)
|
|
167
|
+
_scope: list[str] = field(default_factory=list)
|
|
168
|
+
_seen_drift: set[tuple[str, str]] = field(default_factory=set)
|
|
169
|
+
_duplicates: dict[str, int] = field(default_factory=dict)
|
|
170
|
+
unenforced: int = 0 # diagnostics from UNENFORCED so far (not counting PY2RS056)
|
|
171
|
+
int_range: int = 0 # PY2RS056: the model reads Python's unbounded ints into i64
|
|
172
|
+
|
|
173
|
+
@contextmanager
|
|
174
|
+
def enclosing(self, name: str) -> Generator[None]:
|
|
175
|
+
"""Name the item being translated; it feeds stable TODO ids and drift de-duplication."""
|
|
176
|
+
self._scope.append(name)
|
|
177
|
+
try:
|
|
178
|
+
yield
|
|
179
|
+
finally:
|
|
180
|
+
self._scope.pop()
|
|
181
|
+
|
|
182
|
+
def snapshot(self) -> tuple:
|
|
183
|
+
return (
|
|
184
|
+
len(self.todos), len(self.diagnostics), set(self._seen_drift), dict(self._duplicates),
|
|
185
|
+
self.unenforced, self.int_range,
|
|
186
|
+
) # fmt: skip
|
|
187
|
+
|
|
188
|
+
def restore(self, snap: tuple) -> None:
|
|
189
|
+
"""Forget what lowering recorded since `snapshot()` (it is about to be done again)."""
|
|
190
|
+
todos, diags, seen, dups, self.unenforced, self.int_range = snap
|
|
191
|
+
del self.todos[todos:], self.diagnostics[diags:]
|
|
192
|
+
self._seen_drift, self._duplicates = seen, dups
|
|
193
|
+
|
|
194
|
+
def _snippet(self, node: ast.AST | None) -> str:
|
|
195
|
+
"""The source text of `node` (a generated node has none: its unparse stands in)."""
|
|
196
|
+
if node is None:
|
|
197
|
+
return ""
|
|
198
|
+
try:
|
|
199
|
+
text = ast.get_source_segment(self.source, node) or ""
|
|
200
|
+
except IndexError, TypeError:
|
|
201
|
+
try:
|
|
202
|
+
text = ast.unparse(node)
|
|
203
|
+
except Exception: # a node the generator made up
|
|
204
|
+
text = ""
|
|
205
|
+
return text[:600]
|
|
206
|
+
|
|
207
|
+
def mark(self) -> tuple[int, int, int]:
|
|
208
|
+
return len(self.todos), self.unenforced, self.int_range
|
|
209
|
+
|
|
210
|
+
def clean_since(self, mark: tuple[int, int, int], modulo_int_range: bool = False) -> bool:
|
|
211
|
+
"""No TODO and nothing dropped or unenforced since `mark`: only then is an item clean.
|
|
212
|
+
`modulo_int_range` ignores PY2RS056 (the i64 limit of model ints)."""
|
|
213
|
+
now = self.mark()
|
|
214
|
+
return now[:2] == mark[:2] and (modulo_int_range or now[2] == mark[2])
|
|
215
|
+
|
|
216
|
+
def diag(
|
|
217
|
+
self,
|
|
218
|
+
code: str,
|
|
219
|
+
node: object,
|
|
220
|
+
message: str | None = None,
|
|
221
|
+
*,
|
|
222
|
+
severity: str = "warning",
|
|
223
|
+
construct: str | None = None,
|
|
224
|
+
hint: str | None = None,
|
|
225
|
+
) -> None:
|
|
226
|
+
if code not in DIAGNOSTIC_CODES:
|
|
227
|
+
raise KeyError(f"unregistered diagnostic code {code}")
|
|
228
|
+
line = getattr(node, "lineno", None) or getattr(node, "line", 0) # an ast node or a Span
|
|
229
|
+
col = getattr(node, "col_offset", None) or getattr(node, "col", 0)
|
|
230
|
+
if code == "PY2RS056":
|
|
231
|
+
self.int_range += 1
|
|
232
|
+
else:
|
|
233
|
+
self.unenforced += code in UNENFORCED
|
|
234
|
+
self.diagnostics.append(
|
|
235
|
+
Diagnostic(
|
|
236
|
+
code,
|
|
237
|
+
severity,
|
|
238
|
+
message or DIAGNOSTIC_CODES[code],
|
|
239
|
+
self.file,
|
|
240
|
+
line,
|
|
241
|
+
col,
|
|
242
|
+
construct,
|
|
243
|
+
hint,
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
def drift(self, code: str, node: object, what: str) -> None:
|
|
248
|
+
"""Info diagnostic for a place where Rust behaviour can differ; once per code and item."""
|
|
249
|
+
key = (code, ".".join(self._scope))
|
|
250
|
+
if key not in self._seen_drift:
|
|
251
|
+
self._seen_drift.add(key)
|
|
252
|
+
self.diag(
|
|
253
|
+
code, node, f"{DIAGNOSTIC_CODES[code]} ({what})", severity="info", construct=what
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
def todo(
|
|
257
|
+
self,
|
|
258
|
+
code: str,
|
|
259
|
+
node: ast.AST | None,
|
|
260
|
+
construct: str,
|
|
261
|
+
*,
|
|
262
|
+
kind: str = "stmt",
|
|
263
|
+
hint: str | None = None,
|
|
264
|
+
) -> str:
|
|
265
|
+
"""Record a TODO and return the marker text that goes inside `todo!("...")`."""
|
|
266
|
+
line = getattr(node, "lineno", 0)
|
|
267
|
+
self.diag(
|
|
268
|
+
code, node, f"{DIAGNOSTIC_CODES[code]} ({construct})", construct=construct, hint=hint
|
|
269
|
+
)
|
|
270
|
+
snippet = self._snippet(node)
|
|
271
|
+
enclosing = ".".join(self._scope)
|
|
272
|
+
digest = "\0".join((code, construct, " ".join(snippet.split()), enclosing))
|
|
273
|
+
base = "t" + hashlib.sha256(digest.encode()).hexdigest()[:8]
|
|
274
|
+
nth = self._duplicates[base] = self._duplicates.get(base, 0) + 1
|
|
275
|
+
todo_id = base if nth == 1 else f"{base}-{nth}"
|
|
276
|
+
marker = f"python2rust {todo_id} {code}: {construct} at {self.file}:{line}"
|
|
277
|
+
self.todos.append(
|
|
278
|
+
PendingTodo(todo_id, code, line, snippet, marker, kind, construct, enclosing)
|
|
279
|
+
)
|
|
280
|
+
return marker
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Which crates and python2rust-rt features the generated code needs (for the generated Cargo.toml)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import TypedDict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CrateSpec(TypedDict):
|
|
10
|
+
version: str
|
|
11
|
+
features: list[str]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# Needle in the generated text -> (crate, version, features). python2rust-rt is added separately.
|
|
15
|
+
NEEDLES: tuple[tuple[str, str, str, tuple[str, ...]], ...] = (
|
|
16
|
+
(r"\bSerialize\b|\bDeserialize\b|#\[serde|serde::", "serde", "1", ("derive",)),
|
|
17
|
+
(r"serde_json::", "serde_json", "1", ("preserve_order",)), # dict order as in Python
|
|
18
|
+
(r"\bIndex(?:Map|Set)\b", "indexmap", "2", ("serde",)),
|
|
19
|
+
(r"\bToSchema\b|\bIntoParams\b|utoipa::", "utoipa", "5", ("uuid", "chrono", "indexmap")),
|
|
20
|
+
(r"\bchrono::", "chrono", "0.4", ("serde",)),
|
|
21
|
+
(r"\buuid::", "uuid", "1", ("serde", "v4")),
|
|
22
|
+
(r"\btokio::", "tokio", "1", ("rt", "time")),
|
|
23
|
+
(r"\btracing::", "tracing", "0.1", ()),
|
|
24
|
+
)
|
|
25
|
+
RT_VERSION = "0.1"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def required_crates(text: str, features: set[str]) -> dict[str, CrateSpec]:
|
|
29
|
+
"""Crates (with versions and features) the generated `text` uses, python2rust-rt included."""
|
|
30
|
+
out: dict[str, CrateSpec] = {}
|
|
31
|
+
for pattern, crate, version, feats in NEEDLES:
|
|
32
|
+
if re.search(pattern, text):
|
|
33
|
+
out[crate] = {"version": version, "features": list(feats)}
|
|
34
|
+
if re.search(r"\brt::|python2rust_rt", text):
|
|
35
|
+
out["python2rust-rt"] = {"version": RT_VERSION, "features": sorted(features)}
|
|
36
|
+
return dict(sorted(out.items()))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def render_dependencies(crates: dict[str, CrateSpec], rt_path: str | None = None) -> str:
|
|
40
|
+
"""A `[dependencies]` TOML block; `rt_path` points python2rust-rt at a local checkout."""
|
|
41
|
+
lines = ["[dependencies]"]
|
|
42
|
+
for name, spec in crates.items():
|
|
43
|
+
parts = (
|
|
44
|
+
[f'version = "{spec["version"]}"'] if not (name == "python2rust-rt" and rt_path) else []
|
|
45
|
+
)
|
|
46
|
+
if name == "python2rust-rt" and rt_path:
|
|
47
|
+
parts.append(f'path = "{rt_path}"')
|
|
48
|
+
if spec["features"]:
|
|
49
|
+
parts.append("features = [" + ", ".join(f'"{f}"' for f in spec["features"]) + "]")
|
|
50
|
+
lines.append(f"{name} = {{ {', '.join(parts)} }}")
|
|
51
|
+
return "\n".join(lines) + "\n"
|