python2rust 0.1.0__py3-none-any.whl → 0.1.1__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 CHANGED
@@ -4,5 +4,5 @@ Importing this package is deliberately cheap. The translator core (`python2rust.
4
4
  and the optional MCP SDK are imported lazily by the commands that need them.
5
5
  """
6
6
 
7
- __version__ = "0.1.0"
7
+ __version__ = "0.1.1"
8
8
  __all__ = ["__version__"]
@@ -8,10 +8,12 @@ from __future__ import annotations
8
8
 
9
9
  import math
10
10
  import re
11
+ from dataclasses import replace
11
12
  from typing import TypedDict
12
13
 
13
14
  from ..diagnostics import rust_escape
14
15
  from ..ir import nodes as ir
16
+ from ..ir.rtypes import RType
15
17
  from .schema import operation_attr
16
18
 
17
19
  MARK = "//@py "
@@ -319,7 +321,10 @@ def stmt_lines(s: ir.RStmt, item: str) -> list[str]:
319
321
 
320
322
 
321
323
  def _if(s: ir.IfS, item: str) -> list[str]:
322
- lines = [f"if {head(s.cond)} {{", *_body(s.then, item), "}"]
324
+ condition = head(s.cond)
325
+ if s.binding is not None:
326
+ condition = f"let {pat(s.binding)} = {condition}"
327
+ lines = [f"if {condition} {{", *_body(s.then, item), "}"]
323
328
  if s.other is None:
324
329
  return lines
325
330
  if len(s.other) == 1 and isinstance(s.other[0], ir.IfS):
@@ -501,12 +506,51 @@ def _auto_uses(body: str) -> list[str]:
501
506
  SET_TYPES = {"indexset": "IndexSet", "btreeset": "BTreeSet", "hashset": "HashSet"}
502
507
 
503
508
 
509
+ def _type_complexity(ty: RType, depth: int = 1) -> int:
510
+ if ty.name in ("&", "&mut"):
511
+ return 1 + _type_complexity(ty.args[0], depth)
512
+ return 10 * depth + sum(_type_complexity(arg, depth + 1) for arg in ty.args)
513
+
514
+
515
+ def _alias_signatures(module: ir.Module) -> list[ir.Item]:
516
+ used = {getattr(item, "name", "") for item in module.items}
517
+ used.update(re.findall(r"\w+", "\n".join(module.uses)))
518
+ aliases: dict[RType, str] = {}
519
+ items: list[ir.Item] = []
520
+ index = 0
521
+
522
+ def shorten(ty: RType) -> RType:
523
+ nonlocal index
524
+ # Clippy's default threshold for owned paths and tuples is 250.
525
+ if _type_complexity(ty) <= 250 or not ty.known or "&" in ty.rust():
526
+ return ty
527
+ if ty not in aliases:
528
+ while True:
529
+ index += 1
530
+ name = f"Py2rsSignature{index}"
531
+ if name not in used:
532
+ break
533
+ aliases[ty] = name
534
+ items.append(ir.TypeAlias(name, ty))
535
+ return RType(aliases[ty])
536
+
537
+ for item in module.items:
538
+ if isinstance(item, ir.Function):
539
+ item = replace(
540
+ item,
541
+ params=[replace(param, ty=shorten(param.ty)) for param in item.params],
542
+ ret=shorten(item.ret),
543
+ )
544
+ items.append(item)
545
+ return items
546
+
547
+
504
548
  def render_module(
505
549
  module: ir.Module, path: str, runtime: str | None = None, set_type: str = "indexset"
506
550
  ) -> str:
507
551
  """Render `module` (with source-map markers); `use` lines come from the names the body mentions."""
508
552
  body: list[str] = []
509
- for item in module.items:
553
+ for item in _alias_signatures(module):
510
554
  if body:
511
555
  body.append("")
512
556
  body += item_lines(item)
@@ -299,6 +299,7 @@ class IfS(Node):
299
299
  cond: RExpr
300
300
  then: list[RStmt]
301
301
  other: list[RStmt] | None = None
302
+ binding: Pat | None = None
302
303
 
303
304
 
304
305
  @dataclass
@@ -209,6 +209,12 @@ class ExprLowerer(Lowerer):
209
209
  def expr_BinOp(self, node: ast.BinOp) -> ir.RExpr:
210
210
  a, b = self.expr(node.left), self.expr(node.right)
211
211
  op = type(node.op)
212
+ if (
213
+ op is ast.BitOr
214
+ and isinstance(node.left, (ast.Dict, ast.DictComp))
215
+ and peel(a.ty).name == peel(b.ty).name == MAP
216
+ ):
217
+ return self._merge_dict_items([(None, a), (None, b)], node)
212
218
  special = self._seq_op(node, op, a, b)
213
219
  if special:
214
220
  return special
@@ -508,7 +514,7 @@ class ExprLowerer(Lowerer):
508
514
 
509
515
  def expr_Dict(self, node: ast.Dict) -> ir.RExpr:
510
516
  if any(k is None for k in node.keys):
511
- raise Unsupported("PY2RS034", "dict unpacking **x in a literal", node)
517
+ return self._dict_unpack(node)
512
518
  keys, kt = self._elements([k for k in node.keys if k is not None])
513
519
  vals, vt = self._elements(node.values)
514
520
  if not keys:
@@ -519,12 +525,94 @@ class ExprLowerer(Lowerer):
519
525
  )
520
526
  return ir.Call(func=ir.Path(path=f"{MAP}::from"), args=[pairs], ty=T(MAP, kt, vt))
521
527
 
528
+ def _dict_unpack(self, node: ast.Dict) -> ir.RExpr:
529
+ items = [
530
+ (key, value)
531
+ for key, value in zip(node.keys, node.values, strict=True)
532
+ if key is not None or not (isinstance(value, ast.Dict) and not value.keys)
533
+ ]
534
+ if all(key is not None for key, _ in items):
535
+ literal = ast.Dict(keys=[key for key, _ in items], values=[value for _, value in items])
536
+ return self.expr_Dict(ast.copy_location(literal, node))
537
+ entries = [
538
+ (self.expr(key) if key is not None else None, self.expr(value)) for key, value in items
539
+ ]
540
+ return self._merge_dict_items(entries, node)
541
+
542
+ def _merge_dict_items(
543
+ self, entries: list[tuple[ir.RExpr | None, ir.RExpr]], node: ast.expr
544
+ ) -> ir.RExpr:
545
+ mappings = [peel(value.ty) for key, value in entries if key is None]
546
+ ty = mappings[0]
547
+ if (
548
+ ty.name != MAP
549
+ or not ty.known
550
+ or arg(ty) not in (STR, INT, BOOL)
551
+ or any(other != ty for other in mappings)
552
+ ):
553
+ raise Unsupported(
554
+ "PY2RS034", "dict merge needs one known map type with scalar keys", node
555
+ )
556
+
557
+ def staged(expr: ir.RExpr, stored: RType) -> ir.RExpr:
558
+ if not any(isinstance(part, ir.Borrow) for part in ir.walk(expr)):
559
+ return expr
560
+ # Drop temporary guards before evaluating the next Python operand.
561
+ return ir.BlockX(
562
+ stmts=[ir.Let(ir.PVar("item"), stored, expr)],
563
+ tail=ir.Var(name="item", ty=stored),
564
+ ty=stored,
565
+ )
566
+
567
+ if len(entries) == 1:
568
+ return staged(ir.CloneX(operand=entries[0][1], ty=ty), ty)
569
+ key_ty, value_ty = ty.args
570
+ iterator_ty = T("Iter", T("tuple", key_ty, value_ty))
571
+ sources: list[ir.RExpr] = []
572
+ for key, value in entries:
573
+ if key is None:
574
+ snapshot = ir.CloneX(operand=value, ty=ty)
575
+ sources.append(ir.method(staged(snapshot, ty), "into_iter", ty=iterator_ty))
576
+ continue
577
+ if key_ty != peel(key.ty) or (
578
+ value_ty != VALUE and not compatible(value_ty, peel(value.ty))
579
+ ):
580
+ raise Unsupported(
581
+ "PY2RS034", "dict item does not match the unpacked map type", node
582
+ )
583
+ pair = ir.TupleX(
584
+ elems=[
585
+ staged(self.coerce(key, key_ty), key_ty),
586
+ staged(self.coerce(value, value_ty), value_ty),
587
+ ],
588
+ ty=T("tuple", key_ty, value_ty),
589
+ )
590
+ sources.append(
591
+ ir.Call(func=ir.Path(path="std::iter::once"), args=[pair], ty=iterator_ty)
592
+ )
593
+ ordered = sources[0]
594
+ for source in sources[1:]:
595
+ ordered = ir.method(ordered, "chain", source, ty=iterator_ty)
596
+ return ir.method(ordered, "collect", ty=ty, turbofish=ty)
597
+
522
598
  def expr_Subscript(self, node: ast.Subscript) -> ir.RExpr:
523
599
  base = self.expr(node.value)
524
600
  if isinstance(node.slice, ast.Slice):
525
601
  return self._slice(node, base, node.slice)
526
602
  index = self.expr(node.slice)
527
603
  tb, ti = peel(base.ty), peel(index.ty)
604
+ model = self.ctx.model_by_rust(tb.name)
605
+ if (
606
+ model is not None
607
+ and model.source == "typeddict"
608
+ and isinstance(node.ctx, ast.Load)
609
+ and isinstance(node.slice, ast.Constant)
610
+ and isinstance(node.slice.value, str)
611
+ ):
612
+ field = model.fields.get(node.slice.value)
613
+ if field is not None and field.default is None and field.ty.known:
614
+ return ir.Attr(base=base, name=field.rust, ty=field.ty)
615
+ raise Unsupported("PY2RS019", "indexing a TypedDict key that may be absent", node)
528
616
  if tb.name == MAP and self.catches("KeyError"):
529
617
  found = ir.method(ir.method(base, "get", self.ref_of(index)), "cloned")
530
618
  absent = ir.Closure(params=[], body=ir.rt("key_error", ir.Ref(operand=ir.dup(index))))
@@ -50,16 +50,76 @@ def _root(node: ast.expr) -> str | None:
50
50
  return node.id if isinstance(node, ast.Name) else None
51
51
 
52
52
 
53
+ def _keeps_non_null(body: list[ast.stmt], name: str, *, allow_terminal_reset: bool = True) -> bool:
54
+ for index, stmt in enumerate(body):
55
+ if (
56
+ allow_terminal_reset
57
+ and index == len(body) - 2
58
+ and isinstance(body[-1], (ast.Break, ast.Continue))
59
+ and isinstance(stmt, ast.Assign)
60
+ and len(stmt.targets) == 1
61
+ and isinstance(stmt.targets[0], ast.Name)
62
+ and stmt.targets[0].id == name
63
+ and isinstance(stmt.value, ast.Constant)
64
+ and stmt.value.value is None
65
+ ):
66
+ continue # No subsequent read on this path before the guard runs again.
67
+ if isinstance(stmt, ast.If):
68
+ nodes = ast.walk(stmt.test)
69
+ if not (
70
+ _keeps_non_null(stmt.body, name, allow_terminal_reset=allow_terminal_reset)
71
+ and _keeps_non_null(stmt.orelse, name, allow_terminal_reset=allow_terminal_reset)
72
+ ):
73
+ return False
74
+ else:
75
+ nodes = ast.walk(stmt)
76
+ for node in nodes:
77
+ if (
78
+ isinstance(node, ast.Name)
79
+ and node.id == name
80
+ and not isinstance(node.ctx, ast.Load)
81
+ ):
82
+ return False
83
+ if isinstance(node, (ast.Lambda, ast.GeneratorExp, ast.Global, ast.Nonlocal)):
84
+ return False
85
+ if (
86
+ isinstance(node, (ast.ExceptHandler, ast.MatchAs, ast.MatchStar))
87
+ and node.name == name
88
+ ):
89
+ return False
90
+ if isinstance(node, ast.MatchMapping) and node.rest == name:
91
+ return False
92
+ if (
93
+ isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))
94
+ and node.name == name
95
+ ):
96
+ return False
97
+ if isinstance(node, ast.alias) and (node.asname or node.name.split(".")[0]) in (
98
+ name,
99
+ "*",
100
+ ):
101
+ return False
102
+ return True
103
+
104
+
53
105
  class StmtLowerer(ExceptionLowerer):
54
106
  def __init__(self, *a, **kw) -> None:
55
107
  super().__init__(*a, **kw)
56
108
  self.hoisted: dict[str, Var] = {}
57
109
  self.leaky: set[str] = set()
58
- self.reassigned: set[str] = set() # names bound more than once (no type narrowing)
110
+ self.reassigned: set[str] = set() # names bound more than once
111
+ self.non_null: dict[str, Var] = {}
59
112
  self._tmp = 0
60
113
 
61
114
  # -- blocks ---------------------------------------------------------------------------
62
115
  def block(self, stmts: list[ast.stmt], tail: bool = False, after: int = 0) -> list[ir.RStmt]:
116
+ before = self.non_null
117
+ try:
118
+ return self._block(stmts, tail, after)
119
+ finally:
120
+ self.non_null = before
121
+
122
+ def _block(self, stmts: list[ast.stmt], tail: bool, after: int) -> list[ir.RStmt]:
63
123
  out: list[ir.RStmt] = []
64
124
  prev = after
65
125
  for i, s in enumerate(stmts):
@@ -82,8 +142,26 @@ class StmtLowerer(ExceptionLowerer):
82
142
  if st.span is None:
83
143
  st.span = self.sp(s)
84
144
  out += made
145
+ if isinstance(s, ast.Assign) and len(s.targets) == 1 and i + 1 < len(stmts):
146
+ self._narrow_assignment(s.targets[0], made, stmts[i + 1 :])
85
147
  return out
86
148
 
149
+ def _narrow_assignment(
150
+ self, target: ast.expr, lowered: list[ir.RStmt], following: list[ast.stmt]
151
+ ) -> None:
152
+ if not isinstance(target, ast.Name):
153
+ return
154
+ match lowered:
155
+ case [ir.Assign(lhs=ir.Var(ty=ty), rhs=ir.Call(func=ir.Path(path="Some")))]:
156
+ var = self.lookup(target.id)
157
+ if (
158
+ var is not None
159
+ and ty.name == "Option"
160
+ and arg(ty) in (STR, INT, FLOAT, BOOL)
161
+ and _keeps_non_null(following, target.id)
162
+ ):
163
+ self.non_null = {**self.non_null, target.id: var}
164
+
87
165
  def _failed(
88
166
  self, s: ast.stmt, code: str, construct: str, node: ast.AST | None, hint: str | None
89
167
  ) -> list[ir.RStmt]:
@@ -452,8 +530,10 @@ class StmtLowerer(ExceptionLowerer):
452
530
  def _lets(self, binds: list[tuple[str, ast.expr]]) -> list[ir.RStmt]:
453
531
  return [st for name, value in binds for st in self.bind(name, self.expr(value))]
454
532
 
455
- def _narrowable(self, test: ast.expr, op: type) -> tuple[str, Var] | None:
456
- """`x is None` / `x is not None` where x is an Option local that is never reassigned."""
533
+ def _narrowable(
534
+ self, test: ast.expr, op: type, *, scoped: bool = False
535
+ ) -> tuple[str, Var] | None:
536
+ """Find a simple None comparison on a local Option."""
457
537
  if not (
458
538
  isinstance(test, ast.Compare)
459
539
  and len(test.ops) == 1
@@ -464,7 +544,11 @@ class StmtLowerer(ExceptionLowerer):
464
544
  ):
465
545
  return None
466
546
  var = self.lookup(test.left.id)
467
- if var is None or var.ty.name != "Option" or test.left.id in self.reassigned:
547
+ if (
548
+ var is None
549
+ or var.ty.name != "Option"
550
+ or (not scoped and test.left.id in self.reassigned)
551
+ ):
468
552
  return None
469
553
  return test.left.id, var
470
554
 
@@ -497,9 +581,61 @@ class StmtLowerer(ExceptionLowerer):
497
581
  binds, test = self._hoist(s.test, True, s)
498
582
  return [*self._lets(binds), self._if_chain(s, test)]
499
583
 
584
+ def expr_Name(self, node: ast.Name) -> ir.RExpr:
585
+ value = super().expr_Name(node)
586
+ var = self.non_null.get(node.id)
587
+ if var is not None and self.lookup(node.id) is var:
588
+ return expect(ir.CloneX(operand=value, ty=var.ty), "checked non-None", arg(var.ty))
589
+ return value
590
+
591
+ def _if_body(self, s: ast.If, test: ast.expr) -> list[ir.RStmt]:
592
+ found = self._narrowable(test, ast.IsNot, scoped=True)
593
+ if found is None:
594
+ return self.scoped(s.body, s.lineno)
595
+ name, var = found
596
+ if arg(var.ty) not in (STR, INT, FLOAT, BOOL) or not _keeps_non_null(s.body, name):
597
+ return self.scoped(s.body, s.lineno)
598
+ before = self.non_null
599
+ self.non_null = {**before, name: var}
600
+ try:
601
+ return self.scoped(s.body, s.lineno)
602
+ finally:
603
+ self.non_null = before
604
+
605
+ def _regex_guard(
606
+ self, s: ast.If, test: ast.expr
607
+ ) -> tuple[ir.RExpr, ir.Pat, list[ir.RStmt]] | None:
608
+ if not isinstance(test, ast.Name):
609
+ return None
610
+ name = test.id
611
+ var = self.lookup(name)
612
+ match_ty = T("rt::re::Match")
613
+ if var is None or var.ty != T("Option", match_ty):
614
+ return None
615
+ if not _keeps_non_null(s.body, name, allow_terminal_reset=False):
616
+ return None
617
+ if not any(
618
+ isinstance(node, ast.Name) and node.id == name
619
+ for stmt in s.body
620
+ for node in ast.walk(stmt)
621
+ ):
622
+ return None
623
+ self.push()
624
+ try:
625
+ bound = self.var(self.declare(name, match_ty))
626
+ body = self.block(s.body, after=s.lineno)
627
+ finally:
628
+ self.pop()
629
+ subject = ir.CloneX(operand=self.var(var), ty=var.ty)
630
+ binding = ir.PExpr(ir.Call(func=ir.Path(path="Some"), args=[bound]))
631
+ return subject, binding, body
632
+
500
633
  def _if_chain(self, s: ast.If, test: ast.expr) -> ir.IfS:
501
- cond = self.cond(test)
502
- then = self.scoped(s.body, s.lineno)
634
+ guard = self._regex_guard(s, test)
635
+ if guard is None:
636
+ cond, binding, then = self.cond(test), None, self._if_body(s, test)
637
+ else:
638
+ cond, binding, then = guard
503
639
  other: list[ir.RStmt] | None = None
504
640
  if len(s.orelse) == 1 and isinstance(s.orelse[0], ast.If):
505
641
  nested = s.orelse[0]
@@ -507,7 +643,7 @@ class StmtLowerer(ExceptionLowerer):
507
643
  other[0].span = self.sp(nested)
508
644
  elif s.orelse:
509
645
  other = self.scoped(s.orelse, s.body[-1].end_lineno or s.lineno)
510
- return ir.IfS(cond, then, other)
646
+ return ir.IfS(cond, then, other, binding)
511
647
 
512
648
  def st_While(self, s: ast.While) -> list[ir.RStmt]:
513
649
  if s.orelse:
@@ -186,8 +186,19 @@ pub fn str_slice(s: &str, start: Option<i64>, stop: Option<i64>) -> String {
186
186
  }
187
187
 
188
188
  pub fn str_index(s: &str, i: i64) -> String {
189
- let chars: Vec<char> = s.chars().collect();
190
- chars[idx_in(i, chars.len(), "string")].to_string()
189
+ str_item(s, i).unwrap_or_else(|| panic!("IndexError: string index out of range")).to_string()
190
+ }
191
+
192
+ fn str_item(s: &str, i: i64) -> Option<char> {
193
+ let offset = usize::try_from(if i < 0 { i.unsigned_abs() - 1 } else { i as u64 }).ok()?;
194
+ if s.is_ascii() {
195
+ let index = if i < 0 { s.len().checked_sub(offset.checked_add(1)?)? } else { offset };
196
+ s.as_bytes().get(index).map(|&c| c as char)
197
+ } else if i < 0 {
198
+ s.chars().nth_back(offset)
199
+ } else {
200
+ s.chars().nth(offset)
201
+ }
191
202
  }
192
203
 
193
204
  /// Index (in characters) of the first occurrence of `sub`, or -1.
@@ -529,8 +540,9 @@ fn try_idx_in(i: i64, len: usize, message: &'static str) -> Result<usize, PyErro
529
540
  }
530
541
 
531
542
  pub fn try_str_item(s: &str, i: i64) -> Result<String, PyError> {
532
- let chars: Vec<char> = s.chars().collect();
533
- Ok(chars[try_idx_in(i, chars.len(), "string index out of range")?].to_string())
543
+ str_item(s, i)
544
+ .map(|c| c.to_string())
545
+ .ok_or_else(|| PyError::new(&kinds::INDEX_ERROR, "string index out of range"))
534
546
  }
535
547
 
536
548
  pub fn try_floordiv(a: i64, b: i64) -> Result<i64, PyError> {
@@ -970,16 +982,54 @@ pub mod b64 {
970
982
  base64::engine::general_purpose::URL_SAFE.encode(data).into_bytes()
971
983
  }
972
984
 
985
+ // Python's default decoder skips non-alphabet bytes and stops at a padded quantum.
986
+ fn permissive_decode(data: &[u8], urlsafe: bool) -> Result<Vec<u8>, PyError> {
987
+ let mut output = Vec::new();
988
+ let mut bits = 0u32;
989
+ let mut count = 0usize;
990
+ let mut padding = 0usize;
991
+ for &byte in data {
992
+ let value = match byte {
993
+ b'A'..=b'Z' => byte - b'A',
994
+ b'a'..=b'z' => byte - b'a' + 26,
995
+ b'0'..=b'9' => byte - b'0' + 52,
996
+ b'+' => 62,
997
+ b'/' => 63,
998
+ b'-' if urlsafe => 62,
999
+ b'_' if urlsafe => 63,
1000
+ b'=' => {
1001
+ padding += 1;
1002
+ if (count == 2 && padding >= 2) || count == 3 {
1003
+ return Ok(output);
1004
+ }
1005
+ continue;
1006
+ }
1007
+ _ => continue,
1008
+ };
1009
+ padding = 0;
1010
+ bits = (bits << 6) | u32::from(value);
1011
+ count += 1;
1012
+ if count >= 2 {
1013
+ output.push((bits >> (2 * (4 - count))) as u8);
1014
+ }
1015
+ if count == 4 {
1016
+ bits = 0;
1017
+ count = 0;
1018
+ }
1019
+ }
1020
+ if count == 0 {
1021
+ Ok(output)
1022
+ } else {
1023
+ Err(PyError::new(&kinds::VALUE_ERROR, "Incorrect padding".to_string()))
1024
+ }
1025
+ }
1026
+
973
1027
  pub fn decode(data: &[u8]) -> Result<Vec<u8>, PyError> {
974
- base64::engine::general_purpose::STANDARD
975
- .decode(data)
976
- .map_err(|e| PyError::new(&kinds::VALUE_ERROR, e.to_string()))
1028
+ permissive_decode(data, false)
977
1029
  }
978
1030
 
979
1031
  pub fn urlsafe_decode(data: &[u8]) -> Result<Vec<u8>, PyError> {
980
- base64::engine::general_purpose::URL_SAFE
981
- .decode(data)
982
- .map_err(|e| PyError::new(&kinds::VALUE_ERROR, e.to_string()))
1032
+ permissive_decode(data, true)
983
1033
  }
984
1034
  }
985
1035
 
@@ -1703,7 +1753,22 @@ mod b64_tests {
1703
1753
  assert_eq!(b64::encode(b"hello?>"), b"aGVsbG8/Pg==");
1704
1754
  assert_eq!(b64::urlsafe_encode(b"hello?>"), b"aGVsbG8_Pg==");
1705
1755
  assert_eq!(b64::decode(b"aGVsbG8/Pg==").unwrap(), b"hello?>");
1706
- assert!(b64::decode(b"!!").is_err());
1756
+ assert_eq!(b64::decode(b"!!").unwrap(), b"");
1757
+ for (input, expected) in [
1758
+ (b"=Y!Q===ignored".as_slice(), b"a".as_slice()),
1759
+ (b"YR==".as_slice(), b"a".as_slice()),
1760
+ (b"Y=Q==".as_slice(), b"a".as_slice()),
1761
+ (b"YW=Jj".as_slice(), b"abc".as_slice()),
1762
+ (b"//8=".as_slice(), &[255, 255][..]),
1763
+ ] {
1764
+ assert_eq!(b64::decode(input).unwrap(), expected);
1765
+ }
1766
+ for input in [b"Y".as_slice(), b"YQ", b"YQ=", b"YWJ"] {
1767
+ assert!(b64::decode(input).is_err());
1768
+ }
1769
+ assert_eq!(b64::urlsafe_decode(b"__8=").unwrap(), [255, 255]);
1770
+ assert_eq!(b64::urlsafe_decode(b"//8=").unwrap(), [255, 255]);
1771
+ assert!(b64::decode(b"__8=").is_err());
1707
1772
  }
1708
1773
  }
1709
1774
 
@@ -2003,6 +2068,27 @@ mod tests {
2003
2068
  assert_eq!(idx(0, 3), 0);
2004
2069
  }
2005
2070
 
2071
+ #[test]
2072
+ fn string_indices_handle_unicode_and_bounds() {
2073
+ for text in ["", "abc", "aé🦀e\u{301}"] {
2074
+ let chars: Vec<char> = text.chars().collect();
2075
+ for i in -(chars.len() as i64)..chars.len() as i64 {
2076
+ let expected = chars[idx_in(i, chars.len(), "string")].to_string();
2077
+ assert_eq!(str_index(text, i), expected);
2078
+ assert_eq!(try_str_item(text, i).unwrap(), expected);
2079
+ }
2080
+ for i in [i64::MIN, -(chars.len() as i64) - 1, chars.len() as i64, i64::MAX] {
2081
+ let error = try_str_item(text, i).unwrap_err();
2082
+ assert_eq!(error.kind.name, "IndexError");
2083
+ assert_eq!(error.message, "string index out of range");
2084
+ let panic = std::panic::catch_unwind(|| str_index(text, i)).unwrap_err();
2085
+ let message = panic.downcast_ref::<String>().map(String::as_str)
2086
+ .or_else(|| panic.downcast_ref::<&str>().copied());
2087
+ assert_eq!(message, Some("IndexError: string index out of range"));
2088
+ }
2089
+ }
2090
+ }
2091
+
2006
2092
  #[test]
2007
2093
  #[should_panic(expected = "IndexError")]
2008
2094
  fn out_of_range_index_panics() {
@@ -676,7 +676,7 @@ DEFAULT_DEPS: dict[str, Any] = {
676
676
  # crate enables exactly the ones the translation reports in `required_features`.
677
677
  _RT_MANIFEST = """[package]
678
678
  name = "python2rust-rt"
679
- version = "0.1.0"
679
+ version = "0.1.1"
680
680
  edition = "2024"
681
681
  publish = false
682
682
 
@@ -27,6 +27,7 @@ _FN = re.compile(
27
27
  r"fn\s+(?:r#)?(?P<name>\w+)\s*(?P<gen><)?",
28
28
  re.M,
29
29
  )
30
+ _SIGNATURE_ALIAS = re.compile(r"^pub type (Py2rsSignature\d+)\s*=\s*([^;]+);", re.M)
30
31
 
31
32
 
32
33
  @dataclass
@@ -75,6 +76,7 @@ def snake(name: str) -> str:
75
76
  def find_rust_fn(rust: str, py_name: str) -> RustSig:
76
77
  """The top-level Rust function made from Python function `py_name`; raises `Unsupported`."""
77
78
  clean = strip_noise(rust)
79
+ aliases = dict(_SIGNATURE_ALIAS.findall(clean))
78
80
  wanted = {py_name, snake(py_name)}
79
81
  for m in _FN.finditer(clean):
80
82
  if m.group("name") not in wanted:
@@ -97,11 +99,15 @@ def find_rust_fn(rust: str, py_name: str) -> RustSig:
97
99
  if re.fullmatch(r"(?:&\s*(?:mut\s+)?)?(?:mut\s+)?self(?:\s*:.*)?", part):
98
100
  raise Unsupported("method (takes self)")
99
101
  pname, _, ptype = part.partition(":")
100
- params.append((pname.replace("mut ", "").strip(), parse_rust_type(ptype)))
102
+ ptype = ptype.strip()
103
+ params.append(
104
+ (pname.replace("mut ", "").strip(), parse_rust_type(aliases.get(ptype, ptype)))
105
+ )
101
106
  end = _match(clean, brace, "{", "}") if brace >= 0 else -1
102
107
  text = rust[m.start() : end + 1] if end > 0 else rust[m.start() : close_at + 1]
103
108
  ident = f"r#{name}" if name in _KEYWORDS else name
104
- return RustSig(name, params, parse_rust_type(ret_text), text, bool(m.group("vis")), ident)
109
+ ret = parse_rust_type(aliases.get(ret_text, ret_text))
110
+ return RustSig(name, params, ret, text, bool(m.group("vis")), ident)
105
111
  raise Unsupported(f"no top-level Rust function named {py_name}")
106
112
 
107
113
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python2rust
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Typed-Python to Rust transpiler built to be driven by AI agents: machine-readable diagnostics, loud TODOs, a validation loop.
5
5
  Keywords: python,rust,transpiler,ai-agents,mcp,code-migration
6
6
  Author: BMS Suisse
@@ -51,7 +51,7 @@ to an agent as a precise, machine-readable task.
51
51
 
52
52
  </div>
53
53
 
54
- > **Alpha, work in progress, not yet on PyPI.** Pydantic models, dataclasses, enums, typed functions, exceptions
54
+ > **Alpha, available on PyPI.** Pydantic models, dataclasses, enums, typed functions, exceptions
55
55
  > (`try`/`except`/`raise`), basic `async`/`await` and multi-module projects (a directory becomes one crate)
56
56
  > translate, with `utoipa` schemas, source maps and a checked-output runtime crate. Classes, generators, decorators,
57
57
  > most of the async library (`gather`, tasks, locks) and most third-party libraries are still explicit `todo!()`s
@@ -1,4 +1,4 @@
1
- python2rust/__init__.py,sha256=sW9Of3zMlA5brmQBG1XoE_a3HaWDTbc95Oej1WzzhQM,301
1
+ python2rust/__init__.py,sha256=CjUT17tpDch8mBOWLMXvAPT0mrMDcVROQj-zAzbJddc,301
2
2
  python2rust/__main__.py,sha256=0b_gUaWqrlZemtb9rUrcyLrQLmI8Bt0Au_opxzzDs3c,68
3
3
  python2rust/_core.py,sha256=H3SBJLarBQ390mPvEwa_fOcDUI10DCIict4cAJuSP6k,1514
4
4
  python2rust/agent/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -24,7 +24,7 @@ python2rust/core/constructs.py,sha256=wgbZQ0CUHarOAsS3CfuAhvCf-Fp1Cbj1Z1Et0Bum0H
24
24
  python2rust/core/diagnostics.py,sha256=qP5uD9PVh9BGt5QxF1qmnu_ovbWXzJP5cSiAbOMM3rQ,13939
25
25
  python2rust/core/emit/__init__.py,sha256=-FhPfNXSs_lEnaz3zk9uSKAr9i9PnXZYJSwQRl2qJ64,222
26
26
  python2rust/core/emit/crates.py,sha256=CNK0ih4BLLo8HK9F91pXGcRsJwSIOd1JUf3Bo0g2X5Q,2198
27
- python2rust/core/emit/render.py,sha256=GqJxobSyst6gs2YlqC8cJueX_zypaakLWIrKKhc_vcI,21073
27
+ python2rust/core/emit/render.py,sha256=dy1kK70xOQWvUcOp0drt4fpBfEBr2-6xBW7ZTi9yCC4,22598
28
28
  python2rust/core/emit/schema.py,sha256=GqnRhcVpP9o4Nr1Tg7L-Eslsmo4sIOmnd53IQzEDE24,6860
29
29
  python2rust/core/emit/translate.py,sha256=RQK9To9ycLYEI0PJ_qZUhjHz25SrfBhoH5BKY00xRSM,11243
30
30
  python2rust/core/frontend/__init__.py,sha256=L4svHwirUol44fn6N_lOBOuMMcBDmZWA-q8wP5Eh-aQ,85
@@ -35,20 +35,20 @@ python2rust/core/frontend/project_imports.py,sha256=GCNbdR4HMv_lbJBa-xw5ivgYLfSL
35
35
  python2rust/core/frontend/symbols.py,sha256=G4O14ySEfru4PHuyYyhz_beZR56we_xv6gYFJKlGkhU,5328
36
36
  python2rust/core/frontend/walrus.py,sha256=2bB57jSRdbcu4rkL5BBOks9lRIjVguwLxryoFngWaIs,2091
37
37
  python2rust/core/ir/__init__.py,sha256=1aLVRrz5_JeAHv553C0cWp3-0y-yJ5lmq_1eGfDqFfE,90
38
- python2rust/core/ir/nodes.py,sha256=qr3LafWpUwCYkvIWNNBt9r6VoQfN45Y_nzh8JJgzQHI,15150
38
+ python2rust/core/ir/nodes.py,sha256=3GeO3Sus8YrHzGwILdseruCLSwyRMCeid6saW6HPXlk,15181
39
39
  python2rust/core/ir/rtypes.py,sha256=ARBRH5Yt_ox6wJLPw8-POa0WM3CDn-MIBK_l4_qu2Js,3571
40
40
  python2rust/core/ir/types.py,sha256=XTMpuhON0VOndBY7DTUE4-GYYOYlVncNsbJlBxeBf0s,12932
41
41
  python2rust/core/lower/__init__.py,sha256=FOK4wP21N5wagC5j5Hhk12jmPEcuJLSpWC1yS-uwb-8,47
42
42
  python2rust/core/lower/calls.py,sha256=6_maCmB7EI_Y6o9yGUBes6zE6xtF5vZ4HLWeNCFj5tE,51891
43
43
  python2rust/core/lower/context.py,sha256=jMAhaZN4LhpZQlQcHyUQkBWtUGWQT0pwmbhZ2PCDgq4,10272
44
44
  python2rust/core/lower/exceptions.py,sha256=hjShf7UeJ1wnGb1JpPNN8p6kNLOaBoopfbqJPDzlgRY,13834
45
- python2rust/core/lower/exprs.py,sha256=COISbz72WCxIzfZ4ZSypK5IzHNnPFp5CUpBl2JCDRKo,39682
45
+ python2rust/core/lower/exprs.py,sha256=Abetvh46vbDRE8l3kqL_mphEtMdkT2KipjiWPB4PM4w,43492
46
46
  python2rust/core/lower/fstrings.py,sha256=FmTdFvVVDqL16enx1Qg7lNYpZmpZkmKBAj0o_-D0xx4,6060
47
47
  python2rust/core/lower/funcs.py,sha256=pcoJBL6GwKm37vIvhhbJJokwq6i9j5wjqmqgQ9zIwPM,10852
48
48
  python2rust/core/lower/lowerer.py,sha256=ToF_ZLY-KGsXK3xMoUrP5_3hva0WWTPr282YZEyCd2M,15391
49
49
  python2rust/core/lower/modelcalls.py,sha256=SPXyLc2sWc9nJd9_UGor7Z5zAFnzahlpjeK9S6q4KGU,8553
50
50
  python2rust/core/lower/models.py,sha256=-mO76bOSNGB2SzJ0m9e11eNgh3hntM98y64YmLD6dmc,24376
51
- python2rust/core/lower/stmts.py,sha256=H_7CjH8sA7P8lj5vEwjbblWCQ0yWgQAHj9bK73CVHGA,33168
51
+ python2rust/core/lower/stmts.py,sha256=pWm-DI83LmedgRZq8N8D_AqRMxJvL9n-jJ71gM9H-jA,38393
52
52
  python2rust/core/lower/testing.py,sha256=jSiXoox1Hm_C0Ulb1oLX7vpl-vVhacg2JYweM5J9JJw,23943
53
53
  python2rust/core/lower/validation.py,sha256=Nw1qr-ymhthJJRkGK0r7qDylFxAaFIPm6tfndtOZqEY,10674
54
54
  python2rust/core/passes/__init__.py,sha256=XgKarOvS5p6EMA1z3b0to4qO-HN57E4xk0crGDcumeE,82
@@ -57,7 +57,7 @@ python2rust/core/passes/analysis.py,sha256=KR9_474wyUDq82TK38nZvpL7IB2tbqgRGc82e
57
57
  python2rust/core/passes/devirt.py,sha256=2izoMRGZXhTkEeh8Xctk4XIpVTlY_brbKFyqgH7sWEI,12406
58
58
  python2rust/core/passes/ownership.py,sha256=Ts2_SYeZ47IiZuoXmwBGT-2inTt8sXfRht4-mnP5_-4,9360
59
59
  python2rust/core/passes/raises.py,sha256=SOKrqGzEiYxAqQn_bMip9GUrYyHXOOaMiC2F1KqYqxc,12120
60
- python2rust/core/rt_lib.rs,sha256=ky70ApxK1wfhm6qzgkbi2yH1FtmbDmIR7QK7wn9fpJQ,76639
60
+ python2rust/core/rt_lib.rs,sha256=HBYxSSd3ydT_DvH9aS36PFxUD1gI4OeorwX90QX0tyI,80061
61
61
  python2rust/data/README.md,sha256=pQei980CcXvjE4pYf1Fx8m9Kv2U3N-fO1N-uJEEP_gs,5004
62
62
  python2rust/data/py2many_builtins.toml,sha256=oAJxjakvvuTIpZ5faV6HcpDWqf5blR4riotm2fGtGp0,130519
63
63
  python2rust/errors.py,sha256=ncpeikJRjBn03lHFvFuiqMc6E49vvD_dG80gu5KfNvU,1084
@@ -73,10 +73,10 @@ python2rust/server/mcp_server.py,sha256=WyDrqVaBLxg2-WYIoNbM0sGCGpofJDUBeXBdwHHh
73
73
  python2rust/server/mcp_workflow.py,sha256=K8eUWotKh_-BWB75EE-7-1RXaE1V5ar8qrG36HSs64E,5074
74
74
  python2rust/skill/SKILL.md,sha256=VCmhOYGzWNMSeIZf16DGadXJueoBaEH_HInyECuR80E,14517
75
75
  python2rust/verify/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
76
- python2rust/verify/check.py,sha256=qr27MoExlrb-Vx0k9KIuEVg-_vpfyOnP0pEcl3GWmL4,46277
76
+ python2rust/verify/check.py,sha256=nNZ8dAu802jQwKQm_TaG6jWqNV5c4BU4Hrr86-Thc6I,46277
77
77
  python2rust/verify/equiv/__init__.py,sha256=eBAQeJ4s-hAGUQJM-VS272k83K_UoVn0OIeNF8c3kC8,46676
78
78
  python2rust/verify/equiv/compare.py,sha256=rOc_Diy5aRloZEulfBT-BbspCK1_wY-Ko7kFcOj995c,18657
79
- python2rust/verify/equiv/harness.py,sha256=yoIaebYMDVuUVA0hbtAQf01DErdclAw_-GJ7LHQ03Vo,19872
79
+ python2rust/verify/equiv/harness.py,sha256=jRkYOczjhZ02BpUuHJ24xhxQX878lEMuL-8l4MtBwhY,20134
80
80
  python2rust/verify/equiv/judge.py,sha256=VtSDU9eYFtQ-_vXovctLRjWAfmvVHEf_BlhjyYBxhGM,14098
81
81
  python2rust/verify/equiv/procs.py,sha256=IYfZvb8OyvpYynIrsNiCyfwb8M0vYlnVunmruHQ74Bc,9747
82
82
  python2rust/verify/equiv/runner.py,sha256=WWj04dErvPtxAr_Np_rR_VJO9p9RNXL8RVRwZt1-JGM,8674
@@ -94,9 +94,9 @@ python2rust/workflow/project.py,sha256=sXBXwUKdcb8sC3XlEu0E3AS4iDKPghdUVHctbaxGL
94
94
  python2rust/workflow/schemas.py,sha256=6vUI6rJS8XpJQpq003XRfPCnVG2qAfJpodrnWIM4PeY,9297
95
95
  python2rust/workflow/state.py,sha256=8cUrgIyUje2ILSVgdUV7NegeWmAn-pDGLMbpvM4IhDY,16255
96
96
  python2rust/workflow/staticscan.py,sha256=CIHuDcWWjmLx2Ej6eVoHunglaihgxOTSpO34yI30Eqg,7742
97
- python2rust-0.1.0.dist-info/licenses/LICENSE,sha256=u9FjDtLtoaF44hAh30LqLwwkzzUs0Sdjjicew-n7Rxw,1067
98
- python2rust-0.1.0.dist-info/licenses/NOTICE,sha256=ujjHe8o50S8hqH29qZb_ZcGmB0YKW7ktp0sBtMuv8XQ,2882
99
- python2rust-0.1.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
100
- python2rust-0.1.0.dist-info/entry_points.txt,sha256=cW3FWnKsFpI1-lI4iHgb5Vh3z04zFWfZaK2xT13xMF0,95
101
- python2rust-0.1.0.dist-info/METADATA,sha256=2lwmCZKEUvPr6zKDdUMsG9tWFx_T2D19N827GEVvNWc,25226
102
- python2rust-0.1.0.dist-info/RECORD,,
97
+ python2rust-0.1.1.dist-info/licenses/LICENSE,sha256=u9FjDtLtoaF44hAh30LqLwwkzzUs0Sdjjicew-n7Rxw,1067
98
+ python2rust-0.1.1.dist-info/licenses/NOTICE,sha256=ujjHe8o50S8hqH29qZb_ZcGmB0YKW7ktp0sBtMuv8XQ,2882
99
+ python2rust-0.1.1.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
100
+ python2rust-0.1.1.dist-info/entry_points.txt,sha256=cW3FWnKsFpI1-lI4iHgb5Vh3z04zFWfZaK2xT13xMF0,95
101
+ python2rust-0.1.1.dist-info/METADATA,sha256=aB8IuEiP9yZ0BhUrdCLAQq5p4-2JnLEFbBu0BKcO6Ro,25210
102
+ python2rust-0.1.1.dist-info/RECORD,,