use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
use pyo3::prelude::*;
use pyo3::types::{
PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PySet, PyString,
PyTuple,
};
use pyo3::IntoPyObjectExt;
use crate::host::{with_host, PyHost, PyObj};
use fusevm::Value;
static TABLE: OnceLock<Mutex<Vec<Py<PyAny>>>> = OnceLock::new();
fn table() -> &'static Mutex<Vec<Py<PyAny>>> {
TABLE.get_or_init(|| Mutex::new(Vec::new()))
}
fn resolve_home() -> Option<PathBuf> {
if let Some(p) = std::env::var_os("PYTHONRS_STDLIB") {
return Some(PathBuf::from(p));
}
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
if let Some(prefix) = dir.parent() {
if has_stdlib(prefix) {
return Some(prefix.to_path_buf());
}
}
}
}
if let Some(home) = dirs::home_dir() {
let prefix = home.join(".pythonrs");
if has_stdlib(&prefix) {
return Some(prefix);
}
}
None
}
fn has_stdlib(prefix: &std::path::Path) -> bool {
let libdir = prefix.join("lib");
std::fs::read_dir(&libdir)
.map(|entries| {
entries.flatten().any(|e| {
e.file_name()
.to_str()
.is_some_and(|n| n.starts_with("python3."))
&& e.path().is_dir()
})
})
.unwrap_or(false)
}
pub fn init() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
if let Some(home) = resolve_home() {
std::env::set_var("PYTHONHOME", home);
}
pyo3::prepare_freethreaded_python();
});
}
pub fn run_module(modname: &str, args: &[String]) -> i32 {
init();
Python::with_gil(|py| {
let sys = match py.import("sys") {
Ok(m) => m,
Err(e) => {
eprintln!("python: {e}");
return 1;
}
};
let argv = PyList::empty(py);
let _ = argv.append(modname);
for a in args {
let _ = argv.append(a);
}
if let Err(e) = sys.setattr("argv", argv) {
eprintln!("python: {e}");
return 1;
}
let runpy = match py.import("runpy") {
Ok(m) => m,
Err(e) => {
eprintln!("python: {e}");
return 1;
}
};
let code = match runpy.call_method1("_run_module_as_main", (modname, true)) {
Ok(_) => 0,
Err(e) => {
if e.is_instance_of::<pyo3::exceptions::PySystemExit>(py) {
system_exit_code(py, &e)
} else {
e.print(py);
1
}
}
};
for stream in ["stdout", "stderr"] {
if let Ok(s) = sys.getattr(stream) {
let _ = s.call_method0("flush");
}
}
code
})
}
fn system_exit_code(py: Python, e: &PyErr) -> i32 {
match e.value(py).getattr("code") {
Ok(code) if code.is_none() => 0,
Ok(code) => {
if let Ok(n) = code.extract::<i32>() {
n
} else {
eprintln!(
"{}",
code.str().map(|s| s.to_string()).unwrap_or_default()
);
1
}
}
Err(_) => 0,
}
}
fn store(obj: Py<PyAny>) -> u32 {
let mut t = table().lock().expect("ffi table poisoned");
t.push(obj);
(t.len() - 1) as u32
}
pub fn table_len() -> usize {
table().lock().map(|t| t.len()).unwrap_or(0)
}
fn fetch<'py>(py: Python<'py>, id: u32) -> Result<Bound<'py, PyAny>, String> {
let t = table().lock().expect("ffi table poisoned");
match t.get(id as usize) {
Some(obj) => Ok(obj.clone_ref(py).into_bound(py)),
None => Err(format!("ffi: invalid foreign handle {id}")),
}
}
fn pyerr_class_bases(py: Python, err: &PyErr) -> Option<(String, Vec<String>)> {
let ty = err.get_type(py);
let class = ty.name().ok()?.to_string();
let mut bases: Vec<String> = Vec::new();
if let Ok(mro) = ty.getattr("__mro__") {
if let Ok(seq) = mro.try_iter() {
for c in seq.flatten() {
if let Ok(n) = c.getattr("__name__").and_then(|n| n.extract::<String>()) {
bases.push(n);
}
}
}
}
(!bases.is_empty()).then_some((class, bases))
}
fn pyerr_to_error(py: Python, err: &PyErr) -> String {
if let Some((class, bases)) = pyerr_class_bases(py, err) {
with_host(|h| {
h.foreign_exc_bases.insert(class, bases);
});
}
err.to_string()
}
fn pyerr_to_error_h(host: &mut PyHost, py: Python, err: &PyErr) -> String {
if let Some((class, bases)) = pyerr_class_bases(py, err) {
host.foreign_exc_bases.insert(class, bases);
}
err.to_string()
}
pub fn import(name: &str) -> Result<u32, String> {
init();
Python::with_gil(|py| match py.import(name) {
Ok(module) => Ok(store(module.into_any().unbind())),
Err(e) => Err(e.to_string()),
})
}
pub fn same_object(a: u32, b: u32) -> bool {
Python::with_gil(|py| match (fetch(py, a), fetch(py, b)) {
(Ok(x), Ok(y)) => x.is(&y),
_ => false,
})
}
pub fn foreign_eq(a: u32, b: u32) -> bool {
Python::with_gil(|py| match (fetch(py, a), fetch(py, b)) {
(Ok(x), Ok(y)) => x.eq(&y).unwrap_or(false),
_ => false,
})
}
pub enum Prim<'a> {
Int(i64),
Float(f64),
Str(&'a str),
}
pub fn foreign_eq_prim(fid: u32, prim: Prim) -> bool {
Python::with_gil(|py| {
let Ok(x) = fetch(py, fid) else { return false };
let other: Bound<PyAny> = match prim {
Prim::Int(n) => match n.into_pyobject(py) {
Ok(o) => o.into_any(),
Err(_) => return false,
},
Prim::Float(f) => match f.into_pyobject(py) {
Ok(o) => o.into_any(),
Err(_) => return false,
},
Prim::Str(s) => match s.into_pyobject(py) {
Ok(o) => o.into_any(),
Err(_) => return false,
},
};
x.eq(&other).unwrap_or(false)
})
}
pub fn foreign_cmp(a: u32, b: u32) -> Result<std::cmp::Ordering, String> {
Python::with_gil(|py| match (fetch(py, a), fetch(py, b)) {
(Ok(x), Ok(y)) => x.compare(&y).map_err(|e| e.to_string()),
_ => Err("ffi: invalid foreign handle".into()),
})
}
pub fn foreign_hash(id: u32) -> Result<i64, String> {
Python::with_gil(|py| match fetch(py, id) {
Ok(x) => x.hash().map(|h| h as i64).map_err(|e| e.to_string()),
Err(e) => Err(e),
})
}
pub fn build_foreign_class(
name: &str,
bases: &[Value],
members: &[(String, Value)],
) -> Result<Value, String> {
init();
Python::with_gil(|py| {
let (bases_tuple, members_dict): (Bound<PyAny>, Bound<PyAny>) =
with_host(|h| -> Result<_, String> {
let base_objs: Vec<Bound<PyAny>> = bases
.iter()
.map(|b| value_to_py(h, py, b))
.collect::<Result<_, _>>()?;
let bases_tuple = PyTuple::new(py, &base_objs).map_err(|e| e.to_string())?;
let members_dict = PyDict::new(py);
for (k, v) in members {
let pv = value_to_py(h, py, v)?;
members_dict
.set_item(k.as_str(), pv)
.map_err(|e| e.to_string())?;
}
Ok((bases_tuple.into_any(), members_dict.into_any()))
})?;
let helper = make_class_helper(py)?;
let cls = helper
.call1((name, bases_tuple, members_dict))
.map_err(|e| e.to_string())?;
let id = store(cls.unbind());
Ok(with_host(|h| h.alloc(PyObj::Foreign(id))))
})
}
fn make_class_helper(py: Python) -> Result<Bound<PyAny>, String> {
static MAKE_CLASS: OnceLock<Py<PyAny>> = OnceLock::new();
if let Some(f) = MAKE_CLASS.get() {
return Ok(f.bind(py).clone());
}
let code = cr#"
import types
def _make(name, bases, members):
def body(ns):
for k in members:
ns[k] = members[k]
return types.new_class(name, tuple(bases), {}, body)
"#;
let module = PyModule::from_code(py, code, c"_pyrs_class.py", c"_pyrs_class")
.map_err(|e| e.to_string())?;
let f = module.getattr("_make").map_err(|e| e.to_string())?;
let _ = MAKE_CLASS.set(f.clone().unbind());
Ok(f)
}
fn value_to_py<'py>(
host: &PyHost,
py: Python<'py>,
v: &Value,
) -> Result<Bound<'py, PyAny>, String> {
let conv = |b: Result<Bound<'py, PyAny>, PyErr>| b.map_err(|e| e.to_string());
match v {
Value::Undef => Ok(py.None().into_bound(py)),
Value::Bool(b) => conv(b.into_bound_py_any(py)),
Value::Int(n) => conv(n.into_bound_py_any(py)),
Value::Float(f) => conv(f.into_bound_py_any(py)),
Value::Str(s) => conv(s.as_str().into_bound_py_any(py)),
Value::Obj(_) => match host.get(v) {
Some(PyObj::Str(s)) => conv(s.as_str().into_bound_py_any(py)),
Some(PyObj::Bytes(b)) => Ok(PyBytes::new(py, b).into_any()),
Some(PyObj::Bytearray(b)) => Ok(PyByteArray::new(py, b).into_any()),
Some(PyObj::BigInt(b)) => {
let int_ctor = py
.import("builtins")
.and_then(|m| m.getattr("int"))
.map_err(|e| e.to_string())?;
int_ctor.call1((b.to_string(),)).map_err(|e| e.to_string())
}
Some(PyObj::List(items)) => {
let elems = marshal_seq(host, py, items)?;
Ok(PyList::new(py, elems)
.map_err(|e| e.to_string())?
.into_any())
}
Some(PyObj::Tuple(items)) => {
let elems = marshal_seq(host, py, items)?;
Ok(PyTuple::new(py, elems)
.map_err(|e| e.to_string())?
.into_any())
}
Some(PyObj::Set(s)) => {
let elems = marshal_seq(host, py, &s.values().cloned().collect::<Vec<_>>())?;
Ok(PySet::new(py, &elems)
.map_err(|e| e.to_string())?
.into_any())
}
Some(PyObj::Frozenset(s)) => {
let elems = marshal_seq(host, py, &s.values().cloned().collect::<Vec<_>>())?;
Ok(PyFrozenSet::new(py, &elems)
.map_err(|e| e.to_string())?
.into_any())
}
Some(PyObj::Range { start, stop, step }) => {
let range = py
.import("builtins")
.and_then(|m| m.getattr("range"))
.map_err(|e| e.to_string())?;
range
.call1((*start, *stop, *step))
.map_err(|e| e.to_string())
}
Some(PyObj::Complex(re, im)) => {
let cplx = py
.import("builtins")
.and_then(|m| m.getattr("complex"))
.map_err(|e| e.to_string())?;
cplx.call1((*re, *im)).map_err(|e| e.to_string())
}
Some(PyObj::Deque { items, maxlen }) => {
let elems = marshal_seq(host, py, &items.iter().cloned().collect::<Vec<_>>())?;
let pylist = PyList::new(py, elems).map_err(|e| e.to_string())?;
let deque = py
.import("collections")
.and_then(|m| m.getattr("deque"))
.map_err(|e| e.to_string())?;
match maxlen {
Some(n) => deque.call1((pylist, *n)),
None => deque.call1((pylist,)),
}
.map_err(|e| e.to_string())
}
Some(PyObj::Dict(d)) => {
let dict = PyDict::new(py);
for (k, val) in d.values() {
let pk = value_to_py(host, py, k)?;
let pv = value_to_py(host, py, val)?;
dict.set_item(pk, pv).map_err(|e| e.to_string())?;
}
Ok(dict.into_any())
}
Some(PyObj::Ellipsis) => Ok(py.Ellipsis().into_bound(py)),
Some(PyObj::Foreign(id)) => fetch(py, *id),
Some(
PyObj::Generator { .. }
| PyObj::Iter(_)
| PyObj::Zip { .. }
| PyObj::MapObj { .. }
| PyObj::FilterObj { .. }
| PyObj::EnumerateObj { .. }
| PyObj::CallIter { .. },
) => {
let it = PyrsIterator { target: v.clone() };
Py::new(py, it)
.map(|p| p.into_any().into_bound(py))
.map_err(|e| e.to_string())
}
Some(PyObj::Builtin(name))
if !name.contains('.')
&& py
.import("builtins")
.and_then(|m| m.getattr(name.as_str()))
.is_ok() =>
{
py.import("builtins")
.and_then(|m| m.getattr(name.as_str()))
.map_err(|e| e.to_string())
}
Some(
PyObj::Func(_)
| PyObj::Builtin(_)
| PyObj::BoundMethod { .. }
| PyObj::Partial { .. }
| PyObj::LruCache { .. }
| PyObj::StaticMethod(_)
| PyObj::ClassMethod(_),
) => {
let cb = PyrsCallable { target: v.clone() };
Py::new(py, cb)
.map(|p| p.into_any().into_bound(py))
.map_err(|e| e.to_string())
}
Some(PyObj::Class(cname)) => {
let members: Vec<(String, Value)> = host
.classes
.get(cname)
.map(|c| {
c.ns.iter()
.map(|(k, val)| (k.clone(), val.clone()))
.collect()
})
.unwrap_or_default();
let ns_dict = PyDict::new(py);
for (k, val) in &members {
let pv = value_to_py(host, py, val)?;
ns_dict
.set_item(k.as_str(), pv)
.map_err(|e| e.to_string())?;
}
if !ns_dict.contains("__module__").unwrap_or(false) {
let _ = ns_dict.set_item("__module__", "__main__");
}
let _ = ns_dict.set_item("__qualname__", cname.as_str());
let obj_base = py
.import("builtins")
.and_then(|m| m.getattr("object"))
.map_err(|e| e.to_string())?;
let bases = PyTuple::new(py, &[obj_base]).map_err(|e| e.to_string())?;
let helper = make_class_helper(py)?;
helper
.call1((cname.as_str(), bases, ns_dict))
.map_err(|e| e.to_string())
}
Some(PyObj::Exception { class, args }) => {
let ctor = py
.import("builtins")
.and_then(|m| m.getattr(class.as_str()))
.map_err(|e| e.to_string())?;
let pargs = marshal_seq(host, py, args)?;
let tup = PyTuple::new(py, pargs).map_err(|e| e.to_string())?;
ctor.call1(tup).map_err(|e| e.to_string())
}
Some(PyObj::Instance(_)) => {
let proxy = PyrsInstance { target: v.clone() };
Py::new(py, proxy)
.map(|p| p.into_any().into_bound(py))
.map_err(|e| e.to_string())
}
_ => Err(crate::host::type_error(&format!(
"cannot pass '{}' to a CPython stdlib call",
host.type_name(v)
))),
},
_ => Err(crate::host::type_error(
"unsupported value for CPython call",
)),
}
}
fn marshal_seq<'py>(
host: &PyHost,
py: Python<'py>,
items: &[Value],
) -> Result<Vec<Bound<'py, PyAny>>, String> {
items.iter().map(|it| value_to_py(host, py, it)).collect()
}
fn py_to_value(host: &mut PyHost, py: Python, obj: &Bound<PyAny>) -> Result<Value, String> {
if obj.is_none() {
return Ok(Value::Undef);
}
if obj.is(&py.Ellipsis()) {
return Ok(host.alloc(PyObj::Ellipsis));
}
if obj.is_exact_instance_of::<PyBool>() {
return Ok(Value::Bool(
obj.extract::<bool>().map_err(|e| e.to_string())?,
));
}
if obj.is_exact_instance_of::<PyInt>() {
return Ok(match obj.extract::<i64>() {
Ok(n) => Value::Int(n),
Err(_) => {
let s = obj.str().map_err(|e| e.to_string())?.to_string();
match s.parse::<num_bigint::BigInt>() {
Ok(b) => host.alloc(PyObj::BigInt(b)),
Err(_) => return Err(format!("ffi: cannot marshal int '{s}'")),
}
}
});
}
if obj.is_exact_instance_of::<PyFloat>() {
return Ok(Value::Float(
obj.extract::<f64>().map_err(|e| e.to_string())?,
));
}
if obj.is_exact_instance_of::<pyo3::types::PyString>() {
return Ok(host.new_str(obj.extract::<String>().map_err(|e| e.to_string())?));
}
if obj.is_exact_instance_of::<PyBytes>() {
let b = obj.downcast::<PyBytes>().map_err(|e| e.to_string())?;
return Ok(host.alloc(PyObj::Bytes(b.as_bytes().to_vec())));
}
if obj.is_exact_instance_of::<PyList>() {
let list = obj.downcast::<PyList>().map_err(|e| e.to_string())?;
let items = unmarshal_seq(host, py, list.iter())?;
return Ok(host.new_list(items));
}
if obj.is_exact_instance_of::<PyTuple>() {
let tup = obj.downcast::<PyTuple>().map_err(|e| e.to_string())?;
let items = unmarshal_seq(host, py, tup.iter())?;
return Ok(host.new_tuple(items));
}
if obj.is_exact_instance_of::<PyDict>() {
let dict = obj.downcast::<PyDict>().map_err(|e| e.to_string())?;
let mut map = indexmap::IndexMap::new();
for (k, v) in dict.iter() {
let kv = py_to_value(host, py, &k)?;
let vv = py_to_value(host, py, &v)?;
let key = host.to_key(&kv)?;
map.insert(key, (kv, vv));
}
return Ok(host.new_dict(map));
}
if obj.is_exact_instance_of::<PySet>() || obj.is_exact_instance_of::<PyFrozenSet>() {
let mut map = indexmap::IndexMap::new();
for it in obj.try_iter().map_err(|e| e.to_string())? {
let iv = py_to_value(host, py, &it.map_err(|e| e.to_string())?)?;
let key = host.to_key(&iv)?;
map.insert(key, iv);
}
return Ok(host.new_set(map));
}
Ok(host.alloc(PyObj::Foreign(store(obj.clone().unbind()))))
}
fn unmarshal_seq<'py, I>(host: &mut PyHost, py: Python, items: I) -> Result<Vec<Value>, String>
where
I: Iterator<Item = Bound<'py, PyAny>>,
{
items.map(|it| py_to_value(host, py, &it)).collect()
}
pub fn get_attr(host: &mut PyHost, id: u32, name: &str) -> Result<Value, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let attr = obj.getattr(name).map_err(|e| e.to_string())?;
py_to_value(host, py, &attr)
})
}
pub fn set_attr(host: &mut PyHost, id: u32, name: &str, value: &Value) -> Result<(), String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let v = value_to_py(host, py, value)?;
obj.setattr(name, v)
.map_err(|e| pyerr_to_error_h(host, py, &e))
})
}
pub fn call(id: u32, args: Vec<Value>, kwargs: Vec<(String, Value)>) -> Result<Value, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
invoke_bound(py, &obj, &args, &kwargs)
})
}
pub fn call_method(
id: u32,
name: &str,
args: Vec<Value>,
kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let method = obj.getattr(name).map_err(|e| e.to_string())?;
invoke_bound(py, &method, &args, &kwargs)
})
}
fn invoke_bound(
py: Python,
callable: &Bound<PyAny>,
args: &[Value],
kwargs: &[(String, Value)],
) -> Result<Value, String> {
let (arg_tuple, kw) = with_host(|h| build_call_args(h, py, args, kwargs))?;
let result = callable
.call(&arg_tuple, kw.as_ref())
.map_err(|e| pyerr_to_error(py, &e))?;
with_host(|h| {
writeback_mutated_args(h, py, args, &arg_tuple);
py_to_value(h, py, &result)
})
}
#[derive(Clone, Copy)]
enum MutKind {
List,
Bytearray,
Deque(Option<usize>),
}
fn writeback_mutated_args(
host: &mut PyHost,
py: Python,
args: &[Value],
arg_tuple: &Bound<PyTuple>,
) {
for (i, orig) in args.iter().enumerate() {
let kind = match host.get(orig) {
Some(PyObj::List(_)) => MutKind::List,
Some(PyObj::Bytearray(_)) => MutKind::Bytearray,
Some(PyObj::Deque { maxlen, .. }) => MutKind::Deque(*maxlen),
_ => continue,
};
let Ok(cpy) = arg_tuple.get_item(i) else {
continue;
};
if let Some(obj) = rebuild_mutable(host, py, &cpy, kind) {
if let Some(slot) = host.get_mut(orig) {
*slot = obj;
}
}
}
}
fn rebuild_mutable(
host: &mut PyHost,
py: Python,
cpy: &Bound<PyAny>,
kind: MutKind,
) -> Option<PyObj> {
match kind {
MutKind::Bytearray => {
let ba = cpy.downcast::<PyByteArray>().ok()?;
Some(PyObj::Bytearray(ba.to_vec()))
}
MutKind::List => {
let items = pure_seq(host, py, cpy)?;
Some(PyObj::List(items))
}
MutKind::Deque(maxlen) => {
let items = pure_seq(host, py, cpy)?;
Some(PyObj::Deque {
items: items.into_iter().collect(),
maxlen,
})
}
}
}
fn pure_seq(host: &mut PyHost, py: Python, cpy: &Bound<PyAny>) -> Option<Vec<Value>> {
let it = cpy.try_iter().ok()?;
let mut out = Vec::new();
for item in it {
out.push(pure_value(host, py, &item.ok()?)?);
}
Some(out)
}
fn pure_value(host: &mut PyHost, py: Python, obj: &Bound<PyAny>) -> Option<Value> {
if obj.is_none() {
return Some(Value::Undef);
}
if obj.is_exact_instance_of::<PyBool>() {
return obj.extract::<bool>().ok().map(Value::Bool);
}
if obj.is_exact_instance_of::<PyInt>() {
return match obj.extract::<i64>() {
Ok(n) => Some(Value::Int(n)),
Err(_) => {
let s = obj.str().ok()?.to_string();
s.parse::<num_bigint::BigInt>()
.ok()
.map(|b| host.alloc(PyObj::BigInt(b)))
}
};
}
if obj.is_exact_instance_of::<PyFloat>() {
return obj.extract::<f64>().ok().map(Value::Float);
}
if obj.is_exact_instance_of::<PyString>() {
return obj.extract::<String>().ok().map(|s| host.new_str(s));
}
if obj.is_exact_instance_of::<PyBytes>() {
let b = obj.downcast::<PyBytes>().ok()?;
return Some(host.alloc(PyObj::Bytes(b.as_bytes().to_vec())));
}
if obj.is_exact_instance_of::<PyByteArray>() {
let b = obj.downcast::<PyByteArray>().ok()?;
return Some(host.alloc(PyObj::Bytearray(b.to_vec())));
}
if obj.is_exact_instance_of::<PyList>() {
let items = pure_seq(host, py, obj)?;
return Some(host.new_list(items));
}
if obj.is_exact_instance_of::<PyTuple>() {
let items = pure_seq(host, py, obj)?;
return Some(host.new_tuple(items));
}
None
}
#[allow(clippy::type_complexity)]
fn build_call_args<'py>(
host: &PyHost,
py: Python<'py>,
args: &[Value],
kwargs: &[(String, Value)],
) -> Result<(Bound<'py, PyTuple>, Option<Bound<'py, PyDict>>), String> {
let py_args = marshal_seq(host, py, args)?;
let arg_tuple = PyTuple::new(py, py_args).map_err(|e| e.to_string())?;
let kw = if kwargs.is_empty() {
None
} else {
let d = PyDict::new(py);
for (k, v) in kwargs {
let pv = value_to_py(host, py, v)?;
d.set_item(k.as_str(), pv).map_err(|e| e.to_string())?;
}
Some(d)
};
Ok((arg_tuple, kw))
}
#[pyclass(dict)]
struct PyrsCallable {
target: Value,
}
#[pymethods]
impl PyrsCallable {
fn __getattr__(&self, py: Python, name: String) -> PyResult<Py<PyAny>> {
match with_host(|h| h.get_attr(&self.target, &name)) {
Ok(v) => with_host(|h| value_to_py(h, py, &v))
.map(|b| b.unbind())
.map_err(pyo3::exceptions::PyRuntimeError::new_err),
Err(e) => Err(pyo3::exceptions::PyAttributeError::new_err(e)),
}
}
fn __get__<'py>(
slf: Bound<'py, Self>,
py: Python<'py>,
obj: Option<Bound<'py, PyAny>>,
_owner: Option<Bound<'py, PyAny>>,
) -> PyResult<Bound<'py, PyAny>> {
match obj {
Some(instance) if !instance.is_none() => py
.import("types")?
.getattr("MethodType")?
.call1((slf, instance)),
_ => Ok(slf.into_any()),
}
}
#[pyo3(signature = (*args, **kwargs))]
fn __call__(
&self,
py: Python,
args: &Bound<PyTuple>,
kwargs: Option<&Bound<PyDict>>,
) -> PyResult<Py<PyAny>> {
let to_pyerr = |e: String| pyo3::exceptions::PyRuntimeError::new_err(e);
let rs_args: Vec<Value> = with_host(|h| {
args.iter()
.map(|a| py_to_value(h, py, &a))
.collect::<Result<_, _>>()
})
.map_err(to_pyerr)?;
let rs_kwargs: Vec<(String, Value)> = match kwargs {
None => Vec::new(),
Some(d) => with_host(|h| {
d.iter()
.map(|(k, v)| {
let key = k.str().map_err(|e| e.to_string())?.to_string();
Ok((key, py_to_value(h, py, &v)?))
})
.collect::<Result<_, String>>()
})
.map_err(to_pyerr)?,
};
let result = crate::host::invoke(&self.target, rs_args, rs_kwargs).map_err(to_pyerr)?;
with_host(|h| value_to_py(h, py, &result))
.map(|b| b.unbind())
.map_err(to_pyerr)
}
}
#[pyclass]
struct PyrsIterator {
target: Value,
}
#[pymethods]
impl PyrsIterator {
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
fn __next__(&self, py: Python) -> PyResult<Option<Py<PyAny>>> {
let to_pyerr = |e: String| pyo3::exceptions::PyRuntimeError::new_err(e);
match crate::host::iter_step(&self.target).map_err(to_pyerr)? {
None => Ok(None),
Some(v) => with_host(|h| value_to_py(h, py, &v))
.map(|b| Some(b.unbind()))
.map_err(to_pyerr),
}
}
}
#[pyclass]
struct PyrsInstance {
target: Value,
}
#[pymethods]
impl PyrsInstance {
fn __getattr__(&self, py: Python, name: String) -> PyResult<Py<PyAny>> {
match with_host(|h| h.get_attr(&self.target, &name)) {
Ok(v) => with_host(|h| value_to_py(h, py, &v))
.map(|b| b.unbind())
.map_err(pyo3::exceptions::PyRuntimeError::new_err),
Err(e) => Err(pyo3::exceptions::PyAttributeError::new_err(e)),
}
}
fn __getitem__(&self, py: Python, key: Bound<PyAny>) -> PyResult<Py<PyAny>> {
let to_pyerr = |e: String| pyo3::exceptions::PyRuntimeError::new_err(e);
let key_v = with_host(|h| py_to_value(h, py, &key)).map_err(to_pyerr)?;
let r = crate::host::call_method(&self.target, "__getitem__", vec![key_v], vec![])
.map_err(to_pyerr)?;
with_host(|h| value_to_py(h, py, &r))
.map(|b| b.unbind())
.map_err(to_pyerr)
}
fn __richcmp__(
&self,
py: Python,
other: Bound<PyAny>,
op: pyo3::pyclass::CompareOp,
) -> PyResult<Py<PyAny>> {
use fusevm::NumOp;
let to_pyerr = |e: String| pyo3::exceptions::PyRuntimeError::new_err(e);
let other_v = with_host(|h| py_to_value(h, py, &other)).map_err(to_pyerr)?;
let numop = match op {
pyo3::pyclass::CompareOp::Lt => NumOp::Lt,
pyo3::pyclass::CompareOp::Le => NumOp::Le,
pyo3::pyclass::CompareOp::Eq => NumOp::Eq,
pyo3::pyclass::CompareOp::Ne => NumOp::Ne,
pyo3::pyclass::CompareOp::Gt => NumOp::Gt,
pyo3::pyclass::CompareOp::Ge => NumOp::Ge,
};
let r = crate::builtins::numeric_hook(numop, &self.target, &other_v).map_err(to_pyerr)?;
with_host(|h| value_to_py(h, py, &r))
.map(|b| b.unbind())
.map_err(to_pyerr)
}
fn __hash__(&self) -> PyResult<isize> {
with_host(|h| h.to_key(&self.target))
.map(|k| crate::builtins::hash_key(&k) as isize)
.map_err(pyo3::exceptions::PyTypeError::new_err)
}
fn __repr__(&self) -> PyResult<String> {
crate::builtins::py_repr(&self.target).map_err(pyo3::exceptions::PyRuntimeError::new_err)
}
fn __str__(&self) -> PyResult<String> {
crate::builtins::py_str(&self.target).map_err(pyo3::exceptions::PyRuntimeError::new_err)
}
}
pub fn get_item(host: &mut PyHost, id: u32, idx: &Value) -> Result<Value, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let key = value_to_py(host, py, idx)?;
let item = obj
.get_item(key)
.map_err(|e| pyerr_to_error_h(host, py, &e))?;
py_to_value(host, py, &item)
})
}
pub fn get_item_cb(id: u32, idx: &Value) -> Result<Value, String> {
Python::with_gil(|py| {
let key = with_host(|h| value_to_py(h, py, idx))?;
let obj = fetch(py, id)?;
let item = obj.get_item(key).map_err(|e| e.to_string())?;
with_host(|h| py_to_value(h, py, &item))
})
}
pub fn make_iter(host: &mut PyHost, id: u32) -> Result<Value, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let it = obj.try_iter().map_err(|e| e.to_string())?;
Ok(host.alloc(PyObj::Foreign(store(it.into_any().unbind()))))
})
}
pub fn make_iter_cb(id: u32) -> Result<Value, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let it = obj.try_iter().map_err(|e| e.to_string())?;
let handle = it.into_any().unbind();
Ok(with_host(|h| h.alloc(PyObj::Foreign(store(handle)))))
})
}
pub fn iter_next(host: &mut PyHost, id: u32) -> Result<Option<Value>, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let mut it = obj.try_iter().map_err(|e| e.to_string())?;
match it.next() {
None => Ok(None),
Some(Ok(item)) => Ok(Some(py_to_value(host, py, &item)?)),
Some(Err(e)) => Err(e.to_string()),
}
})
}
pub fn iter_next_cb(id: u32) -> Result<Option<Value>, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let mut it = obj.try_iter().map_err(|e| e.to_string())?;
match it.next() {
None => Ok(None),
Some(Ok(item)) => Ok(Some(with_host(|h| py_to_value(h, py, &item))?)),
Some(Err(e)) => Err(e.to_string()),
}
})
}
pub fn contains(host: &mut PyHost, id: u32, item: &Value) -> Result<bool, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let needle = value_to_py(host, py, item)?;
obj.contains(needle).map_err(|e| e.to_string())
})
}
pub fn contains_cb(id: u32, item: &Value) -> Result<bool, String> {
Python::with_gil(|py| {
let needle = with_host(|h| value_to_py(h, py, item))?;
let obj = fetch(py, id)?;
obj.contains(needle).map_err(|e| e.to_string())
})
}
pub fn binary_op(host: &mut PyHost, func: &str, a: &Value, b: &Value) -> Result<Value, String> {
Python::with_gil(|py| {
let pa = value_to_py(host, py, a)?;
let pb = value_to_py(host, py, b)?;
let op = py
.import("operator")
.and_then(|m| m.getattr(func))
.map_err(|e| e.to_string())?;
let res = op.call1((pa, pb)).map_err(|e| e.to_string())?;
py_to_value(host, py, &res)
})
}
pub fn to_float(id: u32) -> Result<f64, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let f = py
.import("builtins")
.and_then(|b| b.getattr("float"))
.and_then(|f| f.call1((obj,)))
.map_err(|e| e.to_string())?;
f.extract::<f64>().map_err(|e| e.to_string())
})
}
pub fn isinstance_foreign(host: &mut PyHost, v: &Value, cls_id: u32) -> Result<bool, String> {
Python::with_gil(|py| {
let obj = value_to_py(host, py, v)?;
let cls = fetch(py, cls_id)?;
obj.is_instance(&cls).map_err(|e| e.to_string())
})
}
pub fn to_int(host: &mut PyHost, id: u32) -> Result<Value, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let i = py
.import("builtins")
.and_then(|b| b.getattr("int"))
.and_then(|f| f.call1((obj,)))
.map_err(|e| e.to_string())?;
py_to_value(host, py, &i)
})
}
pub fn to_int_cb(id: u32) -> Result<Value, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
let i = py
.import("builtins")
.and_then(|b| b.getattr("int"))
.and_then(|f| f.call1((obj,)))
.map_err(|e| e.to_string())?;
with_host(|h| py_to_value(h, py, &i))
})
}
pub fn binary_op_cb(func: &str, a: &Value, b: &Value) -> Result<Value, String> {
Python::with_gil(|py| {
let (pa, pb) = with_host(|h| -> Result<_, String> {
Ok((value_to_py(h, py, a)?, value_to_py(h, py, b)?))
})?;
let op = py
.import("operator")
.and_then(|m| m.getattr(func))
.map_err(|e| e.to_string())?;
let res = op.call1((pa, pb)).map_err(|e| e.to_string())?;
with_host(|h| py_to_value(h, py, &res))
})
}
pub fn unary_op(host: &mut PyHost, func: &str, v: &Value) -> Result<Value, String> {
Python::with_gil(|py| {
let pv = value_to_py(host, py, v)?;
let op = py
.import("operator")
.and_then(|m| m.getattr(func))
.map_err(|e| e.to_string())?;
let res = op.call1((pv,)).map_err(|e| e.to_string())?;
py_to_value(host, py, &res)
})
}
pub fn unary_op_cb(func: &str, v: &Value) -> Result<Value, String> {
Python::with_gil(|py| {
let pv = with_host(|h| value_to_py(h, py, v))?;
let op = py
.import("operator")
.and_then(|m| m.getattr(func))
.map_err(|e| e.to_string())?;
let res = op.call1((pv,)).map_err(|e| e.to_string())?;
with_host(|h| py_to_value(h, py, &res))
})
}
pub fn len(id: u32) -> Result<usize, String> {
Python::with_gil(|py| {
let obj = fetch(py, id)?;
obj.len().map_err(|e| e.to_string())
})
}
pub fn str_of(id: u32) -> String {
Python::with_gil(
|py| match fetch(py, id).and_then(|o| o.str().map_err(|e| e.to_string())) {
Ok(s) => s.to_string(),
Err(e) => e,
},
)
}
pub fn repr_of(id: u32) -> String {
Python::with_gil(
|py| match fetch(py, id).and_then(|o| o.repr().map_err(|e| e.to_string())) {
Ok(s) => s.to_string(),
Err(e) => e,
},
)
}
pub fn truthy(id: u32) -> bool {
Python::with_gil(|py| {
fetch(py, id)
.ok()
.and_then(|o| o.is_truthy().ok())
.unwrap_or(true)
})
}
pub fn class_name(id: u32) -> Option<String> {
Python::with_gil(|py| {
let obj = fetch(py, id).ok()?;
obj.getattr("__name__")
.ok()
.and_then(|n| n.extract::<String>().ok())
})
}
pub fn type_name(id: u32) -> String {
Python::with_gil(|py| match fetch(py, id) {
Ok(obj) => obj
.get_type()
.name()
.map(|s| s.to_string())
.unwrap_or_else(|_| "object".into()),
Err(_) => "object".into(),
})
}