1use std::fmt::Write as _;
8
9use crate::bridge::Manifest;
10use crate::codegen::{Modules, PortApi, PortFn, Wire, wire};
11use crate::ts::exports::Param;
12
13fn signature(f: &PortFn, source: &[Param]) -> String {
16 let mut parts = Vec::new();
17 let mut keyword_only = false;
18 for (name, ty) in &f.params {
19 let param = source
20 .iter()
21 .find(|p| crate::bridge::snake_case(&p.name) == *name);
22 if param.is_some_and(|p| p.keyword_only) && !keyword_only {
23 keyword_only = true;
24 parts.push("*".to_string());
25 }
26 let py_name = name.trim_start_matches("r#");
27 match param {
28 Some(p) if p.optional => match p.default.as_deref().and_then(rust_literal) {
29 Some(literal) => {
30 let literal = if ty == "f64"
31 && let Ok(integer) = literal.parse::<i64>()
32 {
33 format!("{integer}_f64")
34 } else {
35 literal
36 };
37 parts.push(format!("{py_name}={literal}"));
38 }
39 None => parts.push(format!("{py_name}=None")),
40 },
41 _ => parts.push(py_name.to_string()),
42 }
43 }
44 parts.join(", ")
45}
46
47pub fn rust_literal(default: &str) -> Option<String> {
51 let d = default.trim();
52 match d {
53 "True" | "true" => return Some("true".into()),
55 "False" | "false" => return Some("false".into()),
56 "None" => return None,
57 _ => {}
58 }
59 let digits = d.replace('_', "");
60 if digits.parse::<i64>().is_ok() {
61 return Some(digits);
62 }
63 if (digits.contains('.') || digits.contains('e')) && digits.parse::<f64>().is_ok() {
64 return Some(if digits.contains('.') {
65 digits
66 } else {
67 format!("{digits}_f64")
68 });
69 }
70 let quote = d.chars().next().filter(|c| *c == '"' || *c == '\'')?;
71 let inner = d.strip_prefix(quote)?.strip_suffix(quote)?;
72 if inner.contains('\\') || inner.contains('"') || inner.contains('\'') {
74 return None;
75 }
76 Some(format!("String::from(\"{inner}\")"))
77}
78
79pub fn has_literal_default(p: &Param) -> bool {
81 p.optional && p.default.as_deref().and_then(rust_literal).is_some()
82}
83
84fn params_of<'m>(m: &'m Manifest, f: &PortFn, class: Option<&str>) -> &'m [Param] {
85 match class {
86 Some(c) => m
87 .classes
88 .iter()
89 .find(|k| k.name == c)
90 .map(|k| {
91 if f.rust_name == "new" {
92 k.constructor.as_slice()
93 } else {
94 k.methods
95 .iter()
96 .find(|x| x.name == f.js_name)
97 .map_or(&[][..], |x| x.params.as_slice())
98 }
99 })
100 .unwrap_or(&[]),
101 None => m
102 .exports
103 .iter()
104 .find(|e| e.name == f.js_name)
105 .map_or(&[][..], |e| e.params.as_slice()),
106 }
107}
108
109fn option_inner(ty: &str) -> Option<&str> {
111 ty.strip_prefix("Option<").and_then(|t| t.strip_suffix('>'))
112}
113
114fn is_option_bound(ty: &str) -> bool {
119 option_inner(ty).is_some_and(|inner| wire(inner) == Wire::Json)
120}
121
122fn binding_type(ty: &str) -> String {
123 if is_option_bound(ty) {
124 return "Option<Bound<'_, PyAny>>".to_string();
125 }
126 match wire(ty) {
127 Wire::Json => "Bound<'_, PyAny>".to_string(),
129 _ => ty.to_string(),
130 }
131}
132
133fn direct(ty: &str) -> bool {
136 const KNOWN: &[&str] = &[
137 "Vec",
138 "Option",
139 "HashMap",
140 "std",
141 "collections",
142 "String",
143 "f64",
144 "i64",
145 "bool",
146 "serde_json",
147 "Value",
148 "Num",
149 "crate",
150 "pynum",
151 ];
152 let compact: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
153 let normalized = compact.replace("Vec<u8>", "String");
154 normalized
155 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
156 .filter(|w| !w.is_empty())
157 .all(|w| KNOWN.contains(&w))
158}
159
160fn body(f: &PortFn, target: &str, constructor: bool) -> String {
161 let mut body = String::new();
162 for (n, t) in &f.params {
163 if wire(t) == Wire::Json {
164 if is_option_bound(t) {
165 if direct(t) {
167 let _ = writeln!(
168 body,
169 " let {n}: {t} = match &{n} {{\n None => None,\n Some(v) => Some(crate::pyconv::FromPy::from_py(v)?),\n }};"
170 );
171 } else {
172 let _ = writeln!(
173 body,
174 " let {n} = match &{n} {{\n None => None,\n Some(v) => Some(crate::pyconv::arg(v)?),\n }};"
175 );
176 }
177 } else if direct(t) {
178 let _ = writeln!(
179 body,
180 " let {n}: {t} = crate::pyconv::FromPy::from_py(&{n})?;"
181 );
182 } else {
183 let _ = writeln!(body, " let {n} = crate::pyconv::arg(&{n})?;");
184 }
185 }
186 }
187 let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
188 let call = format!(
189 "{target}({}){}",
190 args.join(", "),
191 if f.fallible { "?" } else { "" }
192 );
193 if !constructor && f.ret.trim() == "()" {
194 let _ = writeln!(body, " {call};\n Ok(())");
195 return body;
196 }
197 let _ = writeln!(body, " let out = {call};");
198 let _ = writeln!(
199 body,
200 " {}",
201 if !constructor && wire(&f.ret) == Wire::Json && !direct(&f.ret) {
202 "serde_json::to_value(&out).map_err(|e| e.to_string())"
203 } else {
204 "Ok(out)"
205 }
206 );
207 body
208}
209
210fn ret(f: &PortFn) -> String {
212 match wire(&f.ret) {
213 Wire::Json if direct(&f.ret) => f.ret.clone(),
214 Wire::Json => "serde_json::Value".into(),
215 _ => f.ret.clone(),
216 }
217}
218
219fn py_ret(f: &PortFn) -> String {
221 match wire(&f.ret) {
222 Wire::Json => "Py<PyAny>".into(),
223 _ => f.ret.clone(),
224 }
225}
226
227fn py_out(f: &PortFn) -> &'static str {
229 match wire(&f.ret) {
230 Wire::Json => ".map_err(error).and_then(|v| crate::pyconv::ToPy::to_py(&v, py))",
231 _ => ".map_err(error)",
232 }
233}
234
235const PY_ERROR: &str = r#"
242fn error(message: String) -> PyErr {
243 use pyo3::exceptions as e;
244 /// `Err("Kind: text")` for a `Kind` the match below does not know: a built-in exception's name or
245 /// `package.module.Class`, called with the text. None when it names no `Exception` subclass or the
246 /// class cannot be made from the text alone (its constructor takes more arguments).
247 fn named_error(kind: &str, text: &str) -> Option<PyErr> {
248 Python::attach(|py| {
249 // Each dotted part must be a Python identifier, by Python's own rules (`str.isidentifier`).
250 let identifier = |part: &str| {
251 pyo3::types::PyString::new(py, part)
252 .call_method0("isidentifier")
253 .and_then(|ok| ok.extract::<bool>())
254 .unwrap_or(false)
255 };
256 if !kind.split('.').all(identifier) {
257 return None;
258 }
259 let (module, name) = kind.rsplit_once('.').unwrap_or(("builtins", kind));
260 let class = py.import(module).ok()?.getattr(name).ok()?;
261 let class = class.cast_into::<pyo3::types::PyType>().ok()?;
262 if !class.is_subclass_of::<pyo3::exceptions::PyException>().ok()? {
263 return None;
264 }
265 let value = class.call1((text,)).ok()?;
266 if !value.is_instance(&class).ok()? {
267 return None;
268 }
269 Some(PyErr::from_value(value))
270 })
271 }
272 let (kind, text) = message.split_once(": ").unwrap_or(("", message.as_str()));
273 let text = text.to_string();
274 match kind {
275 "TypeError" => e::PyTypeError::new_err(text),
276 "KeyError" => e::PyKeyError::new_err(text),
277 "IndexError" => e::PyIndexError::new_err(text),
278 "OverflowError" => e::PyOverflowError::new_err(text),
279 "ZeroDivisionError" => e::PyZeroDivisionError::new_err(text),
280 "AttributeError" => e::PyAttributeError::new_err(text),
281 "RuntimeError" => e::PyRuntimeError::new_err(text),
282 "NotImplementedError" => e::PyNotImplementedError::new_err(text),
283 "LookupError" => e::PyLookupError::new_err(text),
284 "ArithmeticError" => e::PyArithmeticError::new_err(text),
285 "UnicodeError" => e::PyUnicodeError::new_err(text),
286 "ValueError" => e::PyValueError::new_err(text),
287 _ => named_error(kind, &text).unwrap_or_else(|| e::PyValueError::new_err(message)),
288 }
289}
290"#;
291
292pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {
293 let mut out = format!(
294 "//! Python bindings for `{}`: generated from the signatures in `port.rs` by rust-anything.\n\
295 //! Regenerate with `rust-anything refresh` after changing them.\n\n\
296 #![allow(clippy::too_many_arguments)]\n\n\
297 use pyo3::prelude::*;\n\n",
298 m.unit
299 );
300 if modules.js {
301 out.push_str("pub mod js;\n");
302 }
303 out.push_str("pub mod port;\n");
304 if api.needs_json() {
305 out.push_str(
306 "pub mod pyconv;\npub mod pynum;\n\n#[allow(unused_imports)]\nuse pynum::Num;\n",
307 );
308 }
309 if modules.utf16 {
310 out.push_str("pub mod utf16;\n");
311 }
312 out.push_str(PY_ERROR);
313 let mut registrations = Vec::new();
314 for f in &api.functions {
315 let params: Vec<String> = f
316 .params
317 .iter()
318 .map(|(n, t)| format!("{n}: {}", binding_type(t)))
319 .collect();
320 let inner = format!("{}_inner", f.rust_name.trim_start_matches("r#"));
321 let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
322 let _ = writeln!(
323 out,
324 "\nfn {inner}({}) -> Result<{}, String> {{\n{}}}\n",
325 params.join(", "),
326 ret(f),
327 body(f, &format!("port::{}", f.rust_name), false)
328 );
329 let _ = writeln!(out, "/// `{}`.", f.js_name);
330 let _ = writeln!(out, "#[pyfunction]");
331 let _ = writeln!(
332 out,
333 "#[pyo3(name = \"{}\", signature = ({}))]",
334 f.js_name,
335 signature(f, params_of(m, f, None))
336 );
337 let py_param = if wire(&f.ret) == Wire::Json {
338 "py: Python<'_>, "
339 } else {
340 ""
341 };
342 let _ = writeln!(
343 out,
344 "fn {}({py_param}{}) -> PyResult<{}> {{",
345 f.rust_name,
346 params.join(", "),
347 py_ret(f)
348 );
349 let _ = writeln!(out, " {inner}({}){}\n}}", args.join(", "), py_out(f));
350 registrations.push(format!(
351 " m.add_function(wrap_pyfunction!({}, m)?)?;",
352 f.rust_name
353 ));
354 }
355 for c in &api.classes {
356 let (name, js) = (&c.rust_name, &c.js_name);
357 let snake = crate::bridge::snake_case(name);
358 let ctor_params: Vec<String> = c
359 .constructor
360 .params
361 .iter()
362 .map(|(n, t)| format!("{n}: {}", binding_type(t)))
363 .collect();
364 let ctor_args: Vec<&str> = c
365 .constructor
366 .params
367 .iter()
368 .map(|(n, _)| n.as_str())
369 .collect();
370 let _ = writeln!(
371 out,
372 "\nfn {snake}_new_inner({}) -> Result<port::{name}, String> {{\n{}}}",
373 ctor_params.join(", "),
374 body(&c.constructor, &format!("port::{name}::new"), true)
375 );
376 for (method, mutable) in &c.methods {
377 let receiver = if *mutable {
378 format!("inner: &mut port::{name}")
379 } else {
380 format!("inner: &port::{name}")
381 };
382 let params: Vec<String> = std::iter::once(receiver)
383 .chain(
384 method
385 .params
386 .iter()
387 .map(|(n, t)| format!("{n}: {}", binding_type(t))),
388 )
389 .collect();
390 let _ = writeln!(
391 out,
392 "\nfn {snake}_{}_inner({}) -> Result<{}, String> {{\n{}}}",
393 method.rust_name.trim_start_matches("r#"),
394 params.join(", "),
395 ret(method),
396 body(method, &format!("inner.{}", method.rust_name), false)
397 );
398 }
399 let _ = writeln!(
400 out,
401 "\n/// Class `{js}`.\n#[pyclass(name = \"{js}\")]\npub struct {name} {{\n inner: port::{name},\n}}\n"
402 );
403 let _ = writeln!(out, "#[pymethods]\nimpl {name} {{");
404 let _ = writeln!(
405 out,
406 " #[new]\n #[pyo3(signature = ({}))]\n fn new({}) -> PyResult<Self> {{\n \
407 {snake}_new_inner({}).map(|inner| Self {{ inner }}).map_err(error)\n }}",
408 signature(&c.constructor, params_of(m, &c.constructor, Some(js))),
409 ctor_params.join(", "),
410 ctor_args.join(", ")
411 );
412 for (method, mutable) in &c.methods {
413 let receiver = if *mutable { "&mut self" } else { "&self" };
414 let params: Vec<String> = method
415 .params
416 .iter()
417 .map(|(n, t)| format!("{n}: {}", binding_type(t)))
418 .collect();
419 let sig = std::iter::once(receiver.to_string())
420 .chain(params)
421 .collect::<Vec<_>>()
422 .join(", ");
423 let borrow = if *mutable {
424 "&mut self.inner"
425 } else {
426 "&self.inner"
427 };
428 let args = std::iter::once(borrow)
429 .chain(method.params.iter().map(|(n, _)| n.as_str()))
430 .collect::<Vec<_>>();
431 let sig = if wire(&method.ret) == Wire::Json {
432 sig.replacen("self", "self, py: Python<'_>", 1)
433 } else {
434 sig
435 };
436 let _ = writeln!(
437 out,
438 "\n #[pyo3(name = \"{}\", signature = ({}))]\n fn {}({sig}) -> PyResult<{}> {{\n \
439 {snake}_{}_inner({}){}\n }}",
440 method.js_name,
441 signature(method, params_of(m, method, Some(js))),
442 method.rust_name,
443 py_ret(method),
444 method.rust_name.trim_start_matches("r#"),
445 args.join(", "),
446 py_out(method)
447 );
448 }
449 out.push_str("}\n");
450 registrations.push(format!(" m.add_class::<{name}>()?;"));
451 }
452 if !m.batches.is_empty() {
453 match crate::codegen_batch::py_rs(m, api) {
454 Ok((code, classes)) => {
455 out.push_str(&code);
456 for c in classes {
457 registrations.push(format!(" m.add_class::<{c}>()?;"));
458 }
459 }
460 Err(e) => {
461 let _ = writeln!(out, "\ncompile_error!({e:?});");
462 }
463 }
464 }
465 let _ = writeln!(
466 out,
467 "\n#[pymodule]\n#[pyo3(name = \"_native\")]\nfn native_module(m: &Bound<'_, PyModule>) -> PyResult<()> {{\n{}\n Ok(())\n}}",
468 registrations.join("\n")
469 );
470 out
471}
472
473pub fn package_init(m: &Manifest, api: &PortApi) -> String {
475 let structured = |_: &PortFn| -> (Vec<String>, bool) { (Vec::new(), false) };
477 let mut out = format!(
478 "\"\"\"Rust port of `{}`, generated by rust-anything. Import this package where the code\n\
479 imported the original module.\"\"\"\n\nfrom . import _native\n{CODEC_PY}\n",
480 m.unit
481 );
482 let mut names = Vec::new();
483 for f in &api.functions {
484 let (json_params, json_ret) = structured(f);
485 let positions: Vec<String> = f
486 .params
487 .iter()
488 .enumerate()
489 .filter(|(_, (_, t))| wire(t) == Wire::Json)
490 .map(|(i, _)| i.to_string())
491 .collect();
492 if json_params.is_empty() && !json_ret {
493 let _ = writeln!(out, "{} = _native.{}", f.js_name, f.js_name);
494 } else {
495 let _ = writeln!(
496 out,
497 "{name} = _wrap(_native.{name}, ({positions}), ({names_list}), {json_ret})",
498 name = f.js_name,
499 positions = positions
500 .iter()
501 .map(|p| format!("{p},"))
502 .collect::<String>(),
503 names_list = json_params
504 .iter()
505 .map(|n| format!("'{n}',"))
506 .collect::<String>(),
507 json_ret = if json_ret { "True" } else { "False" }
508 );
509 }
510 names.push(f.js_name.clone());
511 }
512 for c in &api.classes {
513 let needs = std::iter::once(&c.constructor)
514 .chain(c.methods.iter().map(|(x, _)| x))
515 .any(|f| {
516 let (p, r) = structured(f);
517 !p.is_empty() || r
518 });
519 if !needs {
520 let _ = writeln!(out, "{} = _native.{}", c.js_name, c.js_name);
521 } else {
522 let methods: String = c
523 .methods
524 .iter()
525 .map(|(method, _)| {
526 let (params, json_ret) = structured(method);
527 let positions: String = method
528 .params
529 .iter()
530 .enumerate()
531 .filter(|(_, (_, t))| wire(t) == Wire::Json)
532 .map(|(i, _)| format!("{i},"))
533 .collect();
534 format!(
535 " {name} = _method('{name}', ({positions}), ({params}), {ret})\n",
536 name = method.js_name,
537 params = params.iter().map(|n| format!("'{n}',")).collect::<String>(),
538 ret = if json_ret { "True" } else { "False" }
539 )
540 })
541 .collect();
542 let (ctor_params, _) = structured(&c.constructor);
543 let ctor_positions: String = c
544 .constructor
545 .params
546 .iter()
547 .enumerate()
548 .filter(|(_, (_, t))| wire(t) == Wire::Json)
549 .map(|(i, _)| format!("{i},"))
550 .collect();
551 let _ = writeln!(
552 out,
553 "\nclass {js}:\n def __init__(self, *args, **kwargs):\n \
554 args, kwargs = _encode_args(args, kwargs, ({ctor_positions}), ({}))\n \
555 self._inner = _native.{js}(*args, **kwargs)\n{methods}",
556 ctor_params
557 .iter()
558 .map(|n| format!("'{n}',"))
559 .collect::<String>(),
560 js = c.js_name
561 );
562 }
563 names.push(c.js_name.clone());
564 }
565 for b in &m.batches {
566 let class = format!("{}Batch", crate::codegen_batch::pascal(&b.function));
567 let _ = writeln!(out, "{class} = _native.{class}");
568 names.push(class);
569 }
570 let _ = writeln!(
571 out,
572 "\n__all__ = [{}]",
573 names
574 .iter()
575 .map(|n| format!("'{n}'"))
576 .collect::<Vec<_>>()
577 .join(", ")
578 );
579 out
580}
581
582const CODEC_PY: &str = r#"
583import json as _json
584import math as _math
585
586# Structured values cross as JSON text. JSON has no NaN, tuples, sets, bytes, big ints or
587# non-string keys: those travel as markers (see `js.rs`) and come back as Python values.
588_BIG = 2 ** 53
589
590
591def _enc(v):
592 if v is None or isinstance(v, (bool, str)):
593 return v
594 if isinstance(v, int):
595 return v if -_BIG <= v <= _BIG else {"$int": str(v)}
596 if isinstance(v, float):
597 if _math.isnan(v):
598 return {"$num": "NaN"}
599 if _math.isinf(v):
600 return {"$num": "Infinity" if v > 0 else "-Infinity"}
601 if v == 0 and _math.copysign(1, v) < 0:
602 return {"$num": "-0"}
603 return v
604 if isinstance(v, list):
605 return [_enc(x) for x in v]
606 if isinstance(v, tuple):
607 return {"$tuple": [_enc(x) for x in v]}
608 if isinstance(v, (set, frozenset)):
609 return {"$set": sorted((_enc(x) for x in v), key=_json.dumps)}
610 if isinstance(v, (bytes, bytearray, memoryview)):
611 return {"$bytes": list(bytes(v))}
612 if isinstance(v, dict):
613 if all(isinstance(k, str) for k in v):
614 return {k: _enc(x) for k, x in v.items()}
615 return {"$dict": [[_enc(k), _enc(x)] for k, x in v.items()]}
616 return {"$repr": repr(v)}
617
618
619def _dec(v):
620 if isinstance(v, list):
621 return [_dec(x) for x in v]
622 if not isinstance(v, dict):
623 return v
624 if len(v) == 1:
625 (key, inner), = v.items()
626 if key == "$undefined":
627 return None
628 if key == "$num":
629 return {"NaN": _math.nan, "Infinity": _math.inf, "-Infinity": -_math.inf, "-0": -0.0}[inner]
630 if key == "$int":
631 return int(inner)
632 if key == "$tuple":
633 return tuple(_dec(x) for x in inner)
634 if key == "$set":
635 return {_dec(x) for x in inner}
636 if key == "$bytes":
637 return bytes(inner)
638 if key == "$dict":
639 return {_dec(k): _dec(x) for k, x in inner}
640 return {k: _dec(x) for k, x in v.items()}
641
642
643def _encode_args(args, kwargs, positions, names):
644 args = tuple(_json.dumps(_enc(a)) if i in positions else a for i, a in enumerate(args))
645 kwargs = {k: (_json.dumps(_enc(a)) if k in names else a) for k, a in kwargs.items()}
646 return args, kwargs
647
648
649def _wrap(fn, positions, names, json_result):
650 def call(*args, **kwargs):
651 args, kwargs = _encode_args(args, kwargs, positions, names)
652 out = fn(*args, **kwargs)
653 return _dec(_json.loads(out)) if json_result else out
654 call.__name__ = fn.__name__
655 call.__doc__ = fn.__doc__
656 return call
657
658
659def _method(name, positions, names, json_result):
660 def call(self, *args, **kwargs):
661 args, kwargs = _encode_args(args, kwargs, positions, names)
662 out = getattr(self._inner, name)(*args, **kwargs)
663 return _dec(_json.loads(out)) if json_result else out
664 call.__name__ = name
665 return call
666"#;
667
668pub const PYCONV_RS: &str = r#"//! Python objects to `serde_json::Value` and back, in Rust. Generated by rust-anything.
672
673#![forbid(unsafe_code)]
674
675use pyo3::prelude::*;
676use pyo3::types::{
677 PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PyMemoryView,
678 PySet, PyString, PyTuple,
679};
680use serde_json::{Map, Value, json};
681
682fn type_error(obj: &Bound<'_, PyAny>) -> String {
683 let name = obj.get_type().name().map(|n| n.to_string()).unwrap_or_default();
684 format!("TypeError: unsupported argument type {name}")
685}
686
687fn float(x: f64) -> Value {
688 if x.is_nan() {
689 json!({"$num": "NaN"})
690 } else if x.is_infinite() {
691 json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
692 } else if x == 0.0 && x.is_sign_negative() {
693 json!({"$num": "-0"})
694 } else {
695 json!(x)
696 }
697}
698
699fn items(obj: &Bound<'_, PyAny>) -> Result<Vec<Value>, String> {
700 let mut out = Vec::new();
701 for item in obj.try_iter().map_err(|e| e.to_string())? {
702 out.push(from_py(&item.map_err(|e| e.to_string())?)?);
703 }
704 Ok(out)
705}
706
707fn extract_bytes(obj: &Bound<'_, PyAny>) -> Option<Result<Vec<u8>, String>> {
708 if obj.is_instance_of::<PyBytes>() {
709 return Some(
710 obj.cast::<PyBytes>()
711 .map(|b| b.as_bytes().to_vec())
712 .map_err(|e| e.to_string()),
713 );
714 }
715 if obj.is_instance_of::<PyByteArray>() {
716 return Some(
717 obj.cast::<PyByteArray>()
718 .map(|b| b.to_vec())
719 .map_err(|e| e.to_string()),
720 );
721 }
722 if obj.is_instance_of::<PyMemoryView>() {
723 return Some(
724 obj.call_method0("tobytes")
725 .and_then(|b| {
726 b.cast::<PyBytes>()
727 .map(|b| b.as_bytes().to_vec())
728 .map_err(Into::into)
729 })
730 .map_err(|e| e.to_string()),
731 );
732 }
733 None
734}
735
736/// A Python object as a JSON value.
737pub fn from_py(obj: &Bound<'_, PyAny>) -> Result<Value, String> {
738 if obj.is_none() {
739 return Ok(Value::Null);
740 }
741 if obj.is_instance_of::<PyBool>() {
742 return Ok(Value::Bool(obj.extract::<bool>().map_err(|e| e.to_string())?));
743 }
744 if obj.is_instance_of::<PyInt>() {
745 return Ok(match obj.extract::<i64>() {
746 Ok(i) => json!(i),
747 Err(_) => json!({"$int": obj.str().map_err(|e| e.to_string())?.to_string()}),
748 });
749 }
750 if obj.is_instance_of::<PyFloat>() {
751 return Ok(float(obj.extract::<f64>().map_err(|e| e.to_string())?));
752 }
753 if obj.is_instance_of::<PyString>() {
754 return Ok(Value::String(obj.extract::<String>().map_err(|e| e.to_string())?));
755 }
756 if obj.is_instance_of::<PyList>() {
757 return Ok(Value::Array(items(obj)?));
758 }
759 if obj.is_instance_of::<PyTuple>() {
760 return Ok(json!({"$tuple": items(obj)?}));
761 }
762 if obj.is_instance_of::<PyDict>() {
763 let dict = obj.cast::<PyDict>().map_err(|e| e.to_string())?;
764 let mut map = Map::new();
765 let mut pairs = Vec::new();
766 let mut string_keys = true;
767 for (k, v) in dict.iter() {
768 let value = from_py(&v)?;
769 if let Ok(key) = k.extract::<String>() {
770 map.insert(key.clone(), value.clone());
771 pairs.push(json!([key, value]));
772 } else {
773 string_keys = false;
774 pairs.push(json!([from_py(&k)?, value]));
775 }
776 }
777 return Ok(if string_keys { Value::Object(map) } else { json!({"$dict": pairs}) });
778 }
779 if obj.is_instance_of::<PySet>() || obj.is_instance_of::<PyFrozenSet>() {
780 return Ok(json!({"$set": items(obj)?}));
781 }
782 if let Some(bytes) = extract_bytes(obj) {
783 return Ok(json!({"$bytes": bytes?}));
784 }
785 Err(type_error(obj))
786}
787
788/// A structured argument, converted to the port's parameter type.
789pub fn arg<T: serde::de::DeserializeOwned>(obj: &Bound<'_, PyAny>) -> Result<T, String> {
790 serde_json::from_value(from_py(obj)?).map_err(|e| format!("TypeError: {e}"))
791}
792
793/// A Python argument as a Rust value, without going through JSON.
794pub trait FromPy: Sized {
795 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String>;
796}
797
798/// A Rust result as a Python object, without going through JSON.
799pub trait ToPy {
800 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>>;
801}
802
803macro_rules! extract {
804 ($($t:ty),*) => {$(
805 impl FromPy for $t {
806 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
807 obj.extract::<$t>().map_err(|_| type_error(obj))
808 }
809 }
810 impl ToPy for $t {
811 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
812 Ok(self.clone().into_pyobject(py)?.to_owned().into_any().unbind())
813 }
814 }
815 )*};
816}
817extract!(i64, bool, String);
818
819impl FromPy for f64 {
820 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
821 if obj.is_instance_of::<PyFloat>() || obj.is_instance_of::<PyInt>() {
822 obj.extract::<f64>().map_err(|_| type_error(obj))
823 } else {
824 Err(type_error(obj))
825 }
826 }
827}
828
829impl ToPy for f64 {
830 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
831 Ok(PyFloat::new(py, *self).into_any().unbind())
832 }
833}
834
835impl FromPy for crate::pynum::Num {
836 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
837 use crate::pynum::Num;
838 if obj.is_instance_of::<PyFloat>() {
839 return obj.extract::<f64>().map(Num::Float).map_err(|_| type_error(obj));
840 }
841 if obj.is_instance_of::<PyInt>() {
842 return obj
843 .extract::<i64>()
844 .map(Num::Int)
845 .map_err(|_| "OverflowError: int too large for the port".to_string());
846 }
847 Err(type_error(obj))
848 }
849}
850
851impl ToPy for crate::pynum::Num {
852 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
853 match *self {
854 crate::pynum::Num::Int(i) => i.to_py(py),
855 crate::pynum::Num::Float(x) => x.to_py(py),
856 }
857 }
858}
859
860impl FromPy for Value {
861 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
862 from_py(obj)
863 }
864}
865
866impl ToPy for Value {
867 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
868 to_py(py, self)
869 }
870}
871
872impl<T: FromPy> FromPy for Option<T> {
873 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
874 if obj.is_none() { Ok(None) } else { T::from_py(obj).map(Some) }
875 }
876}
877
878impl<T: ToPy> ToPy for Option<T> {
879 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
880 match self {
881 Some(v) => v.to_py(py),
882 None => Ok(py.None()),
883 }
884 }
885}
886
887impl FromPy for Vec<u8> {
888 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
889 extract_bytes(obj).unwrap_or_else(|| Err(type_error(obj)))
890 }
891}
892
893impl ToPy for Vec<u8> {
894 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
895 Ok(PyBytes::new(py, self).into_any().unbind())
896 }
897}
898
899impl<T: FromPy> FromPy for Vec<T> {
900 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
901 if !obj.is_instance_of::<PyList>() && !obj.is_instance_of::<PyTuple>() {
902 return Err(type_error(obj));
903 }
904 let mut out = Vec::new();
905 for item in obj.try_iter().map_err(|e| e.to_string())? {
906 out.push(T::from_py(&item.map_err(|e| e.to_string())?)?);
907 }
908 Ok(out)
909 }
910}
911
912impl<T: ToPy> ToPy for Vec<T> {
913 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
914 let items: PyResult<Vec<Py<PyAny>>> = self.iter().map(|x| x.to_py(py)).collect();
915 Ok(PyList::new(py, items?)?.into_any().unbind())
916 }
917}
918
919impl<T: FromPy> FromPy for std::collections::HashMap<String, T> {
920 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
921 let dict = obj.cast::<PyDict>().map_err(|_| type_error(obj))?;
922 let mut out = Self::new();
923 for (k, v) in dict.iter() {
924 out.insert(k.extract::<String>().map_err(|_| type_error(&k))?, T::from_py(&v)?);
925 }
926 Ok(out)
927 }
928}
929
930impl<T: ToPy> ToPy for std::collections::HashMap<String, T> {
931 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
932 let dict = PyDict::new(py);
933 for (k, v) in self {
934 dict.set_item(k, v.to_py(py)?)?;
935 }
936 Ok(dict.into_any().unbind())
937 }
938}
939
940macro_rules! tuples {
941 ($(($($t:ident $i:tt),+)),*) => {$(
942 impl<$($t: FromPy),+> FromPy for ($($t,)+) {
943 fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
944 let t = obj.cast::<PyTuple>().map_err(|_| type_error(obj))?;
945 Ok(($($t::from_py(&t.get_item($i).map_err(|e| e.to_string())?)?,)+))
946 }
947 }
948 impl<$($t: ToPy),+> ToPy for ($($t,)+) {
949 fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
950 Ok(PyTuple::new(py, [$(self.$i.to_py(py)?),+])?.into_any().unbind())
951 }
952 }
953 )*};
954}
955tuples!((A 0, B 1), (A 0, B 1, C 2), (A 0, B 1, C 2, D 3));
956
957/// A JSON value as a Python object; markers become the Python types they stand for.
958pub fn to_py(py: Python<'_>, v: &Value) -> PyResult<Py<PyAny>> {
959 let list = |items: &[Value]| -> PyResult<Vec<Py<PyAny>>> { items.iter().map(|x| to_py(py, x)).collect() };
960 Ok(match v {
961 Value::Null => py.None(),
962 Value::Bool(b) => PyBool::new(py, *b).to_owned().into_any().unbind(),
963 Value::Number(n) => match n.as_i64() {
964 Some(i) if !n.is_f64() => i.into_pyobject(py)?.into_any().unbind(),
965 _ => match n.as_u64() {
966 Some(u) if !n.is_f64() => u.into_pyobject(py)?.into_any().unbind(),
967 _ => PyFloat::new(py, n.as_f64().unwrap_or(f64::NAN)).into_any().unbind(),
968 },
969 },
970 Value::String(s) => PyString::new(py, s).into_any().unbind(),
971 Value::Array(items) => PyList::new(py, list(items)?)?.into_any().unbind(),
972 Value::Object(o) if o.len() == 1 => {
973 let (key, inner) = o.iter().next().expect("one entry");
974 let items = || inner.as_array().map(Vec::as_slice).unwrap_or_default();
975 match key.as_str() {
976 "$tuple" => PyTuple::new(py, list(items())?)?.into_any().unbind(),
977 "$set" => PySet::new(py, list(items())?)?.into_any().unbind(),
978 "$bytes" => {
979 let bytes: Vec<u8> = items().iter().filter_map(|b| b.as_u64()).map(|b| b as u8).collect();
980 PyBytes::new(py, &bytes).into_any().unbind()
981 }
982 "$int" => py
983 .import("builtins")?
984 .getattr("int")?
985 .call1((inner.as_str().unwrap_or("0"),))?
986 .unbind(),
987 "$float" => PyFloat::new(py, inner.as_str().and_then(|s| s.parse().ok()).unwrap_or(f64::NAN)).into_any().unbind(),
988 "$num" => PyFloat::new(
989 py,
990 match inner.as_str() {
991 Some("Infinity") => f64::INFINITY,
992 Some("-Infinity") => f64::NEG_INFINITY,
993 Some("-0") => -0.0,
994 _ => f64::NAN,
995 },
996 )
997 .into_any()
998 .unbind(),
999 "$dict" => {
1000 let dict = PyDict::new(py);
1001 for pair in items() {
1002 if let Some([k, v]) = pair.as_array().map(Vec::as_slice) {
1003 dict.set_item(to_py(py, k)?, to_py(py, v)?)?;
1004 }
1005 }
1006 dict.into_any().unbind()
1007 }
1008 _ => {
1009 let dict = PyDict::new(py);
1010 dict.set_item(key, to_py(py, inner)?)?;
1011 dict.into_any().unbind()
1012 }
1013 }
1014 }
1015 Value::Object(o) => {
1016 let dict = PyDict::new(py);
1017 for (k, x) in o {
1018 dict.set_item(k, to_py(py, x)?)?;
1019 }
1020 dict.into_any().unbind()
1021 }
1022 })
1023}
1024"#;
1025
1026pub const PYNUM_RS: &str = r#"//! Python numbers: an int stays an int through `+`, `-`, `*`, `//` and `%`; `/` gives a float.
1028//! Generated by rust-anything. Ints beyond i64 become floats (Python would keep a big int).
1029
1030#![forbid(unsafe_code)]
1031
1032use std::cmp::Ordering;
1033use std::ops::{Add, Mul, Neg, Sub};
1034
1035#[derive(Clone, Copy, Debug)]
1036pub enum Num {
1037 Int(i64),
1038 Float(f64),
1039}
1040
1041impl Num {
1042 pub fn f(self) -> f64 {
1043 match self {
1044 Self::Int(i) => i as f64,
1045 Self::Float(x) => x,
1046 }
1047 }
1048
1049 fn op(self, o: Self, int: fn(i64, i64) -> Option<i64>, float: fn(f64, f64) -> f64) -> Self {
1050 match (self, o) {
1051 (Self::Int(a), Self::Int(b)) => int(a, b).map_or_else(|| Self::Float(float(a as f64, b as f64)), Self::Int),
1052 (a, b) => Self::Float(float(a.f(), b.f())),
1053 }
1054 }
1055
1056 /// `/`: always a float; `ZeroDivisionError` for zero.
1057 pub fn true_div(self, o: Self) -> Result<Self, String> {
1058 match (self, o) {
1059 (_, o) if o.f() == 0.0 => Err(match (self, o) {
1060 (Self::Int(_), Self::Int(_)) => "ZeroDivisionError: division by zero".into(),
1061 _ => "ZeroDivisionError: float division by zero".into(),
1062 }),
1063 (a, b) => Ok(Self::Float(a.f() / b.f())),
1064 }
1065 }
1066
1067 /// `%`: the result takes the divisor's sign.
1068 pub fn modulo(self, o: Self) -> Result<Self, String> {
1069 match (self, o) {
1070 (Self::Int(_), Self::Int(0)) => Err("ZeroDivisionError: integer modulo by zero".into()),
1071 (Self::Int(a), Self::Int(b)) => {
1072 let r = a.wrapping_rem(b);
1073 Ok(Self::Int(if r != 0 && (r < 0) != (b < 0) { r + b } else { r }))
1074 }
1075 (a, b) => {
1076 let (x, y) = (a.f(), b.f());
1077 if y == 0.0 {
1078 return Err("ZeroDivisionError: float modulo".into());
1079 }
1080 let m = x % y;
1081 Ok(Self::Float(if m != 0.0 {
1082 if (y < 0.0) != (m < 0.0) { m + y } else { m }
1083 } else {
1084 0.0_f64.copysign(y)
1085 }))
1086 }
1087 }
1088 }
1089
1090 /// Python's `max(a, b, ...)`: the first value no later value is greater than.
1091 pub fn max(values: &[Self]) -> Self {
1092 values[1..].iter().fold(values[0], |m, &x| if x > m { x } else { m })
1093 }
1094
1095 /// Python's `min(a, b, ...)`.
1096 pub fn min(values: &[Self]) -> Self {
1097 values[1..].iter().fold(values[0], |m, &x| if x < m { x } else { m })
1098 }
1099}
1100
1101impl From<f64> for Num {
1102 fn from(x: f64) -> Self {
1103 Self::Float(x)
1104 }
1105}
1106
1107impl From<i64> for Num {
1108 fn from(i: i64) -> Self {
1109 Self::Int(i)
1110 }
1111}
1112
1113impl Add for Num {
1114 type Output = Self;
1115 fn add(self, o: Self) -> Self {
1116 self.op(o, i64::checked_add, |a, b| a + b)
1117 }
1118}
1119
1120impl Sub for Num {
1121 type Output = Self;
1122 fn sub(self, o: Self) -> Self {
1123 self.op(o, i64::checked_sub, |a, b| a - b)
1124 }
1125}
1126
1127impl Mul for Num {
1128 type Output = Self;
1129 fn mul(self, o: Self) -> Self {
1130 self.op(o, i64::checked_mul, |a, b| a * b)
1131 }
1132}
1133
1134impl Neg for Num {
1135 type Output = Self;
1136 fn neg(self) -> Self {
1137 match self {
1138 Self::Int(i) => i.checked_neg().map_or(Self::Float(-(i as f64)), Self::Int),
1139 Self::Float(x) => Self::Float(-x),
1140 }
1141 }
1142}
1143
1144impl PartialEq for Num {
1145 fn eq(&self, o: &Self) -> bool {
1146 match (*self, *o) {
1147 (Self::Int(a), Self::Int(b)) => a == b,
1148 (a, b) => a.f() == b.f(),
1149 }
1150 }
1151}
1152
1153impl PartialOrd for Num {
1154 fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
1155 match (*self, *o) {
1156 (Self::Int(a), Self::Int(b)) => a.partial_cmp(&b),
1157 (a, b) => a.f().partial_cmp(&b.f()),
1158 }
1159 }
1160}
1161"#;
1162
1163#[cfg(test)]
1164mod tests {
1165 use super::*;
1166 use crate::bridge::{Kind, Manifest};
1167 use crate::codegen::{Modules, PortApi, PortFn};
1168 use crate::lang::Lang;
1169 use crate::ts::exports::{ExportedFn, Param};
1170
1171 #[test]
1172 fn converts_python_literals() {
1173 assert_eq!(rust_literal("'-'").as_deref(), Some("String::from(\"-\")"));
1174 assert_eq!(rust_literal("8").as_deref(), Some("8"));
1175 assert_eq!(rust_literal("1_000").as_deref(), Some("1000"));
1176 assert_eq!(rust_literal("0.5").as_deref(), Some("0.5"));
1177 assert_eq!(rust_literal("True").as_deref(), Some("true"));
1178 assert_eq!(rust_literal("None"), None);
1179 assert_eq!(rust_literal("[]"), None);
1180 assert_eq!(rust_literal("'a\\nb'"), None);
1181 }
1182
1183 #[test]
1184 fn integer_defaults_match_the_rust_parameter_type() {
1185 let f = PortFn {
1186 js_name: "scale".into(),
1187 rust_name: "scale".into(),
1188 params: vec![
1189 ("factor".into(), "f64".into()),
1190 ("count".into(), "i64".into()),
1191 ],
1192 ret: "f64".into(),
1193 fallible: true,
1194 is_async: false,
1195 };
1196 let param = |name: &str, default: &str| Param {
1197 name: name.into(),
1198 optional: true,
1199 default: Some(default.into()),
1200 ..Default::default()
1201 };
1202 let source = [param("factor", "-1_000"), param("count", "2")];
1203 assert_eq!(signature(&f, &source), "factor=-1000_f64, count=2");
1204 }
1205
1206 #[test]
1207 fn optional_object_params_bind_as_option_bound() {
1208 assert_eq!(
1211 binding_type("Option<serde_json::Value>").as_str(),
1212 "Option<Bound<'_, PyAny>>"
1213 );
1214 assert_eq!(
1215 binding_type("serde_json::Value").as_str(),
1216 "Bound<'_, PyAny>"
1217 );
1218 assert_eq!(binding_type("Option<i64>").as_str(), "Option<i64>");
1219 assert_eq!(binding_type("String").as_str(), "String");
1220 }
1221
1222 fn verdict_port() -> PortFn {
1223 PortFn {
1224 js_name: "verdict".into(),
1225 rust_name: "verdict".into(),
1226 params: vec![
1227 ("readings".into(), "serde_json::Value".into()),
1228 ("thresholds".into(), "Option<serde_json::Value>".into()),
1229 ],
1230 ret: "serde_json::Value".into(),
1231 fallible: true,
1232 is_async: false,
1233 }
1234 }
1235
1236 fn verdict_manifest() -> Manifest {
1237 let param = |name: &str, ts_type: &str, optional: bool, default: Option<&str>| Param {
1238 name: name.into(),
1239 ts_type: ts_type.into(),
1240 optional,
1241 default: default.map(str::to_string),
1242 ..Default::default()
1243 };
1244 Manifest {
1245 schema: "1".into(),
1246 root: std::path::PathBuf::from("/tmp"),
1247 root_written: None,
1248 unit: "hpdet/".into(),
1249 language: Lang::Python,
1250 kind: Kind::Pyo3,
1251 crate_name: "hpdet-rs".into(),
1252 exports: vec![ExportedFn {
1253 name: "verdict".into(),
1254 file: "hpdet/verdict.py".into(),
1255 line: 1,
1256 params: vec![
1257 param("readings", "Record<string, number>", false, None),
1258 param("thresholds", "Thresholds | undefined", true, Some("None")),
1259 ],
1260 returns: "Record<string, number>".into(),
1261 ..Default::default()
1262 }],
1263 classes: Vec::new(),
1264 js_only: Vec::new(),
1265 batches: Vec::new(),
1266 allocator: Default::default(),
1267 float_tolerance: None,
1268 }
1269 }
1270
1271 #[test]
1272 fn optional_object_wrapper_accepts_none() {
1273 let api = PortApi {
1274 functions: vec![verdict_port()],
1275 ..Default::default()
1276 };
1277 let modules = Modules {
1278 utf16: false,
1279 js: false,
1280 };
1281 let lib = lib_rs(&verdict_manifest(), &api, &modules);
1282 assert!(
1283 lib.contains("#![allow(clippy::too_many_arguments)]"),
1284 "{lib}"
1285 );
1286 assert!(
1288 lib.contains("#[pyo3(name = \"verdict\", signature = (readings, thresholds=None))]"),
1289 "{lib}"
1290 );
1291 assert!(
1292 lib.contains(
1293 "fn verdict_inner(readings: Bound<'_, PyAny>, \
1294 thresholds: Option<Bound<'_, PyAny>>)"
1295 ),
1296 "{lib}"
1297 );
1298 assert!(lib.contains("match &thresholds"), "{lib}");
1300 assert!(lib.contains("None => None,"), "{lib}");
1301 }
1302
1303 #[test]
1304 fn bytes_params_and_results_convert_directly_without_json() {
1305 assert!(direct("Vec<u8>"));
1306 assert!(direct("Option<Vec<u8>>"));
1307 assert!(direct("Vec<Vec<u8>>"));
1308 assert!(!direct("u8"));
1309 assert!(!direct("Option<u8>"));
1310 assert_eq!(binding_type("Vec<u8>"), "Bound<'_, PyAny>");
1311 assert_eq!(binding_type("Option<Vec<u8>>"), "Option<Bound<'_, PyAny>>");
1312
1313 let crc = PortFn {
1314 js_name: "crc".into(),
1315 rust_name: "crc".into(),
1316 params: vec![("data".into(), "Vec<u8>".into())],
1317 ret: "Vec<u8>".into(),
1318 fallible: true,
1319 is_async: false,
1320 };
1321 let mut manifest = verdict_manifest();
1322 manifest.exports = vec![ExportedFn {
1323 name: "crc".into(),
1324 file: "geo/crc.py".into(),
1325 line: 1,
1326 params: vec![Param {
1327 name: "data".into(),
1328 ts_type: "pybytes".into(),
1329 ..Default::default()
1330 }],
1331 returns: "pybytes".into(),
1332 ..Default::default()
1333 }];
1334 let api = PortApi {
1335 functions: vec![crc],
1336 ..Default::default()
1337 };
1338 let modules = Modules {
1339 utf16: false,
1340 js: false,
1341 };
1342 let lib = lib_rs(&manifest, &api, &modules);
1343 assert!(
1344 lib.contains("fn crc_inner(data: Bound<'_, PyAny>) -> Result<Vec<u8>, String>"),
1345 "{lib}"
1346 );
1347 assert!(
1348 lib.contains("let data: Vec<u8> = crate::pyconv::FromPy::from_py(&data)?;"),
1349 "{lib}"
1350 );
1351 assert!(!lib.contains("serde_json::to_value"), "{lib}");
1352 }
1353}