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,675 @@
1
+ """Typed Rust IR with Python spans. Rust text is produced only by `emit`.
2
+
3
+ Expressions carry their Rust type (`ty`) so passes (ownership, source maps) never parse text.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ import copy
10
+ import dataclasses
11
+ from collections.abc import Iterator
12
+ from dataclasses import dataclass, field
13
+
14
+ from .rtypes import UNIT, UNKNOWN, RType
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Span:
19
+ file: str
20
+ line: int
21
+ col: int
22
+ end_line: int
23
+ end_col: int
24
+
25
+
26
+ def span_of(node: ast.AST | None, file: str) -> Span | None:
27
+ line = getattr(node, "lineno", None)
28
+ if node is None or not isinstance(line, int):
29
+ return None
30
+ col = getattr(node, "col_offset", 0)
31
+ return Span(
32
+ file,
33
+ line,
34
+ col,
35
+ getattr(node, "end_lineno", line) or line,
36
+ getattr(node, "end_col_offset", 0) or 0,
37
+ )
38
+
39
+
40
+ @dataclass(kw_only=True)
41
+ class Node:
42
+ span: Span | None = None
43
+
44
+
45
+ # -- patterns ---------------------------------------------------------------------------
46
+ @dataclass
47
+ class PVar(Node):
48
+ name: str
49
+ mut: bool = False
50
+
51
+
52
+ @dataclass
53
+ class PTuple(Node):
54
+ elems: list[Pat]
55
+
56
+
57
+ @dataclass
58
+ class PWild(Node):
59
+ pass
60
+
61
+
62
+ @dataclass
63
+ class PExpr(Node):
64
+ """A literal or path pattern (`3`, `"a"`, `Color::Red`)."""
65
+
66
+ expr: RExpr
67
+
68
+
69
+ @dataclass
70
+ class POr(Node):
71
+ alts: list[Pat]
72
+
73
+
74
+ @dataclass
75
+ class PBind(Node):
76
+ name: str
77
+ pat: Pat
78
+
79
+
80
+ Pat = PVar | PTuple | PWild | PExpr | POr | PBind
81
+
82
+
83
+ # -- expressions ------------------------------------------------------------------------
84
+ @dataclass(kw_only=True)
85
+ class Expr(Node):
86
+ ty: RType = UNKNOWN
87
+
88
+
89
+ LitValue = int | float | bool | str | bytes | None
90
+
91
+
92
+ @dataclass(kw_only=True)
93
+ class Lit(Expr):
94
+ kind: str # int float bool str none unit bytes
95
+ value: LitValue = None
96
+ suffixed: bool = (
97
+ False # print `1_i64` (arguments to closures whose parameter types are inferred)
98
+ )
99
+
100
+
101
+ @dataclass(kw_only=True)
102
+ class Var(Expr):
103
+ name: str
104
+
105
+
106
+ @dataclass(kw_only=True)
107
+ class Path(Expr):
108
+ path: str
109
+ borrowed: bool = False # a const/static item: moving it out needs a conversion
110
+
111
+
112
+ @dataclass(kw_only=True)
113
+ class Attr(Expr):
114
+ base: RExpr
115
+ name: str
116
+
117
+
118
+ @dataclass(kw_only=True)
119
+ class Index(Expr):
120
+ base: RExpr
121
+ index: RExpr
122
+
123
+
124
+ @dataclass(kw_only=True)
125
+ class Call(Expr):
126
+ func: RExpr
127
+ args: list[RExpr] = field(default_factory=list)
128
+
129
+
130
+ @dataclass(kw_only=True)
131
+ class Method(Expr):
132
+ recv: RExpr
133
+ name: str
134
+ args: list[RExpr] = field(default_factory=list)
135
+ turbofish: RType | None = None
136
+
137
+
138
+ @dataclass(kw_only=True)
139
+ class Macro(Expr):
140
+ """format/println/vec/vec_repeat/assert/matches/json."""
141
+
142
+ name: str
143
+ args: list[RExpr] = field(default_factory=list)
144
+ template: str | None = None
145
+ pat: Pat | None = None
146
+
147
+
148
+ @dataclass(kw_only=True)
149
+ class Un(Expr):
150
+ op: str
151
+ operand: RExpr
152
+
153
+
154
+ @dataclass(kw_only=True)
155
+ class Bin(Expr):
156
+ op: str
157
+ left: RExpr
158
+ right: RExpr
159
+
160
+
161
+ @dataclass(kw_only=True)
162
+ class Cast(Expr):
163
+ operand: RExpr
164
+
165
+
166
+ @dataclass(kw_only=True)
167
+ class Ref(Expr):
168
+ operand: RExpr
169
+ mut: bool = False
170
+ elide: bool = (
171
+ False # the operand is already a `&T` in Rust (literals, const items): print it as-is
172
+ )
173
+
174
+
175
+ @dataclass(kw_only=True)
176
+ class Deref(Expr):
177
+ operand: RExpr
178
+
179
+
180
+ @dataclass(kw_only=True)
181
+ class Borrow(Expr):
182
+ """`handle.borrow()` / `handle.borrow_mut()`: the VALUE a `Shared<T>` handle holds (ty: T)."""
183
+
184
+ operand: RExpr
185
+ mut: bool = False # decided by the ownership pass from how the value is used
186
+ deref: bool = False # `*handle.borrow()`: operands of operators
187
+
188
+
189
+ @dataclass(kw_only=True)
190
+ class Closure(Expr):
191
+ params: list[Pat] = field(default_factory=list)
192
+ body: RExpr
193
+ move: bool = False # the closure outlives the statement that makes it
194
+
195
+
196
+ @dataclass(kw_only=True)
197
+ class IfX(Expr):
198
+ cond: RExpr
199
+ then: RExpr
200
+ other: RExpr
201
+
202
+
203
+ @dataclass(kw_only=True)
204
+ class BlockX(Expr):
205
+ stmts: list[RStmt] = field(default_factory=list)
206
+ tail: RExpr | None = None
207
+ label: str | None = None # `'try1: { .. }`: `break 'try1 value` leaves the block (try lowering)
208
+
209
+
210
+ @dataclass(kw_only=True)
211
+ class TupleX(Expr):
212
+ elems: list[RExpr] = field(default_factory=list)
213
+
214
+
215
+ @dataclass(kw_only=True)
216
+ class ArrayX(Expr):
217
+ elems: list[RExpr] = field(default_factory=list)
218
+
219
+
220
+ @dataclass(kw_only=True)
221
+ class StructLit(Expr):
222
+ name: str
223
+ fields: list[tuple[str, RExpr]] = field(default_factory=list)
224
+ base: RExpr | None = None # `..base` struct update
225
+
226
+
227
+ @dataclass(kw_only=True)
228
+ class RangeX(Expr):
229
+ lo: RExpr
230
+ hi: RExpr
231
+ inclusive: bool = False
232
+
233
+
234
+ @dataclass(kw_only=True)
235
+ class Template(Expr):
236
+ """User-supplied Rust (library_map entries); `{0}`, `{1}` are replaced by the lowered args."""
237
+
238
+ template: str
239
+ args: list[RExpr] = field(default_factory=list)
240
+
241
+
242
+ @dataclass(kw_only=True)
243
+ class Question(Expr):
244
+ """Propagate an error: `operand?`, or, with a label, `match operand { Ok(v) => v, Err(e) => break 'label Err(e) }`."""
245
+
246
+ operand: RExpr
247
+ label: str | None = None
248
+
249
+
250
+ @dataclass(kw_only=True)
251
+ class CloneX(Expr):
252
+ operand: RExpr
253
+
254
+
255
+ @dataclass(kw_only=True)
256
+ class TodoX(Expr):
257
+ marker: str
258
+
259
+
260
+ # -- statements -------------------------------------------------------------------------
261
+ @dataclass
262
+ class Let(Node):
263
+ pat: Pat
264
+ ty: RType | None = None
265
+ init: RExpr | None = None
266
+
267
+
268
+ @dataclass
269
+ class Assign(Node):
270
+ lhs: RExpr
271
+ rhs: RExpr
272
+ op: str = "="
273
+
274
+
275
+ @dataclass
276
+ class ExprS(Node):
277
+ expr: RExpr
278
+
279
+
280
+ @dataclass
281
+ class Return(Node):
282
+ value: RExpr | None = None
283
+ tail: bool = False
284
+
285
+
286
+ @dataclass
287
+ class Break(Node):
288
+ label: str | None = None
289
+ value: RExpr | None = None
290
+
291
+
292
+ @dataclass
293
+ class Continue(Node):
294
+ pass
295
+
296
+
297
+ @dataclass
298
+ class IfS(Node):
299
+ cond: RExpr
300
+ then: list[RStmt]
301
+ other: list[RStmt] | None = None
302
+
303
+
304
+ @dataclass
305
+ class WhileS(Node):
306
+ cond: RExpr
307
+ body: list[RStmt]
308
+
309
+
310
+ @dataclass
311
+ class LoopS(Node):
312
+ body: list[RStmt]
313
+
314
+
315
+ @dataclass
316
+ class ForS(Node):
317
+ pat: Pat
318
+ iter: RExpr
319
+ body: list[RStmt]
320
+
321
+
322
+ @dataclass
323
+ class Arm(Node):
324
+ pat: Pat
325
+ body: list[RStmt]
326
+ guard: RExpr | None = None
327
+
328
+
329
+ @dataclass
330
+ class MatchS(Node):
331
+ subject: RExpr
332
+ arms: list[Arm]
333
+
334
+
335
+ @dataclass
336
+ class TodoS(Node):
337
+ marker: str
338
+
339
+
340
+ @dataclass
341
+ class CommentS(Node):
342
+ text: str
343
+
344
+
345
+ # -- items ------------------------------------------------------------------------------
346
+ @dataclass(frozen=True)
347
+ class Ident:
348
+ """A path/identifier value inside an attribute (`Query`, `Binary`, `Object`)."""
349
+
350
+ name: str
351
+
352
+
353
+ # str is a quoted string literal; a tuple is a nested list: `rename(serialize = "a")`
354
+ AttrValue = str | int | float | bool | RType | Ident | tuple
355
+ Arg = tuple[str, AttrValue | None] # (key, value) or (flag, None)
356
+
357
+
358
+ @dataclass
359
+ class Attribute:
360
+ """`#[name(key = value, flag, ...)]`: structured, rendered only by the emitter."""
361
+
362
+ name: str
363
+ args: list[Arg] = field(default_factory=list)
364
+
365
+
366
+ @dataclass
367
+ class FieldDef(Node):
368
+ name: str
369
+ ty: RType
370
+ doc: list[str] = field(default_factory=list)
371
+ attrs: list[Attribute] = field(default_factory=list)
372
+
373
+
374
+ @dataclass
375
+ class Struct(Node):
376
+ name: str
377
+ fields: list[FieldDef]
378
+ derives: list[str]
379
+ doc: list[str] = field(default_factory=list)
380
+ attrs: list[Attribute] = field(default_factory=list)
381
+ vis: str = "pub "
382
+ tuple_inner: RType | None = None # NewType: `struct X(pub T);`
383
+
384
+
385
+ @dataclass
386
+ class Variant(Node):
387
+ name: str
388
+ doc: list[str] = field(default_factory=list)
389
+ attrs: list[Attribute] = field(default_factory=list)
390
+ payload: RType | None = None
391
+ discriminant: str | None = None
392
+
393
+
394
+ @dataclass
395
+ class EnumDef(Node):
396
+ name: str
397
+ variants: list[Variant]
398
+ derives: list[str]
399
+ doc: list[str] = field(default_factory=list)
400
+ attrs: list[Attribute] = field(default_factory=list)
401
+ vis: str = "pub "
402
+
403
+
404
+ @dataclass
405
+ class Param:
406
+ name: str
407
+ ty: RType
408
+ mut: bool = False
409
+
410
+
411
+ @dataclass
412
+ class OperationParam:
413
+ name: str
414
+ ty: RType
415
+ location: str = "query" # path | query | header | cookie
416
+ required: bool = True
417
+ description: str | None = None
418
+
419
+
420
+ @dataclass
421
+ class Response:
422
+ status: int
423
+ description: str = ""
424
+ body: RType | None = None
425
+
426
+
427
+ @dataclass
428
+ class Operation:
429
+ """An HTTP operation (`#[utoipa::path]`). The 0.2 route frontend fills it; 0.1 only renders it."""
430
+
431
+ method: str
432
+ path: str
433
+ operation_id: str | None = None
434
+ tag: str | None = None
435
+ params: list[OperationParam] = field(default_factory=list)
436
+ request_body: RType | None = None
437
+ responses: list[Response] = field(default_factory=list)
438
+ security: list[str] = field(default_factory=list)
439
+
440
+
441
+ @dataclass
442
+ class Function(Node):
443
+ name: str
444
+ params: list[Param]
445
+ ret: RType = UNIT
446
+ body: list[RStmt] = field(default_factory=list)
447
+ doc: list[str] = field(default_factory=list)
448
+ vis: str = "pub "
449
+ is_async: bool = False
450
+ operation: Operation | None = None
451
+ decorators: list[Decorator] = field(default_factory=list)
452
+ attrs: list[Attribute] = field(default_factory=list) # e.g. `#[test]`
453
+
454
+
455
+ @dataclass
456
+ class Const(Node):
457
+ name: str
458
+ ty: RType
459
+ value: RExpr
460
+ kind: str = "const" # "const" or "static" (LazyLock)
461
+ vis: str = "pub "
462
+ doc: list[str] = field(default_factory=list)
463
+
464
+
465
+ @dataclass
466
+ class TypeAlias(Node):
467
+ name: str
468
+ target: RType
469
+ vis: str = "pub "
470
+
471
+
472
+ # -- 0.2 nodes: part of the IR now, lowered later ---------------------------------------
473
+ # ADR: exceptions. One crate-level error type, `PyError { kind: ExcKind, message, source }`, where
474
+ # `ExcKind` is GENERATED from the exception classes of the translated code: one variant per class
475
+ # (builtin ValueError/KeyError/... plus user subclasses) and `fn parent(self) -> Option<ExcKind>` /
476
+ # `fn is_a(self, ancestor: ExcKind) -> bool` generated from the class graph. Functions that can
477
+ # raise return `Result<T, PyError>`; `raise X(m)` is `return Err(PyError::new(ExcKind::X, m))`,
478
+ # calls to fallible functions use `?`, and `except A, B as e:` is a guard on `e.kind.is_a(A)`, so
479
+ # catching a base class catches subclasses exactly like Python. No per-module error enums. Raise
480
+ # sets are inferred by a pass over the IR (callee fixpoint), never by lowering. Until then the
481
+ # nodes below render as explicit `todo!()` with the stable codes PY2RS011/012/013/014/024/025/027.
482
+
483
+
484
+ @dataclass(kw_only=True)
485
+ class AwaitX(Expr):
486
+ operand: RExpr
487
+
488
+
489
+ @dataclass(kw_only=True)
490
+ class YieldX(Expr):
491
+ """`yield` / generator expression body (0.2: eager Vec or a stream, by use)."""
492
+
493
+ operand: RExpr | None = None
494
+
495
+
496
+ @dataclass
497
+ class Handler(Node):
498
+ kinds: list[str] # exception class names; empty = bare `except`
499
+ name: str | None
500
+ body: list[RStmt]
501
+
502
+
503
+ @dataclass
504
+ class TryS(Node):
505
+ body: list[RStmt]
506
+ handlers: list[Handler]
507
+ orelse: list[RStmt] = field(default_factory=list)
508
+ finalbody: list[RStmt] = field(default_factory=list)
509
+
510
+
511
+ @dataclass
512
+ class RaiseS(Node):
513
+ kind: str | None # None = bare `raise` (re-raise)
514
+ args: list[RExpr] = field(default_factory=list)
515
+ cause: RExpr | None = None
516
+
517
+
518
+ @dataclass
519
+ class WithS(Node):
520
+ items: list[tuple[RExpr, Pat | None]]
521
+ body: list[RStmt]
522
+ is_async: bool = False
523
+
524
+
525
+ @dataclass
526
+ class Decorator:
527
+ name: str
528
+ args: list[RExpr] = field(default_factory=list)
529
+
530
+
531
+ @dataclass
532
+ class ClassDef(Node):
533
+ """A plain class: fields, methods and bases (0.2: struct + impl, traits for protocols)."""
534
+
535
+ name: str
536
+ bases: list[str] = field(default_factory=list)
537
+ fields: list[FieldDef] = field(default_factory=list)
538
+ methods: list[Function] = field(default_factory=list)
539
+ decorators: list[Decorator] = field(default_factory=list)
540
+
541
+
542
+ @dataclass
543
+ class ModItem(Node):
544
+ """An inline module (`#[cfg(test)] mod tests { use super::*; ... }`)."""
545
+
546
+ name: str
547
+ items: list[Item]
548
+ attrs: list[Attribute] = field(default_factory=list)
549
+ uses: list[str] = field(default_factory=list)
550
+
551
+
552
+ @dataclass
553
+ class Validator(Node):
554
+ """A generated `deserialize_with` function applying Pydantic's rules (rt::pydantic)."""
555
+
556
+ name: str
557
+ ty: RType
558
+ rules: list[tuple[str, int | float | str | None]] = field(default_factory=list)
559
+
560
+
561
+ @dataclass
562
+ class WireImpl(Node):
563
+ """`impl From<rt::pydantic::Object<Wire>> for Target`: moves the fields of the private wire struct
564
+ (which derives Deserialize) into the public model, so the model itself rejects non-objects."""
565
+
566
+ target: str
567
+ wire: str
568
+ fields: list[str]
569
+
570
+
571
+ @dataclass
572
+ class TodoItem(Node):
573
+ """A TODO in item position (Rust has no todo!() there): rendered as a line comment."""
574
+
575
+ marker: str
576
+
577
+
578
+ @dataclass
579
+ class CommentItem(Node):
580
+ lines: list[str]
581
+
582
+
583
+ Item = (
584
+ Struct
585
+ | EnumDef
586
+ | Function
587
+ | Const
588
+ | TypeAlias
589
+ | TodoItem
590
+ | CommentItem
591
+ | ClassDef
592
+ | ModItem
593
+ | Validator
594
+ | WireImpl
595
+ )
596
+
597
+
598
+ @dataclass
599
+ class Module:
600
+ doc: list[str] = field(default_factory=list)
601
+ uses: list[str] = field(default_factory=list)
602
+ items: list[Item] = field(default_factory=list)
603
+ vendored_runtime: bool = False
604
+
605
+
606
+ # -- unions over every node (defined last: they name the 0.2 nodes too) --------------
607
+ RExpr = (
608
+ Lit | Var | Path | Attr | Index | Call | Method | Macro | Un | Bin | Cast | Ref | Deref | Borrow
609
+ | Closure | IfX | BlockX | TupleX | ArrayX | StructLit | RangeX | CloneX | Template | TodoX
610
+ | AwaitX | YieldX | Question
611
+ ) # fmt: skip
612
+
613
+ RStmt = (
614
+ Let
615
+ | Assign
616
+ | ExprS
617
+ | Return
618
+ | Break
619
+ | Continue
620
+ | IfS
621
+ | WhileS
622
+ | LoopS
623
+ | ForS
624
+ | MatchS
625
+ | TodoS
626
+ | CommentS
627
+ | TryS
628
+ | RaiseS
629
+ | WithS
630
+ )
631
+
632
+
633
+ # -- small builders ---------------------------------------------------------------------
634
+ def lit(kind: str, value: LitValue, ty: RType, span: Span | None = None) -> Lit:
635
+ return Lit(kind=kind, value=value, ty=ty, span=span)
636
+
637
+
638
+ def method(
639
+ recv: RExpr, name: str, *args: RExpr, ty: RType = UNKNOWN, turbofish: RType | None = None
640
+ ) -> Method:
641
+ return Method(recv=recv, name=name, args=list(args), turbofish=turbofish, ty=ty, span=recv.span)
642
+
643
+
644
+ def rt(name: str, *args: RExpr, ty: RType = UNKNOWN) -> Call:
645
+ """Call into the python2rust-rt runtime crate (imported as `rt`)."""
646
+ return Call(func=Path(path=f"rt::{name}"), args=list(args), ty=ty)
647
+
648
+
649
+ def walk(node: object) -> Iterator[object]:
650
+ """Every IR node below `node` (and `node` itself), depth first."""
651
+ if isinstance(node, list | tuple):
652
+ for item in node:
653
+ yield from walk(item)
654
+ elif dataclasses.is_dataclass(node) and not isinstance(node, type):
655
+ yield node
656
+ for f in dataclasses.fields(node):
657
+ yield from walk(getattr(node, f.name))
658
+
659
+
660
+ def is_place(e: RExpr) -> bool:
661
+ return isinstance(e, (Var, Attr, Index, Borrow)) or (
662
+ isinstance(e, Deref) and is_place(e.operand)
663
+ )
664
+
665
+
666
+ def dup(e: RExpr) -> RExpr:
667
+ """An independent copy: passes mutate nodes in place, so a node must never appear twice."""
668
+ return copy.deepcopy(e)
669
+
670
+
671
+ def lit_int(e: object) -> int | None:
672
+ """The value of an integer literal, else None."""
673
+ if isinstance(e, Lit) and e.kind == "int" and isinstance(e.value, int):
674
+ return e.value
675
+ return None