Merge pull request #2250 from youknowone/funcargs

PyFuncArgs from rust tuple
This commit is contained in:
Jeong YunWon authored and GitHub committed 2020-10-11 15:07:15 +09:00
commit 708da5790b
52 files changed
+372 -423

No files matched your search

+1 -1
View File
@@ -204,7 +204,7 @@ pub fn impl_from_args(input: DeriveInput) -> Result<TokenStream2, Diagnostic> {
impl #impl_generics ::rustpython_vm::function::FromArgs for #name #ty_generics #where_clause {
fn from_args(
vm: &::rustpython_vm::VirtualMachine,
args: &mut ::rustpython_vm::function::PyFuncArgs
args: &mut ::rustpython_vm::function::FuncArgs
) -> ::std::result::Result<Self, ::rustpython_vm::function::ArgumentError> {
Ok(#name { #fields })
}
+2 -6
View File
@@ -496,7 +496,7 @@ fn run_module(vm: &VirtualMachine, module: &str) -> PyResult<()> {
debug!("Running module {}", module);
let runpy = vm.import("runpy", &[], 0)?;
let run_module_as_main = vm.get_attribute(runpy, "_run_module_as_main")?;
vm.invoke(&run_module_as_main, vec![vm.ctx.new_str(module)])?;
vm.invoke(&run_module_as_main, (module,))?;
Ok(())
}
@@ -527,11 +527,7 @@ fn run_script(vm: &VirtualMachine, scope: Scope, script_file: &str) -> PyResult<
let dir = file_path.parent().unwrap().to_str().unwrap().to_owned();
let sys_path = vm.get_attribute(vm.sys_module.clone(), "path").unwrap();
vm.call_method(
&sys_path,
"insert",
vec![vm.ctx.new_int(0), vm.ctx.new_str(dir)],
)?;
vm.call_method(&sys_path, "insert", (0, dir))?;
match util::read_file(&file_path) {
Ok(source) => {
+1 -1
View File
@@ -64,7 +64,7 @@ impl<'vm> ShellHelper<'vm> {
let (first, rest) = words.split_first().unwrap();
let str_iter_method = |obj, name| {
let iter = self.vm.call_method(obj, name, vec![])?;
let iter = self.vm.call_method(obj, name, ())?;
PyIterable::<PyStrRef>::try_from_object(self.vm, iter)?.iter(self.vm)
};
+27 -32
View File
@@ -19,7 +19,7 @@ mod decl {
use super::to_ascii;
use crate::byteslike::PyBytesLike;
use crate::exceptions::PyBaseExceptionRef;
use crate::function::{single_or_tuple_any, Args, KwArgs, OptionalArg, PyFuncArgs};
use crate::function::{single_or_tuple_any, Args, FuncArgs, KwArgs, OptionalArg};
use crate::obj::objbool::{self, IntoPyBool};
use crate::obj::objbytes::PyBytesRef;
use crate::obj::objcode::PyCodeRef;
@@ -49,7 +49,7 @@ mod decl {
let method = vm.get_method_or_type_error(x.clone(), "__abs__", || {
format!("bad operand type for abs(): '{}'", x.class().name)
})?;
vm.invoke(&method, PyFuncArgs::new(vec![], vec![]))
vm.invoke(&method, ())
}
#[pyfunction]
@@ -169,10 +169,8 @@ mod decl {
#[pyfunction]
fn dir(obj: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult<PyList> {
let seq = match obj {
OptionalArg::Present(obj) => vm.call_method(&obj, "__dir__", vec![])?,
OptionalArg::Missing => {
vm.call_method(&vm.get_locals().into_object(), "keys", vec![])?
}
OptionalArg::Present(obj) => vm.call_method(&obj, "__dir__", ())?,
OptionalArg::Missing => vm.call_method(&vm.get_locals().into_object(), "keys", ())?,
};
let sorted = sorted(seq, Default::default(), vm)?;
Ok(sorted)
@@ -279,7 +277,7 @@ mod decl {
.into_option()
.unwrap_or_else(|| PyStr::from("").into_ref(vm));
vm.call_method(&value, "__format__", vec![format_spec.into_object()])?
vm.call_method(&value, "__format__", (format_spec,))?
.downcast()
.map_err(|obj| {
vm.new_type_error(format!(
@@ -360,10 +358,10 @@ mod decl {
let stdout = sysmodule::get_stdout(vm)?;
let stderr = sysmodule::get_stderr(vm)?;
let _ = vm.call_method(&stderr, "flush", vec![]);
let _ = vm.call_method(&stderr, "flush", ());
let fd_matches = |obj, expected| {
vm.call_method(obj, "fileno", vec![])
vm.call_method(obj, "fileno", ())
.and_then(|o| i64::try_from_object(vm, o))
.ok()
.map_or(false, |fd| fd == expected)
@@ -389,9 +387,9 @@ mod decl {
}
} else {
if let OptionalArg::Present(prompt) = prompt {
vm.call_method(&stdout, "write", vec![prompt.into_object()])?;
vm.call_method(&stdout, "write", (prompt,))?;
}
let _ = vm.call_method(&stdout, "flush", vec![]);
let _ = vm.call_method(&stdout, "flush", ());
py_io::file_readline(&stdin, None, vm)
}
}
@@ -459,7 +457,7 @@ mod decl {
}
#[pyfunction]
fn max(mut args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn max(mut args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let default = args.take_keyword("default");
let key_func = args.take_keyword("key");
if !args.kwargs.is_empty() {
@@ -497,9 +495,9 @@ mod decl {
let key_func = key_func.filter(|f| !vm.is_none(f));
if let Some(ref key_func) = key_func {
let mut x_key = vm.invoke(key_func, x.clone())?;
let mut x_key = vm.invoke(key_func, (x.clone(),))?;
for y in candidates_iter {
let y_key = vm.invoke(key_func, y.clone())?;
let y_key = vm.invoke(key_func, (y.clone(),))?;
if vm.bool_cmp(&y_key, &x_key, PyComparisonOp::Gt)? {
x = y;
x_key = y_key;
@@ -517,7 +515,7 @@ mod decl {
}
#[pyfunction]
fn min(args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn min(args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let candidates = match args.args.len().cmp(&1) {
std::cmp::Ordering::Greater => args.args.clone(),
std::cmp::Ordering::Equal => vm.extract_elements(&args.args[0])?,
@@ -540,14 +538,14 @@ mod decl {
// TODO: this key function looks pretty duplicate. Maybe we can create
// a local function?
let mut x_key = if let Some(ref f) = &key_func {
vm.invoke(f, vec![x.clone()])?
vm.invoke(f, (x.clone(),))?
} else {
x.clone()
};
for y in candidates_iter {
let y_key = if let Some(ref f) = &key_func {
vm.invoke(f, vec![y.clone()])?
vm.invoke(f, (y.clone(),))?
} else {
y.clone()
};
@@ -567,7 +565,7 @@ mod decl {
default_value: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
match vm.call_method(&iterator, "__next__", vec![]) {
match vm.call_method(&iterator, "__next__", ()) {
Ok(value) => Ok(value),
Err(value) => {
if objtype::isinstance(&value, &vm.ctx.exceptions.stop_iteration) {
@@ -690,7 +688,7 @@ mod decl {
Some(f) => f,
None => sysmodule::get_stdout(vm)?,
};
let write = |obj: PyStrRef| vm.call_method(&file, "write", vec![obj.into_object()]);
let write = |obj: PyStrRef| vm.call_method(&file, "write", (obj,));
let sep = options.sep.unwrap_or_else(|| PyStr::from(" ").into_ref(vm));
@@ -711,7 +709,7 @@ mod decl {
write(end)?;
if options.flush.to_bool() {
vm.call_method(&file, "flush", vec![])?;
vm.call_method(&file, "flush", ())?;
}
Ok(())
@@ -725,12 +723,12 @@ mod decl {
#[pyfunction]
fn reversed(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if let Some(reversed_method) = vm.get_method(obj.clone(), "__reversed__") {
vm.invoke(&reversed_method?, PyFuncArgs::default())
vm.invoke(&reversed_method?, ())
} else {
vm.get_method_or_type_error(obj.clone(), "__getitem__", || {
"argument to reversed() must be a sequence".to_owned()
})?;
let len = vm.call_method(&obj, "__len__", PyFuncArgs::default())?;
let len = vm.call_method(&obj, "__len__", ())?;
let len = objint::get_value(&len).to_isize().unwrap();
let obj_iterator = objiter::PySequenceIterator::new_reversed(obj, len);
Ok(obj_iterator.into_object(vm))
@@ -746,14 +744,14 @@ mod decl {
let rounded = match ndigits {
OptionalArg::Present(ndigits) => match ndigits {
Some(int) => {
let ndigits = vm.call_method(int.as_object(), "__int__", vec![])?;
vm.call_method(&number, "__round__", vec![ndigits])?
let ndigits = vm.call_method(int.as_object(), "__int__", ())?;
vm.call_method(&number, "__round__", (ndigits,))?
}
None => vm.call_method(&number, "__round__", vec![])?,
None => vm.call_method(&number, "__round__", ())?,
},
OptionalArg::Missing => {
// without a parameter, the result type is coerced to int
vm.call_method(&number, "__round__", vec![])?
vm.call_method(&number, "__round__", ())?
}
};
Ok(rounded)
@@ -791,7 +789,7 @@ mod decl {
}
#[pyfunction]
fn __import__(args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn __import__(args: FuncArgs, vm: &VirtualMachine) -> PyResult {
vm.invoke(&vm.import_func, args)
}
@@ -853,14 +851,11 @@ mod decl {
.new_child_scope_with_locals(cells.clone())
.new_child_scope_with_locals(namespace.clone());
function.invoke_with_scope(vec![].into(), &scope, vm)?;
function.invoke_with_scope(().into(), &scope, vm)?;
let class = vm.invoke(
metaclass.as_object(),
(
Args::from(vec![name_obj, bases, namespace.into_object()]),
kwargs,
),
FuncArgs::new(vec![name_obj, bases, namespace.into_object()], kwargs),
)?;
cells.set_item("__class__", class.clone(), vm)?;
Ok(class)
+1 -1
View File
@@ -131,7 +131,7 @@ impl ByteInnerNewOptions {
if let Some(bytes_method) =
vm.get_method(obj.clone(), "__bytes__")
{
let bytes = vm.invoke(&bytes_method?, vec![])?;
let bytes = vm.invoke(&bytes_method?, ())?;
return PyBytesInner::try_from_object(vm, bytes);
}
PyBytesInner::value_seq_try_from_object(vm, obj.clone())
+1 -1
View File
@@ -296,7 +296,7 @@ impl CFormatSpec {
CFormatPreconversor::Str => vm.to_str(&obj)?,
CFormatPreconversor::Repr | CFormatPreconversor::Ascii => vm.to_repr(&obj)?,
CFormatPreconversor::Bytes => {
TryFromObject::try_from_object(vm, vm.call_method(&obj, "decode", vec![])?)?
TryFromObject::try_from_object(vm, vm.call_method(&obj, "decode", ())?)?
}
};
self.format_string(result.borrow_value().to_owned())
+4 -4
View File
@@ -1,5 +1,5 @@
use crate::common::lock::PyRwLock;
use crate::function::PyFuncArgs;
use crate::function::FuncArgs;
use crate::obj::objsingletons::{PyNone, PyNoneRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::obj::objtraceback::PyTracebackRef;
@@ -62,12 +62,12 @@ impl PyBaseException {
}
#[pyslot]
fn tp_new(cls: PyTypeRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
fn tp_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
PyBaseException::new(args.args, vm).into_ref_with_type(vm, cls)
}
#[pymethod(name = "__init__")]
fn init(&self, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn init(&self, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
*self.args.write() = PyTupleRef::with_elements(args.args, &vm.ctx);
Ok(())
}
@@ -622,7 +622,7 @@ impl ExceptionZoo {
}
}
fn import_error_init(exc_self: PyObjectRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn import_error_init(exc_self: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
vm.set_attr(
&exc_self,
"name",
+7 -9
View File
@@ -1,5 +1,5 @@
use crate::exceptions::{IntoPyException, PyBaseExceptionRef};
use crate::function::PyFuncArgs;
use crate::function::FuncArgs;
use crate::obj::{objstr, objtype};
use crate::pyobject::{ItemProtocol, PyObjectRef, PyResult, TypeProtocol};
use crate::vm::VirtualMachine;
@@ -839,7 +839,7 @@ impl FormatString {
Ok(final_string)
}
pub(crate) fn format(&self, arguments: &PyFuncArgs, vm: &VirtualMachine) -> PyResult<String> {
pub(crate) fn format(&self, arguments: &FuncArgs, vm: &VirtualMachine) -> PyResult<String> {
let mut auto_argument_index: usize = 0;
let mut seen_index = false;
self.format_internal(vm, &mut |field_type| match field_type {
@@ -894,15 +894,13 @@ fn call_object_format(
format_spec: &str,
) -> PyResult {
let argument = match preconversion_spec.and_then(FormatPreconversor::from_char) {
Some(FormatPreconversor::Str) => vm.call_method(&argument, "__str__", vec![])?,
Some(FormatPreconversor::Repr) => vm.call_method(&argument, "__repr__", vec![])?,
Some(FormatPreconversor::Ascii) => vm.call_method(&argument, "__repr__", vec![])?,
Some(FormatPreconversor::Bytes) => vm.call_method(&argument, "decode", vec![])?,
Some(FormatPreconversor::Str) => vm.call_method(&argument, "__str__", ())?,
Some(FormatPreconversor::Repr) => vm.call_method(&argument, "__repr__", ())?,
Some(FormatPreconversor::Ascii) => vm.call_method(&argument, "__repr__", ())?,
Some(FormatPreconversor::Bytes) => vm.call_method(&argument, "decode", ())?,
None => argument,
};
let returned_type = vm.ctx.new_str(format_spec);
let result = vm.call_method(&argument, "__format__", vec![returned_type])?;
let result = vm.call_method(&argument, "__format__", (format_spec,))?;
if !objtype::isinstance(&result, &vm.ctx.types.str_type) {
return Err(vm.new_type_error(format!(
"__format__ must return a str, not {}",
+18 -18
View File
@@ -9,7 +9,7 @@ use crate::bytecode;
use crate::common::lock::PyMutex;
use crate::coroutine::Coro;
use crate::exceptions::{self, ExceptionCtor, PyBaseExceptionRef};
use crate::function::PyFuncArgs;
use crate::function::FuncArgs;
use crate::obj::objasyncgenerator::PyAsyncGenWrappedValue;
use crate::obj::objcode::PyCodeRef;
use crate::obj::objcoroutine::PyCoroutine;
@@ -516,7 +516,7 @@ impl ExecutingFrame<'_> {
let exit = vm.get_attribute(context_manager.clone(), "__exit__")?;
self.push_value(exit);
// Call enter:
let enter_res = vm.call_method(&context_manager, "__enter__", vec![])?;
let enter_res = vm.call_method(&context_manager, "__enter__", ())?;
self.push_block(BlockType::Finally { handler: *end });
self.push_value(enter_res);
Ok(None)
@@ -525,7 +525,7 @@ impl ExecutingFrame<'_> {
let mgr = self.pop_value();
let aexit = vm.get_attribute(mgr.clone(), "__aexit__")?;
self.push_value(aexit);
let aenter_res = vm.call_method(&mgr, "__aenter__", vec![])?;
let aenter_res = vm.call_method(&mgr, "__aenter__", ())?;
self.push_value(aenter_res);
Ok(None)
@@ -552,7 +552,7 @@ impl ExecutingFrame<'_> {
} else {
(vm.ctx.none(), vm.ctx.none(), vm.ctx.none())
};
let exit_res = vm.invoke(&exit, vec![args.0, args.1, args.2])?;
let exit_res = vm.invoke(&exit, args)?;
self.push_value(exit_res);
Ok(None)
@@ -596,24 +596,24 @@ impl ExecutingFrame<'_> {
awaited_obj.class().name,
)
})?;
vm.invoke(&await_method, vec![])?
vm.invoke(&await_method, ())?
};
self.push_value(awaitable);
Ok(None)
}
bytecode::Instruction::GetAIter => {
let aiterable = self.pop_value();
let aiter = vm.call_method(&aiterable, "__aiter__", vec![])?;
let aiter = vm.call_method(&aiterable, "__aiter__", ())?;
self.push_value(aiter);
Ok(None)
}
bytecode::Instruction::GetANext => {
let aiter = self.last_value();
let awaitable = vm.call_method(&aiter, "__anext__", vec![])?;
let awaitable = vm.call_method(&aiter, "__anext__", ())?;
let awaitable = if awaitable.payload_is::<PyCoroutine>() {
awaitable
} else {
vm.call_method(&awaitable, "__await__", vec![])?
vm.call_method(&awaitable, "__await__", ())?
};
self.push_value(awaitable);
Ok(None)
@@ -675,7 +675,7 @@ impl ExecutingFrame<'_> {
let displayhook = vm
.get_attribute(vm.sys_module.clone(), "displayhook")
.map_err(|_| vm.new_runtime_error("lost sys.displayhook".to_owned()))?;
vm.invoke(&displayhook, vec![expr])?;
vm.invoke(&displayhook, (expr,))?;
Ok(None)
}
@@ -729,8 +729,8 @@ impl ExecutingFrame<'_> {
None => self.pop_value(),
};
let spec = vm.to_str(&self.pop_value())?.into_object();
let formatted = vm.call_method(&value, "__format__", vec![spec])?;
let spec = self.pop_value();
let formatted = vm.call_method(&value, "__format__", (spec,))?;
self.push_value(formatted);
Ok(None)
}
@@ -1051,7 +1051,7 @@ impl ExecutingFrame<'_> {
let args = match typ {
bytecode::CallType::Positional(count) => {
let args: Vec<PyObjectRef> = self.pop_multiple(*count);
PyFuncArgs {
FuncArgs {
args,
kwargs: IndexMap::new(),
}
@@ -1065,7 +1065,7 @@ impl ExecutingFrame<'_> {
.iter()
.map(|pyobj| objstr::clone_value(pyobj))
.collect();
PyFuncArgs::new(args, kwarg_names)
FuncArgs::with_kwargs_names(args, kwarg_names)
}
bytecode::CallType::Ex(has_kwargs) => {
let kwargs = if *has_kwargs {
@@ -1088,7 +1088,7 @@ impl ExecutingFrame<'_> {
};
let args = self.pop_value();
let args = vm.extract_elements(&args)?;
PyFuncArgs { args, kwargs }
FuncArgs { args, kwargs }
}
};
@@ -1149,7 +1149,7 @@ impl ExecutingFrame<'_> {
match self.builtin_coro(&coro) {
Some(coro) => coro.send(val, vm),
None if vm.is_none(&val) => objiter::call_next(vm, &coro),
None => vm.call_method(&coro, "send", vec![val]),
None => vm.call_method(&coro, "send", (val,)),
}
}
@@ -1358,9 +1358,9 @@ impl ExecutingFrame<'_> {
fn execute_unop(&mut self, vm: &VirtualMachine, op: &bytecode::UnaryOperator) -> FrameResult {
let a = self.pop_value();
let value = match *op {
bytecode::UnaryOperator::Minus => vm.call_method(&a, "__neg__", vec![])?,
bytecode::UnaryOperator::Plus => vm.call_method(&a, "__pos__", vec![])?,
bytecode::UnaryOperator::Invert => vm.call_method(&a, "__invert__", vec![])?,
bytecode::UnaryOperator::Minus => vm.call_method(&a, "__neg__", ())?,
bytecode::UnaryOperator::Plus => vm.call_method(&a, "__pos__", ())?,
bytecode::UnaryOperator::Invert => vm.call_method(&a, "__invert__", ())?,
bytecode::UnaryOperator::Not => {
let value = objbool::boolval(vm, a)?;
vm.ctx.new_bool(!value)
+102 -81
View File
@@ -1,89 +1,103 @@
use std::collections::HashMap;
use std::marker::PhantomData;
use std::mem;
use std::ops::RangeInclusive;
use indexmap::IndexMap;
use result_like::impl_option_like;
use self::OptionalArg::*;
use crate::exceptions::PyBaseExceptionRef;
use crate::obj::objtuple::PyTupleRef;
use crate::obj::objtype::{isinstance, PyTypeRef};
use crate::pyobject::{
BorrowValue, IntoPyResult, PyObjectRef, PyRef, PyResult, PyThreadingConstraint, PyValue,
TryFromObject, TypeProtocol,
BorrowValue, IntoPyObject, IntoPyResult, PyObjectRef, PyRef, PyResult, PyThreadingConstraint,
PyValue, TryFromObject, TypeProtocol,
};
use crate::vm::VirtualMachine;
use indexmap::IndexMap;
use result_like::impl_option_like;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::ops::RangeInclusive;
use self::OptionalArg::*;
pub trait IntoFuncArgs {
fn into_args(self, vm: &VirtualMachine) -> FuncArgs;
}
/// The `PyFuncArgs` struct is one of the most used structs then creating
impl<T> IntoFuncArgs for T
where
T: Into<FuncArgs>,
{
fn into_args(self, _vm: &VirtualMachine) -> FuncArgs {
self.into()
}
}
// A tuple of values that each implement `IntoPyObject` represents a sequence of
// arguments that can be bound and passed to a built-in function.
macro_rules! into_func_args_from_tuple {
($(($n:tt, $T:ident)),*) => {
impl<$($T,)*> IntoFuncArgs for ($($T,)*)
where
$($T: IntoPyObject,)*
{
fn into_args(self, vm: &VirtualMachine) -> FuncArgs {
let ($($n,)*) = self;
vec![$($n.into_pyobject(vm),)*].into()
}
}
};
}
into_func_args_from_tuple!((v1, T1));
into_func_args_from_tuple!((v1, T1), (v2, T2));
into_func_args_from_tuple!((v1, T1), (v2, T2), (v3, T3));
into_func_args_from_tuple!((v1, T1), (v2, T2), (v3, T3), (v4, T4));
into_func_args_from_tuple!((v1, T1), (v2, T2), (v3, T3), (v4, T4), (v5, T5));
/// The `FuncArgs` struct is one of the most used structs then creating
/// a rust function that can be called from python. It holds both positional
/// arguments, as well as keyword arguments passed to the function.
#[derive(Debug, Default, Clone)]
pub struct PyFuncArgs {
pub struct FuncArgs {
pub args: Vec<PyObjectRef>,
// sorted map, according to https://www.python.org/dev/peps/pep-0468/
pub kwargs: IndexMap<String, PyObjectRef>,
}
/// Conversion from vector of python objects to function arguments.
impl From<Vec<PyObjectRef>> for PyFuncArgs {
fn from(args: Vec<PyObjectRef>) -> Self {
PyFuncArgs {
args,
impl<A> From<A> for FuncArgs
where
A: Into<Args>,
{
fn from(args: A) -> Self {
FuncArgs {
args: args.into().into_vec(),
kwargs: IndexMap::new(),
}
}
}
impl From<PyObjectRef> for PyFuncArgs {
fn from(arg: PyObjectRef) -> Self {
PyFuncArgs {
args: vec![arg],
kwargs: IndexMap::new(),
}
}
}
impl From<(Args, KwArgs)> for PyFuncArgs {
fn from(arg: (Args, KwArgs)) -> Self {
let Args(args) = arg.0;
let KwArgs(kwargs) = arg.1;
PyFuncArgs {
args,
kwargs: kwargs.into_iter().collect(),
}
}
}
impl From<(&Args, &KwArgs)> for PyFuncArgs {
fn from(arg: (&Args, &KwArgs)) -> Self {
let Args(args) = arg.0;
let KwArgs(kwargs) = arg.1;
PyFuncArgs {
args: args.clone(),
kwargs: kwargs.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
}
}
}
impl From<KwArgs> for PyFuncArgs {
impl From<KwArgs> for FuncArgs {
fn from(kwargs: KwArgs) -> Self {
PyFuncArgs {
FuncArgs {
args: Vec::new(),
kwargs: kwargs.into_iter().collect(),
kwargs: kwargs.0,
}
}
}
impl FromArgs for PyFuncArgs {
fn from_args(_vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result<Self, ArgumentError> {
Ok(mem::take(args))
impl FromArgs for FuncArgs {
fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
Ok(std::mem::take(args))
}
}
impl PyFuncArgs {
pub fn new(mut args: Vec<PyObjectRef>, kwarg_names: Vec<String>) -> PyFuncArgs {
impl FuncArgs {
pub fn new<A, K>(args: A, kwargs: K) -> Self
where
A: Into<Args>,
K: Into<KwArgs>,
{
let Args(args) = args.into();
let KwArgs(kwargs) = kwargs.into();
Self { args, kwargs }
}
pub fn with_kwargs_names(mut args: Vec<PyObjectRef>, kwarg_names: Vec<String>) -> Self {
// last `kwarg_names.len()` elements of args in order of appearance in the call signature
let kwarg_values = args.drain((args.len() - kwarg_names.len())..);
@@ -91,11 +105,11 @@ impl PyFuncArgs {
for (name, value) in kwarg_names.iter().zip(kwarg_values) {
kwargs.insert(name.clone(), value);
}
PyFuncArgs { args, kwargs }
FuncArgs { args, kwargs }
}
pub fn insert(&self, item: PyObjectRef) -> PyFuncArgs {
let mut args = PyFuncArgs {
pub fn insert(&self, item: PyObjectRef) -> FuncArgs {
let mut args = FuncArgs {
args: self.args.clone(),
kwargs: self.kwargs.clone(),
};
@@ -241,7 +255,7 @@ pub trait FromArgs: Sized {
}
/// Extracts this item from the next argument(s).
fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result<Self, ArgumentError>;
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError>;
}
pub trait FromArgOptional {
@@ -275,10 +289,10 @@ impl<T: TryFromObject> FromArgOptional for T {
/// KwArgs is only for functions that accept arbitrary keyword arguments. For
/// functions that accept only *specific* named arguments, a rust struct with
/// an appropriate FromArgs implementation must be created.
pub struct KwArgs<T = PyObjectRef>(HashMap<String, T>);
pub struct KwArgs<T = PyObjectRef>(IndexMap<String, T>);
impl<T> KwArgs<T> {
pub fn new(map: HashMap<String, T>) -> Self {
pub fn new(map: IndexMap<String, T>) -> Self {
KwArgs(map)
}
@@ -287,13 +301,13 @@ impl<T> KwArgs<T> {
}
}
impl<T> From<HashMap<String, T>> for KwArgs<T> {
fn from(map: HashMap<String, T>) -> Self {
KwArgs(map)
fn from(kwargs: HashMap<String, T>) -> Self {
KwArgs(kwargs.into_iter().collect())
}
}
impl<T> Default for KwArgs<T> {
fn default() -> Self {
KwArgs(HashMap::new())
KwArgs(IndexMap::new())
}
}
@@ -301,8 +315,8 @@ impl<T> FromArgs for KwArgs<T>
where
T: TryFromObject,
{
fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result<Self, ArgumentError> {
let mut kwargs = HashMap::new();
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
let mut kwargs = IndexMap::new();
for (name, value) in args.remaining_keywords() {
kwargs.insert(name, T::try_from_object(vm, value)?);
}
@@ -312,7 +326,7 @@ where
impl<T> IntoIterator for KwArgs<T> {
type Item = (String, T);
type IntoIter = std::collections::hash_map::IntoIter<String, T>;
type IntoIter = indexmap::map::IntoIter<String, T>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
@@ -339,12 +353,19 @@ impl<T> Args<T> {
self.0
}
}
impl<T> From<Vec<T>> for Args<T> {
fn from(v: Vec<T>) -> Self {
Args(v)
}
}
impl From<()> for Args<PyObjectRef> {
fn from(_args: ()) -> Self {
Args(Vec::new())
}
}
impl<T> AsRef<[T]> for Args<T> {
fn as_ref(&self) -> &[T] {
&self.0
@@ -362,7 +383,7 @@ impl<T> FromArgs for Args<T>
where
T: TryFromObject,
{
fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result<Self, ArgumentError> {
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
let mut varargs = Vec::new();
while let Some(value) = args.take_positional() {
varargs.push(T::try_from_object(vm, value)?);
@@ -388,7 +409,7 @@ where
1..=1
}
fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result<Self, ArgumentError> {
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
if let Some(value) = args.take_positional() {
Ok(T::try_from_object(vm, value)?)
} else {
@@ -434,7 +455,7 @@ where
0..=1
}
fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result<Self, ArgumentError> {
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
if let Some(value) = args.take_positional() {
Ok(Present(T::try_from_object(vm, value)?))
} else {
@@ -446,7 +467,7 @@ where
// For functions that accept no arguments. Implemented explicitly instead of via
// macro below to avoid unused warnings.
impl FromArgs for () {
fn from_args(_vm: &VirtualMachine, _args: &mut PyFuncArgs) -> Result<Self, ArgumentError> {
fn from_args(_vm: &VirtualMachine, _args: &mut FuncArgs) -> Result<Self, ArgumentError> {
Ok(())
}
}
@@ -474,7 +495,7 @@ macro_rules! tuple_from_py_func_args {
min..=max
}
fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result<Self, ArgumentError> {
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
Ok(($($T::from_args(vm, args)?,)+))
}
}
@@ -492,7 +513,7 @@ tuple_from_py_func_args!(A, B, C, D, E);
tuple_from_py_func_args!(A, B, C, D, E, F);
/// A built-in Python function.
pub type PyNativeFunc = Box<py_dyn_fn!(dyn Fn(&VirtualMachine, PyFuncArgs) -> PyResult)>;
pub type PyNativeFunc = Box<py_dyn_fn!(dyn Fn(&VirtualMachine, FuncArgs) -> PyResult)>;
/// Implemented by types that are or can generate built-in functions.
///
@@ -507,14 +528,14 @@ pub type PyNativeFunc = Box<py_dyn_fn!(dyn Fn(&VirtualMachine, PyFuncArgs) -> Py
/// `Fn(&self, PyStrRef, FooOptions, vm: &VirtualMachine) -> PyResult<PyInt>`
/// is `IntoPyNativeFunc`. If you do want a really general function signature, e.g.
/// to forward the args to another function, you can define a function like
/// `Fn(PyFuncArgs [, &VirtualMachine]) -> ...`
/// `Fn(FuncArgs [, &VirtualMachine]) -> ...`
///
/// Note that the `Kind` type parameter is meaningless and should be considered
/// an implementation detail; if you need to use `IntoPyNativeFunc` as a trait bound
/// just pass an unconstrained generic type, e.g.
/// `fn foo<F, FKind>(f: F) where F: IntoPyNativeFunc<FKind>`
pub trait IntoPyNativeFunc<Kind>: Sized + PyThreadingConstraint + 'static {
fn call(&self, vm: &VirtualMachine, args: PyFuncArgs) -> PyResult;
fn call(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult;
/// `IntoPyNativeFunc::into_func()` generates a PyNativeFunc that performs the
/// appropriate type and arity checking, any requested conversions, and then if
/// successful calls the function with the extracted parameters.
@@ -529,7 +550,7 @@ impl<F, T, R, VM> IntoPyNativeFunc<(T, R, VM)> for F
where
F: PyNativeFuncInternal<T, R, VM>,
{
fn call(&self, vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
fn call(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult {
self.call_(vm, args)
}
}
@@ -537,7 +558,7 @@ where
mod sealed {
use super::*;
pub trait PyNativeFuncInternal<T, R, VM>: Sized + PyThreadingConstraint + 'static {
fn call_(&self, vm: &VirtualMachine, args: PyFuncArgs) -> PyResult;
fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult;
}
}
use sealed::PyNativeFuncInternal;
@@ -559,7 +580,7 @@ macro_rules! into_py_native_func_tuple {
$($T: FromArgs,)*
R: IntoPyResult,
{
fn call_(&self, vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult {
let ($($n,)*) = args.bind::<($($T,)*)>(vm)?;
(self)($($n,)* vm).into_pyresult(vm)
@@ -573,7 +594,7 @@ macro_rules! into_py_native_func_tuple {
$($T: FromArgs,)*
R: IntoPyResult,
{
fn call_(&self, vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult {
let (zelf, $($n,)*) = args.bind::<(PyRef<S>, $($T,)*)>(vm)?;
(self)(&zelf, $($n,)* vm).into_pyresult(vm)
@@ -586,7 +607,7 @@ macro_rules! into_py_native_func_tuple {
$($T: FromArgs,)*
R: IntoPyResult,
{
fn call_(&self, vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult {
let ($($n,)*) = args.bind::<($($T,)*)>(vm)?;
(self)($($n,)*).into_pyresult(vm)
@@ -600,7 +621,7 @@ macro_rules! into_py_native_func_tuple {
$($T: FromArgs,)*
R: IntoPyResult,
{
fn call_(&self, vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult {
let (zelf, $($n,)*) = args.bind::<(PyRef<S>, $($T,)*)>(vm)?;
(self)(&zelf, $($n,)*).into_pyresult(vm)
+1 -1
View File
@@ -34,7 +34,7 @@ pub(crate) fn init_importlib(
enter_vm(vm, || {
flame_guard!("install_external");
let install_external = vm.get_attribute(importlib, "_install_external_importers")?;
vm.invoke(&install_external, vec![])?;
vm.invoke(&install_external, ())?;
// Set pyc magic number to commit hash. Should be changed when bytecode will be more stable.
let importlib_external = vm.import("_frozen_importlib_external", &[], 0)?;
let mut magic = get_git_revision().into_bytes();
+3 -3
View File
@@ -1,7 +1,7 @@
use num_bigint::Sign;
use num_traits::Zero;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::OptionalArg;
use crate::pyobject::{
BorrowValue, IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyResult,
TryFromObject, TypeProtocol,
@@ -40,7 +40,7 @@ pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
Some(method_or_err) => {
// If descriptor returns Error, propagate it further
let method = method_or_err?;
let bool_obj = vm.invoke(&method, PyFuncArgs::default())?;
let bool_obj = vm.invoke(&method, ())?;
if !objtype::isinstance(&bool_obj, &vm.ctx.types.bool_type) {
return Err(vm.new_type_error(format!(
"__bool__ should return bool, returned type {}",
@@ -53,7 +53,7 @@ pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
None => match vm.get_method(obj, "__len__") {
Some(method_or_err) => {
let method = method_or_err?;
let bool_obj = vm.invoke(&method, PyFuncArgs::default())?;
let bool_obj = vm.invoke(&method, ())?;
let int_obj = bool_obj.payload::<PyInt>().ok_or_else(|| {
vm.new_type_error(format!(
"'{}' object cannot be interpreted as an integer",
+3 -3
View File
@@ -2,7 +2,7 @@ use std::fmt;
use super::objclassmethod::PyClassMethod;
use crate::common::borrow::BorrowValue;
use crate::function::{PyFuncArgs, PyNativeFunc};
use crate::function::{FuncArgs, PyNativeFunc};
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyTypeRef;
use crate::pyobject::{
@@ -112,7 +112,7 @@ impl PyBuiltinFunction {
}
impl Callable for PyBuiltinFunction {
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
(zelf.value.func)(vm, args)
}
}
@@ -192,7 +192,7 @@ impl SlotDescriptor for PyBuiltinMethod {
}
impl Callable for PyBuiltinMethod {
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
(zelf.value.func)(vm, args)
}
}
+4 -4
View File
@@ -8,7 +8,7 @@ use super::objstr;
use super::objtype::{self, PyTypeRef};
use crate::dictdatatype::{self, DictKey};
use crate::exceptions::PyBaseExceptionRef;
use crate::function::{KwArgs, OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, KwArgs, OptionalArg};
use crate::pyobject::{
BorrowValue, IdProtocol, IntoPyObject, ItemProtocol, PyArithmaticValue::*, PyAttributes,
PyClassImpl, PyComparisonValue, PyContext, PyIterable, PyObjectRef, PyRef, PyResult, PyValue,
@@ -53,7 +53,7 @@ impl PyValue for PyDict {
#[pyimpl(with(Hashable, Comparable), flags(BASETYPE))]
impl PyDict {
#[pyslot]
fn tp_new(class: PyTypeRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
fn tp_new(class: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
PyDict {
entries: DictContentType::default(),
}
@@ -83,7 +83,7 @@ impl PyDict {
dict.insert(vm, key, value)?;
}
} else if let Some(keys) = vm.get_method(dict_obj.clone(), "keys") {
let keys = objiter::get_iter(vm, &vm.invoke(&keys?, vec![])?)?;
let keys = objiter::get_iter(vm, &vm.invoke(&keys?, ())?)?;
while let Some(key) = objiter::get_next_object(vm, &keys)? {
let val = dict_obj.get_item(key.clone(), vm)?;
dict.insert(vm, key, val)?;
@@ -433,7 +433,7 @@ impl PyDictRef {
if let Some(method_or_err) = vm.get_method(self.clone().into_object(), "__missing__") {
let method = method_or_err?;
Ok(Some(vm.invoke(&method, vec![key.into_pyobject(vm)])?))
Ok(Some(vm.invoke(&method, (key,))?))
} else {
Ok(None)
}
+1 -1
View File
@@ -514,7 +514,7 @@ fn to_float(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<f64> {
obj.class().name
)
})?;
let result = vm.invoke(&method, vec![])?;
let result = vm.invoke(&method, ())?;
PyFloatRef::try_from_object(vm, result)?.to_f64()
};
Ok(value)
+6 -6
View File
@@ -8,7 +8,7 @@ use super::objtuple::PyTupleRef;
use super::objtype::PyTypeRef;
use crate::bytecode;
use crate::frame::Frame;
use crate::function::PyFuncArgs;
use crate::function::FuncArgs;
use crate::obj::objasyncgenerator::PyAsyncGen;
use crate::obj::objcoroutine::PyCoroutine;
use crate::obj::objgenerator::PyGenerator;
@@ -65,7 +65,7 @@ impl PyFunction {
&self,
code_object: &bytecode::CodeObject,
locals: &PyDictRef,
func_args: PyFuncArgs,
func_args: FuncArgs,
vm: &VirtualMachine,
) -> PyResult<()> {
let nargs = func_args.args.len();
@@ -216,7 +216,7 @@ impl PyFunction {
pub fn invoke_with_scope(
&self,
func_args: PyFuncArgs,
func_args: FuncArgs,
scope: &Scope,
vm: &VirtualMachine,
) -> PyResult {
@@ -258,7 +258,7 @@ impl PyFunction {
}
}
pub fn invoke(&self, func_args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
pub fn invoke(&self, func_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
self.invoke_with_scope(func_args, &self.scope, vm)
}
}
@@ -321,7 +321,7 @@ impl SlotDescriptor for PyFunction {
}
impl Callable for PyFunction {
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
zelf.invoke(args, vm)
}
}
@@ -335,7 +335,7 @@ pub struct PyBoundMethod {
}
impl Callable for PyBoundMethod {
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let args = args.insert(zelf.object.clone());
vm.invoke(&zelf.function, args)
}
+2 -2
View File
@@ -1,5 +1,5 @@
use crate::exceptions::PyBaseExceptionRef;
use crate::function::PyFuncArgs;
use crate::function::FuncArgs;
use crate::obj::objdict::PyDictRef;
use crate::obj::objfunction::{PyFunction, PyFunctionRef};
use crate::obj::{objfloat, objint};
@@ -125,7 +125,7 @@ fn get_jit_value(vm: &VirtualMachine, obj: &PyObjectRef) -> Result<AbiValue, Arg
#[cfg(feature = "jit")]
pub(crate) fn get_jit_args<'a>(
func: &PyFunction,
func_args: &PyFuncArgs,
func_args: &FuncArgs,
jitted_code: &'a CompiledCode,
vm: &VirtualMachine,
) -> Result<Args<'a>, ArgsError> {
+2 -2
View File
@@ -14,7 +14,7 @@ use super::objfloat;
use super::objstr::{PyStr, PyStrRef};
use super::objtype::PyTypeRef;
use crate::format::FormatSpec;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::OptionalArg;
use crate::pyobject::{
BorrowValue, IdProtocol, IntoPyObject, IntoPyResult, PyArithmaticValue, PyClassImpl,
PyComparisonValue, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
@@ -732,7 +732,7 @@ pub(crate) fn to_int(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<BigInt>
return try_convert(s.borrow_value().as_bytes());
}
if let Some(method) = vm.get_method(obj.clone(), "__int__") {
let result = vm.invoke(&method?, PyFuncArgs::default())?;
let result = vm.invoke(&method?, ())?;
return match result.payload::<PyInt>() {
Some(int_obj) => Ok(int_obj.borrow_value().clone()),
None => Err(vm.new_type_error(format!(
+5 -5
View File
@@ -22,7 +22,7 @@ use crate::vm::VirtualMachine;
pub fn get_iter(vm: &VirtualMachine, iter_target: &PyObjectRef) -> PyResult {
if let Some(method_or_err) = vm.get_method(iter_target.clone(), "__iter__") {
let method = method_or_err?;
let iter = vm.invoke(&method, vec![])?;
let iter = vm.invoke(&method, ())?;
if iter.has_class_attr("__next__") {
Ok(iter)
} else {
@@ -42,7 +42,7 @@ pub fn get_iter(vm: &VirtualMachine, iter_target: &PyObjectRef) -> PyResult {
}
pub fn call_next(vm: &VirtualMachine, iter_obj: &PyObjectRef) -> PyResult {
vm.call_method(iter_obj, "__next__", vec![])
vm.call_method(iter_obj, "__next__", ())
}
/*
@@ -113,7 +113,7 @@ pub fn length_hint(vm: &VirtualMachine, iter: PyObjectRef) -> PyResult<Option<us
Some(hint) => hint?,
None => return Ok(None),
};
let result = match vm.invoke(&hint, vec![]) {
let result = match vm.invoke(&hint, ()) {
Ok(res) => res,
Err(e) => {
return if objtype::isinstance(&e, &vm.ctx.exceptions.type_error) {
@@ -176,7 +176,7 @@ impl PySequenceIterator {
let step: isize = if self.reversed { -1 } else { 1 };
let pos = self.position.fetch_add(step);
if pos >= 0 {
match vm.call_method(&self.obj, "__getitem__", vec![vm.ctx.new_int(pos)]) {
match vm.call_method(&self.obj, "__getitem__", (pos,)) {
Err(ref e) if objtype::isinstance(&e, &vm.ctx.exceptions.index_error) => {
Err(new_stop_iteration(vm))
}
@@ -242,7 +242,7 @@ impl PyCallableIterator {
return Err(new_stop_iteration(vm));
}
let ret = self.callable.invoke(vec![], vm)?;
let ret = self.callable.invoke((), vm)?;
if vm.bool_eq(&ret, &self.sentinel)? {
self.done.store(true);
+4 -4
View File
@@ -104,7 +104,7 @@ impl PyMappingProxy {
PyDict::from_attributes(c.attributes.read().clone(), vm)?.into_pyobject(vm)
}
};
vm.call_method(&obj, "items", vec![])
vm.call_method(&obj, "items", ())
}
#[pymethod]
pub fn keys(&self, vm: &VirtualMachine) -> PyResult {
@@ -114,7 +114,7 @@ impl PyMappingProxy {
PyDict::from_attributes(c.attributes.read().clone(), vm)?.into_pyobject(vm)
}
};
vm.call_method(&obj, "keys", vec![])
vm.call_method(&obj, "keys", ())
}
#[pymethod]
pub fn values(&self, vm: &VirtualMachine) -> PyResult {
@@ -124,12 +124,12 @@ impl PyMappingProxy {
PyDict::from_attributes(c.attributes.read().clone(), vm)?.into_pyobject(vm)
}
};
vm.call_method(&obj, "values", vec![])
vm.call_method(&obj, "values", ())
}
#[pymethod]
pub fn copy(&self, vm: &VirtualMachine) -> PyResult {
match &self.mapping {
MappingProxyInner::Dict(d) => vm.call_method(d, "copy", vec![]),
MappingProxyInner::Dict(d) => vm.call_method(d, "copy", ()),
MappingProxyInner::Class(c) => {
Ok(PyDict::from_attributes(c.attributes.read().clone(), vm)?.into_pyobject(vm))
}
+3 -3
View File
@@ -1,7 +1,7 @@
use super::objdict::PyDictRef;
use super::objstr::{PyStr, PyStrRef};
use super::objtype::PyTypeRef;
use crate::function::{OptionalOption, PyFuncArgs};
use crate::function::{FuncArgs, OptionalOption};
use crate::pyobject::{
BorrowValue, IntoPyObject, ItemProtocol, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult,
PyValue,
@@ -46,7 +46,7 @@ pub fn init_module_dict(
#[pyimpl(with(SlotGetattro), flags(BASETYPE, HAS_DICT))]
impl PyModule {
#[pyslot]
fn tp_new(cls: PyTypeRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyModuleRef> {
fn tp_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyModuleRef> {
PyModule {}.into_ref_with_type(vm, cls)
}
@@ -84,7 +84,7 @@ impl PyModule {
fn repr(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult {
let importlib = vm.import("_frozen_importlib", &[], 0)?;
let module_repr = vm.get_attribute(importlib, "_module_repr")?;
vm.invoke(&module_repr, vec![zelf.into_object()])
vm.invoke(&module_repr, (zelf,))
}
#[pymethod(magic)]
+9 -9
View File
@@ -4,7 +4,7 @@ use super::objlist::PyList;
use super::objstr::PyStrRef;
use super::objtype::PyTypeRef;
use crate::common::hash::PyHash;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::obj::objtype::PyType;
use crate::pyobject::{
BorrowValue, Either, IdProtocol, ItemProtocol, PyArithmaticValue, PyAttributes, PyClassImpl,
@@ -28,7 +28,7 @@ impl PyValue for PyBaseObject {
#[pyimpl(flags(BASETYPE))]
impl PyBaseObject {
#[pyslot]
fn tp_new(mut args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn tp_new(mut args: FuncArgs, vm: &VirtualMachine) -> PyResult {
// more or less __new__ operator
let cls = PyTypeRef::try_from_object(vm, args.shift())?;
let dict = if cls.is(&vm.ctx.types.object_type) {
@@ -163,7 +163,7 @@ impl PyBaseObject {
#[pymethod(magic)]
fn str(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
vm.call_method(&zelf, "__repr__", vec![])
vm.call_method(&zelf, "__repr__", ())
}
#[pymethod(magic)]
@@ -172,7 +172,7 @@ impl PyBaseObject {
}
#[pyclassmethod(magic)]
fn subclasshook(_args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn subclasshook(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.not_implemented())
}
@@ -187,7 +187,7 @@ impl PyBaseObject {
// Get instance attributes:
if let Some(object_dict) = obj.dict() {
vm.call_method(dict.as_object(), "update", vec![object_dict.into_object()])?;
vm.call_method(dict.as_object(), "update", (object_dict,))?;
}
let attributes: Vec<_> = dict.into_iter().map(|(k, _v)| k).collect();
@@ -207,7 +207,7 @@ impl PyBaseObject {
}
#[pymethod(magic)]
fn init(_args: PyFuncArgs) {}
fn init(_args: FuncArgs) {}
#[pyproperty(name = "__class__")]
fn get_class(obj: PyObjectRef) -> PyObjectRef {
@@ -255,7 +255,7 @@ impl PyBaseObject {
if let Some(reduce) = obj.get_class_attr("__reduce__") {
let object_reduce = vm.ctx.types.object_type.get_attr("__reduce__").unwrap();
if !reduce.is(&object_reduce) {
return vm.invoke(&reduce, vec![]);
return vm.invoke(&reduce, ());
}
}
common_reduce(obj, proto, vm)
@@ -316,10 +316,10 @@ fn common_reduce(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResul
if proto >= 2 {
let reducelib = vm.import("__reducelib", &[], 0)?;
let reduce_2 = vm.get_attribute(reducelib, "reduce_2")?;
vm.invoke(&reduce_2, vec![obj])
vm.invoke(&reduce_2, (obj,))
} else {
let copyreg = vm.import("copyreg", &[], 0)?;
let reduce_ex = vm.get_attribute(copyreg, "_reduce_ex")?;
vm.invoke(&reduce_ex, vec![obj, vm.ctx.new_int(proto)])
vm.invoke(&reduce_ex, (obj, proto))
}
}
+4 -4
View File
@@ -4,7 +4,7 @@
use crate::common::lock::PyRwLock;
use super::objtype::PyTypeRef;
use crate::function::PyFuncArgs;
use crate::function::FuncArgs;
use crate::pyobject::{
PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
};
@@ -83,7 +83,7 @@ impl SlotDescriptor for PyProperty {
if vm.is_none(&obj) {
Ok(zelf.into_object())
} else if let Some(getter) = zelf.getter.read().as_ref() {
vm.invoke(&getter, obj)
vm.invoke(&getter, (obj,))
} else {
Err(vm.new_attribute_error("unreadable attribute".to_string()))
}
@@ -93,7 +93,7 @@ impl SlotDescriptor for PyProperty {
#[pyimpl(with(SlotDescriptor), flags(BASETYPE))]
impl PyProperty {
#[pyslot]
fn tp_new(cls: PyTypeRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyPropertyRef> {
fn tp_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyPropertyRef> {
PyProperty {
getter: PyRwLock::new(None),
setter: PyRwLock::new(None),
@@ -125,7 +125,7 @@ impl PyProperty {
#[pymethod(name = "__delete__")]
fn delete(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if let Some(ref deleter) = self.deleter.read().as_ref() {
vm.invoke(deleter, obj)
vm.invoke(deleter, (obj,))
} else {
Err(vm.new_attribute_error("can't delete attribute".to_owned()))
}
+2 -2
View File
@@ -9,7 +9,7 @@ use super::objslice::{PySlice, PySliceRef};
use super::objtype::PyTypeRef;
use crate::common::hash::PyHash;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::pyobject::{
self, BorrowValue, IdProtocol, IntoPyRef, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult,
PyValue, TryFromObject, TypeProtocol,
@@ -306,7 +306,7 @@ impl PyRange {
}
#[pyslot]
fn tp_new(args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn tp_new(args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let range = if args.args.len() <= 2 {
let (cls, stop) = args.bind(vm)?;
PyRange::new(cls, stop, vm)
+2 -2
View File
@@ -2,7 +2,7 @@
use super::objint::PyInt;
use super::objtype::PyTypeRef;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::pyobject::{
BorrowValue, IntoPyObject, PyClassImpl, PyComparisonValue, PyContext, PyObjectRef, PyRef,
PyResult, PyValue, TryIntoRef, TypeProtocol,
@@ -94,7 +94,7 @@ impl PySlice {
}
#[pyslot]
fn tp_new(cls: PyTypeRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PySliceRef> {
fn tp_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<PySliceRef> {
let slice: PySlice = match args.args.len() {
0 => {
return Err(
+2 -2
View File
@@ -20,7 +20,7 @@ use super::objtype::{self, PyTypeRef};
use crate::anystr::{self, adjust_indices, AnyStr, AnyStrContainer, AnyStrWrapper};
use crate::exceptions::IntoPyException;
use crate::format::{FormatSpec, FormatString, FromTemplate};
use crate::function::{OptionalArg, OptionalOption, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg, OptionalOption};
use crate::pyobject::{
BorrowValue, Either, IdProtocol, IntoPyObject, ItemProtocol, PyClassImpl, PyComparisonValue,
PyContext, PyIterable, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TryIntoRef,
@@ -576,7 +576,7 @@ impl PyStr {
}
#[pymethod]
fn format(&self, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<String> {
fn format(&self, args: FuncArgs, vm: &VirtualMachine) -> PyResult<String> {
match FormatString::from_str(self.borrow_value()) {
Ok(format_string) => format_string.format(&args, vm),
Err(err) => Err(err.into_pyexception(vm)),
+1 -1
View File
@@ -151,7 +151,7 @@ impl SlotDescriptor for PySuper {
let obj = vm.unwrap_or_none(zelf.obj.clone().map(|(o, _)| o));
vm.invoke(
zelf.as_object().clone_class().as_object(),
vec![zelf.typ.clone().into_object(), obj],
(zelf.typ.clone(), obj),
)
}
}
+23 -36
View File
@@ -12,7 +12,7 @@ use super::objstaticmethod::PyStaticMethod;
use super::objstr::PyStrRef;
use super::objtuple::PyTuple;
use super::objweakref::PyWeak;
use crate::function::{KwArgs, PyFuncArgs};
use crate::function::{FuncArgs, KwArgs};
use crate::pyobject::{
BorrowValue, Either, IdProtocol, PyAttributes, PyClassImpl, PyContext, PyIterable, PyLease,
PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
@@ -152,10 +152,7 @@ impl PyType {
"__get__" => {
let func: slots::DescrGetFunc = |zelf, obj, cls, vm| {
let magic = get_class_magic(&zelf, "__get__");
vm.invoke(
&magic,
vec![zelf, vm.unwrap_or_none(obj), vm.unwrap_or_none(cls)],
)
vm.invoke(&magic, (zelf, obj, cls))
} as _;
self.slots.descr_get.store(Some(func))
}
@@ -176,7 +173,8 @@ impl PyType {
"__del__" => {
let func: slots::DelFunc = |zelf, vm| {
let magic = get_class_magic(&zelf, "__del__");
vm.invoke(&magic, vec![zelf.clone()]).map(|_| ())
let _ = vm.invoke(&magic, vec![zelf.clone()])?;
Ok(())
} as _;
self.slots.del.store(Some(func));
}
@@ -191,7 +189,7 @@ impl PyType {
"__getattribute__" => {
let func: slots::GetattroFunc = |zelf, name, vm| {
let magic = get_class_magic(&zelf, "__getattribute__");
vm.invoke(&magic, vec![zelf, name.into_object()])
vm.invoke(&magic, (zelf, name))
};
self.slots.getattro.store(Some(func))
}
@@ -315,7 +313,7 @@ impl PyType {
) -> PyResult<()> {
if let Some(attr) = zelf.get_class_attr(attr_name.borrow_value()) {
if let Some(ref descriptor) = attr.get_class_attr("__set__") {
vm.invoke(descriptor, vec![attr, zelf.into_object(), value])?;
vm.invoke(descriptor, (attr, zelf, value))?;
return Ok(());
}
}
@@ -331,9 +329,7 @@ impl PyType {
fn delattr(zelf: PyRef<Self>, attr_name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
if let Some(attr) = zelf.get_class_attr(attr_name.borrow_value()) {
if let Some(ref descriptor) = attr.get_class_attr("__delete__") {
return vm
.invoke(descriptor, vec![attr, zelf.into_object()])
.map(|_| ());
return vm.invoke(descriptor, (attr, zelf)).map(|_| ());
}
}
@@ -364,7 +360,7 @@ impl PyType {
)
}
#[pyslot]
fn tp_new(metatype: PyTypeRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn tp_new(metatype: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
vm_trace!("type.__new__ {:?}", args);
let is_type_type = metatype.is(&vm.ctx.types.type_type);
@@ -459,20 +455,17 @@ impl PyType {
for (name, obj) in typ.attributes.read().clone().iter() {
if let Some(meth) = vm.get_method(obj.clone(), "__set_name__") {
let set_name = meth?;
vm.invoke(
&set_name,
vec![typ.clone().into_object(), vm.ctx.new_str(name.clone())],
)
.map_err(|e| {
let err = vm.new_runtime_error(format!(
"Error calling __set_name__ on '{}' instance {} in '{}'",
obj.class().name,
name,
typ.name
));
err.set_cause(Some(e));
err
})?;
vm.invoke(&set_name, (typ.clone(), name.clone()))
.map_err(|e| {
let err = vm.new_runtime_error(format!(
"Error calling __set_name__ on '{}' instance {} in '{}'",
obj.class().name,
name,
typ.name
));
err.set_cause(Some(e));
err
})?;
}
}
@@ -538,13 +531,7 @@ impl SlotGetattro for PyType {
drop(mcl);
vm.call_if_get_descriptor(attr, zelf.into_object())
} else if let Some(ref getter) = zelf.get_attr("__getattr__") {
vm.invoke(
getter,
vec![
PyLease::into_pyref(mcl).into_object(),
name_str.into_object(),
],
)
vm.invoke(getter, (PyLease::into_pyref(mcl), name_str))
} else {
Err(vm.new_attribute_error(format!(
"type object '{}' has no attribute '{}'",
@@ -555,7 +542,7 @@ impl SlotGetattro for PyType {
}
impl Callable for PyType {
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
vm_trace!("type_call: {:?}", zelf);
let obj = call_tp_new(zelf.clone(), zelf.clone(), args.clone(), vm)?;
@@ -668,7 +655,7 @@ pub fn issubclass<T: DerefToPyType + IdProtocol, R: IdProtocol>(subclass: T, cls
fn call_tp_new(
typ: PyTypeRef,
subtype: PyTypeRef,
args: PyFuncArgs,
args: FuncArgs,
vm: &VirtualMachine,
) -> PyResult {
for cls in typ.deref().iter_mro() {
@@ -688,7 +675,7 @@ fn call_tp_new(
pub fn tp_new_wrapper(
zelf: PyTypeRef,
cls: PyTypeRef,
args: PyFuncArgs,
args: FuncArgs,
vm: &VirtualMachine,
) -> PyResult {
if !issubclass(&cls, &zelf) {
+2 -2
View File
@@ -1,6 +1,6 @@
use super::objtype::PyTypeRef;
use crate::common::hash::PyHash;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::pyobject::{
IdProtocol, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
};
@@ -39,7 +39,7 @@ impl PyValue for PyWeak {
pub type PyWeakRef = PyRef<PyWeak>;
impl Callable for PyWeak {
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
args.bind::<()>(vm)?;
Ok(vm.unwrap_or_none(zelf.upgrade()))
}
+1 -2
View File
@@ -26,8 +26,7 @@ impl Write for PyWriter<'_> {
type Error = PyBaseExceptionRef;
fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), Self::Error> {
let PyWriter(obj, vm) = self;
vm.call_method(obj, "write", vec![vm.ctx.new_str(args.to_string())])
.map(drop)
vm.call_method(obj, "write", (args.to_string(),)).map(drop)
}
}
+7 -14
View File
@@ -4,14 +4,13 @@ use std::fmt;
use std::marker::PhantomData;
use std::ops::Deref;
use indexmap::IndexMap;
use num_bigint::BigInt;
use num_complex::Complex64;
use num_traits::ToPrimitive;
use crate::bytecode;
use crate::exceptions::{self, PyBaseExceptionRef};
use crate::function::{IntoPyNativeFunc, PyFuncArgs};
use crate::function::{IntoFuncArgs, IntoPyNativeFunc};
use crate::obj::objbuiltinfunc::PyFuncDef;
use crate::obj::objbytearray;
use crate::obj::objbytes;
@@ -628,7 +627,7 @@ pub struct PyCallable {
impl PyCallable {
#[inline]
pub fn invoke(&self, args: impl Into<PyFuncArgs>, vm: &VirtualMachine) -> PyResult {
pub fn invoke(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult {
vm.invoke(&self.obj, args)
}
@@ -788,15 +787,15 @@ where
T: IntoPyObject,
{
fn get_item(&self, key: T, vm: &VirtualMachine) -> PyResult {
vm.call_method(self, "__getitem__", key.into_pyobject(vm))
vm.call_method(self, "__getitem__", (key,))
}
fn set_item(&self, key: T, value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
vm.call_method(self, "__setitem__", vec![key.into_pyobject(vm), value])
vm.call_method(self, "__setitem__", (key, value))
}
fn del_item(&self, key: T, vm: &VirtualMachine) -> PyResult {
vm.call_method(self, "__delitem__", key.into_pyobject(vm))
vm.call_method(self, "__delitem__", (key,))
}
}
@@ -832,13 +831,7 @@ impl<T> PyIterable<T> {
/// `__iter__` method of the iterable object.
pub fn iter<'a>(&self, vm: &'a VirtualMachine) -> PyResult<PyIterator<'a, T>> {
let method = &self.method;
let iter_obj = vm.invoke(
method,
PyFuncArgs {
args: vec![],
kwargs: IndexMap::new(),
},
)?;
let iter_obj = vm.invoke(method, ())?;
let length_hint = objiter::length_hint(vm, iter_obj.clone())?;
@@ -865,7 +858,7 @@ where
type Item = PyResult<T>;
fn next(&mut self) -> Option<Self::Item> {
match self.vm.call_method(&self.obj, "__next__", vec![]) {
match self.vm.call_method(&self.obj, "__next__", ()) {
Ok(value) => Some(T::try_from_object(self.vm, value)),
Err(err) => {
if objtype::isinstance(&err, &self.vm.ctx.exceptions.stop_iteration) {
+1 -1
View File
@@ -160,7 +160,7 @@ where
let tb_module = vm.import("traceback", &[], 0).unwrap();
// TODO: set exc traceback
let print_stack = vm.get_attribute(tb_module, "print_stack").unwrap();
vm.invoke(&print_stack, vec![]).unwrap();
vm.invoke(&print_stack, ()).unwrap();
if let Ok(repr) = vm.to_repr(e.as_object()) {
println!("{}", repr.borrow_value());
+5 -5
View File
@@ -2,7 +2,7 @@ use std::cmp::Ordering;
use crate::common::hash::PyHash;
use crate::common::lock::PyRwLock;
use crate::function::{OptionalArg, PyFuncArgs, PyNativeFunc};
use crate::function::{FuncArgs, OptionalArg, PyNativeFunc};
use crate::obj::objmemory::Buffer;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{
@@ -42,7 +42,7 @@ impl Default for PyTpFlags {
}
}
pub(crate) type GenericMethod = fn(&PyObjectRef, PyFuncArgs, &VirtualMachine) -> PyResult;
pub(crate) type GenericMethod = fn(&PyObjectRef, FuncArgs, &VirtualMachine) -> PyResult;
pub(crate) type DelFunc = fn(&PyObjectRef, &VirtualMachine) -> PyResult<()>;
pub(crate) type DescrGetFunc =
fn(PyObjectRef, Option<PyObjectRef>, Option<PyObjectRef>, &VirtualMachine) -> PyResult;
@@ -107,7 +107,7 @@ pub trait SlotDesctuctor: PyValue {
#[pyimpl]
pub trait Callable: PyValue {
#[pyslot]
fn tp_call(zelf: &PyObjectRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn tp_call(zelf: &PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
if let Some(zelf) = zelf.downcast_ref() {
Self::call(zelf, args, vm)
} else {
@@ -115,10 +115,10 @@ pub trait Callable: PyValue {
}
}
#[pymethod]
fn __call__(zelf: PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn __call__(zelf: PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
Self::call(&zelf, args, vm)
}
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult;
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult;
}
#[pyimpl]
+2 -2
View File
@@ -2,12 +2,12 @@ pub(crate) use atexit::make_module;
#[pymodule]
mod atexit {
use crate::function::PyFuncArgs;
use crate::function::FuncArgs;
use crate::pyobject::{PyObjectRef, PyResult};
use crate::VirtualMachine;
#[pyfunction]
fn register(func: PyObjectRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyObjectRef {
fn register(func: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
vm.state.atexit_funcs.lock().push((func.clone(), args));
func
}
+4 -4
View File
@@ -3,7 +3,7 @@ use itertools::{self, Itertools};
use std::fmt::{self, Debug, Formatter};
use crate::common::lock::PyRwLock;
use crate::function::PyFuncArgs;
use crate::function::FuncArgs;
use crate::obj::objiter;
use crate::obj::objstr::{self, PyStr};
use crate::obj::objtype::PyTypeRef;
@@ -28,7 +28,7 @@ struct ReaderOption {
}
impl ReaderOption {
fn new(args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<Self> {
fn new(args: FuncArgs, vm: &VirtualMachine) -> PyResult<Self> {
let delimiter = if let Some(delimiter) = args.get_optional_kwarg("delimiter") {
*objstr::borrow_value(&delimiter)
.as_bytes()
@@ -64,7 +64,7 @@ impl ReaderOption {
pub fn build_reader(
iterable: PyIterable<PyObjectRef>,
args: PyFuncArgs,
args: FuncArgs,
vm: &VirtualMachine,
) -> PyResult {
let config = ReaderOption::new(args, vm)?;
@@ -186,7 +186,7 @@ impl Reader {
}
}
fn _csv_reader(fp: PyObjectRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn _csv_reader(fp: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
if let Ok(iterable) = PyIterable::<PyObjectRef>::try_from_object(vm, fp) {
build_reader(iterable, args, vm)
} else {
+2 -2
View File
@@ -3,7 +3,7 @@ pub(crate) use hashlib::make_module;
#[pymodule]
mod hashlib {
use crate::common::lock::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard};
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::obj::objbytes::{PyBytes, PyBytesRef};
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyTypeRef;
@@ -55,7 +55,7 @@ mod hashlib {
}
#[pyslot]
fn tp_new(_cls: PyTypeRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn tp_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
Ok(PyHasher::new("md5", HashWrapper::md5())
.into_ref(vm)
.into_object())
+33 -35
View File
@@ -23,7 +23,7 @@ mod _io {
PyRwLock, PyRwLockReadGuard, PyRwLockUpgradableReadGuard, PyRwLockWriteGuard,
};
use crate::exceptions::{IntoPyException, PyBaseExceptionRef};
use crate::function::{Args, KwArgs, OptionalArg, OptionalOption, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg, OptionalOption};
use crate::obj::objbool;
use crate::obj::objbytearray::PyByteArray;
use crate::obj::objbytes::PyBytesRef;
@@ -227,7 +227,7 @@ mod _io {
#[pyslot]
fn tp_del(instance: &PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
vm.call_method(instance, "close", vec![])?;
vm.call_method(instance, "close", ())?;
Ok(())
}
@@ -237,8 +237,8 @@ mod _io {
}
#[pymethod(magic)]
fn exit(instance: PyObjectRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<()> {
vm.call_method(&instance, "close", vec![])?;
fn exit(instance: PyObjectRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
vm.call_method(&instance, "close", ())?;
Ok(())
}
@@ -268,7 +268,7 @@ mod _io {
fn close(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let closed = objbool::boolval(vm, Self::closed(instance.clone(), vm)?)?;
if !closed {
let res = vm.call_method(&instance, "flush", vec![]);
let res = vm.call_method(&instance, "flush", ());
vm.set_attr(&instance, "__closed", vm.ctx.new_bool(true))?;
res?;
}
@@ -285,8 +285,7 @@ mod _io {
let read = vm.get_attribute(instance, "read")?;
let mut res = Vec::new();
while size.map_or(true, |s| res.len() < s) {
let read_res =
PyBytesLike::try_from_object(vm, vm.invoke(&read, vec![vm.ctx.new_int(1)])?)?;
let read_res = PyBytesLike::try_from_object(vm, vm.invoke(&read, (1,))?)?;
if read_res.with_ref(|b| b.is_empty()) {
break;
}
@@ -325,7 +324,7 @@ mod _io {
msg: OptionalOption<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
if !objbool::boolval(vm, vm.call_method(&instance, "readable", vec![])?)? {
if !objbool::boolval(vm, vm.call_method(&instance, "readable", ())?)? {
let msg = msg
.flatten()
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not readable."));
@@ -341,7 +340,7 @@ mod _io {
msg: OptionalOption<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
if !objbool::boolval(vm, vm.call_method(&instance, "writable", vec![])?)? {
if !objbool::boolval(vm, vm.call_method(&instance, "writable", ())?)? {
let msg = msg
.flatten()
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not writable."));
@@ -357,7 +356,7 @@ mod _io {
msg: OptionalOption<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
if !objbool::boolval(vm, vm.call_method(&instance, "seekable", vec![])?)? {
if !objbool::boolval(vm, vm.call_method(&instance, "seekable", ())?)? {
let msg = msg
.flatten()
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not seekable."));
@@ -373,7 +372,7 @@ mod _io {
}
#[pymethod(magic)]
fn next(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let line = vm.call_method(&instance, "readline", vec![])?;
let line = vm.call_method(&instance, "readline", ())?;
if !objbool::boolval(vm, line.clone())? {
Err(objiter::new_stop_iteration(vm))
} else {
@@ -394,7 +393,7 @@ mod _io {
let b = PyByteArray::from(vec![0; size]).into_ref(vm);
let n = <Option<usize>>::try_from_object(
vm,
vm.call_method(&instance, "readinto", vec![b.as_object().clone()])?,
vm.call_method(&instance, "readinto", (b.clone(),))?,
)?;
Ok(n.map(|n| {
let bytes = &mut b.borrow_value_mut().elements;
@@ -403,7 +402,7 @@ mod _io {
})
.into_pyobject(vm))
} else {
vm.call_method(&instance, "readall", vec![])
vm.call_method(&instance, "readall", ())
}
}
}
@@ -432,7 +431,7 @@ mod _io {
// #[pymethod]
fn fileno(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let raw = vm.get_attribute(instance, "raw")?;
vm.call_method(&raw, "fileno", vec![])
vm.call_method(&raw, "fileno", ())
}
// #[pyproperty]
@@ -450,13 +449,13 @@ mod _io {
// #[pymethod]
fn tell(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let raw = vm.get_attribute(instance, "raw")?;
vm.invoke(&vm.get_attribute(raw, "tell")?, vec![])
vm.invoke(&vm.get_attribute(raw, "tell")?, ())
}
// #[pymethod]
fn close(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let raw = vm.get_attribute(instance, "raw")?;
vm.invoke(&vm.get_attribute(raw, "close")?, vec![])?;
vm.invoke(&vm.get_attribute(raw, "close")?, ())?;
Ok(())
}
}
@@ -517,7 +516,7 @@ mod _io {
vm.call_method(
&vm.get_attribute(instance, "raw")?,
"read",
vec![size.to_usize().into_pyobject(vm)],
(size.to_usize(),),
)
}
@@ -588,7 +587,7 @@ mod _io {
let raw = vm.get_attribute(instance, "raw").unwrap();
//This should be replaced with a more appropriate chunking implementation
vm.call_method(&raw, "write", vec![obj])
vm.call_method(&raw, "write", (obj,))
}
#[pymethod]
@@ -697,7 +696,7 @@ mod _io {
#[pymethod]
fn tell(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let raw = vm.get_attribute(instance, "buffer")?;
vm.invoke(&vm.get_attribute(raw, "tell")?, vec![])
vm.invoke(&vm.get_attribute(raw, "tell")?, ())
}
#[pyproperty]
@@ -715,7 +714,7 @@ mod _io {
#[pymethod]
fn fileno(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let raw = vm.get_attribute(instance, "buffer")?;
vm.call_method(&raw, "fileno", vec![])
vm.call_method(&raw, "fileno", ())
}
#[pymethod]
@@ -732,7 +731,7 @@ mod _io {
return Err(vm.new_value_error("not readable".to_owned()));
}
let bytes = vm.call_method(&raw, "read", vec![vm.unwrap_or_none(size.flatten())])?;
let bytes = vm.call_method(&raw, "read", (size.flatten(),))?;
let bytes = PyBytesLike::try_from_object(vm, bytes)?;
//format bytes into string
let rust_string = String::from_utf8(bytes.to_cow().into_owned()).map_err(|e| {
@@ -758,7 +757,7 @@ mod _io {
let bytes = obj.borrow_value().to_owned().into_bytes();
let len = vm.call_method(&raw, "write", vec![vm.ctx.new_bytes(bytes.clone())])?;
let len = vm.call_method(&raw, "write", (vm.ctx.new_bytes(bytes.clone()),))?;
let len = objint::try_to_primitive(objint::get_value(&len), vm)?;
// returns the count of unicode code points written
@@ -783,8 +782,7 @@ mod _io {
return Err(vm.new_value_error("not readable".to_owned()));
}
let bytes =
vm.call_method(&raw, "readline", vec![vm.unwrap_or_none(size.flatten())])?;
let bytes = vm.call_method(&raw, "readline", (size.flatten(),))?;
let bytes = PyBytesLike::try_from_object(vm, bytes)?;
//format bytes into string
let rust_string = String::from_utf8(bytes.to_cow().into_owned()).map_err(|e| {
@@ -1251,13 +1249,13 @@ mod _io {
})?;
let file_io_obj = vm.invoke(
&file_io_class,
PyFuncArgs::from((
Args::new(vec![file, vm.ctx.new_str(mode.clone())]),
KwArgs::new(maplit::hashmap! {
FuncArgs::new(
vec![file, vm.ctx.new_str(mode.clone())],
maplit::hashmap! {
"closefd".to_owned() => vm.ctx.new_bool(opts.closefd),
"opener".to_owned() => vm.unwrap_or_none(opts.opener),
}),
)),
},
),
)?;
vm.set_attr(&file_io_obj, "mode", vm.ctx.new_str(mode_string))?;
@@ -1271,13 +1269,13 @@ mod _io {
let buffered_writer_class = vm
.get_attribute(io_module.clone(), "BufferedWriter")
.unwrap();
vm.invoke(&buffered_writer_class, vec![file_io_obj])
vm.invoke(&buffered_writer_class, (file_io_obj,))
}
'r' => {
let buffered_reader_class = vm
.get_attribute(io_module.clone(), "BufferedReader")
.unwrap();
vm.invoke(&buffered_reader_class, vec![file_io_obj])
vm.invoke(&buffered_reader_class, (file_io_obj,))
}
//TODO: updating => PyBufferedRandom
_ => unimplemented!("'+' modes is not yet implemented"),
@@ -1288,7 +1286,7 @@ mod _io {
// a TextIOWrapper which is subsequently returned.
't' => {
let text_io_wrapper_class = vm.get_attribute(io_module, "TextIOWrapper").unwrap();
vm.invoke(&text_io_wrapper_class, vec![buffered.unwrap()])
vm.invoke(&text_io_wrapper_class, (buffered.unwrap(),))
}
// If the mode is binary this Buffered class is returned directly at
// this point.
@@ -1474,7 +1472,7 @@ mod fileio {
use super::_io::*;
use crate::byteslike::{PyBytesLike, PyRwBytesLike};
use crate::exceptions::IntoPyException;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyTypeRef;
use crate::pyobject::{
@@ -1529,7 +1527,7 @@ mod fileio {
#[pyimpl(flags(HAS_DICT))]
impl FileIO {
#[pyslot]
fn tp_new(cls: PyTypeRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<FileIORef> {
fn tp_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<FileIORef> {
FileIO {
fd: AtomicCell::new(-1),
closefd: AtomicCell::new(false),
@@ -1546,7 +1544,7 @@ mod fileio {
let name = args.name.clone();
let fd = if let Some(opener) = args.opener {
let mode = compute_c_flag(&mode);
let fd = vm.invoke(&opener, vec![name.clone(), vm.ctx.new_int(mode)])?;
let fd = vm.invoke(&opener, (name.clone(), mode))?;
if !vm.isinstance(&fd, &vm.ctx.types.int_type)? {
return Err(vm.new_type_error("expected integer from opener".to_owned()));
}
+9 -10
View File
@@ -10,7 +10,7 @@ mod decl {
use crate::common::lock::{PyMutex, PyRwLock, PyRwLockWriteGuard};
use crate::common::rc::PyRc;
use crate::function::{Args, OptionalArg, OptionalOption, PyFuncArgs};
use crate::function::{Args, FuncArgs, OptionalArg, OptionalOption};
use crate::obj::objbool;
use crate::obj::objint::{self, PyInt, PyIntRef};
use crate::obj::objiter::{call_next, get_all, get_iter, get_next_object, new_stop_iteration};
@@ -40,7 +40,7 @@ mod decl {
#[pyimpl]
impl PyItertoolsChain {
#[pyslot]
fn tp_new(cls: PyTypeRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
fn tp_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
PyItertoolsChain {
iterables: args.args,
cur_idx: AtomicCell::new(0),
@@ -419,7 +419,7 @@ mod decl {
let obj = call_next(vm, &self.iterable)?;
let predicate = &self.predicate;
let verdict = vm.invoke(predicate, vec![obj.clone()])?;
let verdict = vm.invoke(predicate, (obj.clone(),))?;
let verdict = objbool::boolval(vm, verdict)?;
if verdict {
Ok(obj)
@@ -478,7 +478,7 @@ mod decl {
loop {
let obj = call_next(vm, iterable)?;
let pred = predicate.clone();
let pred_value = vm.invoke(&pred.into_object(), vec![obj.clone()])?;
let pred_value = vm.invoke(&pred.into_object(), (obj.clone(),))?;
if !objbool::boolval(vm, pred_value)? {
self.start_flag.store(true);
return Ok(obj);
@@ -618,7 +618,7 @@ mod decl {
pub(super) fn advance(&self, vm: &VirtualMachine) -> PyResult<(PyObjectRef, PyObjectRef)> {
let new_value = call_next(vm, &self.iterable)?;
let new_key = if let Some(ref kf) = self.key_func {
vm.invoke(kf, new_value.clone())?
vm.invoke(kf, vec![new_value.clone()])?
} else {
new_value.clone()
};
@@ -707,7 +707,7 @@ mod decl {
#[pyimpl]
impl PyItertoolsIslice {
#[pyslot]
fn tp_new(cls: PyTypeRef, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
fn tp_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
let (iter, start, stop, step) = match args.args.len() {
0 | 1 => {
return Err(vm.new_type_error(format!(
@@ -966,7 +966,7 @@ mod decl {
fn from_iter(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let it = get_iter(vm, &iterable)?;
if it.class().is(&PyItertoolsTee::class(vm)) {
return vm.call_method(&it, "__copy__", PyFuncArgs::from(vec![]));
return vm.call_method(&it, "__copy__", ());
}
Ok(PyItertoolsTee {
tee_data: PyItertoolsTeeData::new(it, vm)?,
@@ -989,15 +989,14 @@ mod decl {
let n = n.unwrap_or(2);
let copyable = if iterable.class().has_attr("__copy__") {
vm.call_method(&iterable, "__copy__", PyFuncArgs::from(vec![]))?
vm.call_method(&iterable, "__copy__", ())?
} else {
PyItertoolsTee::from_iter(iterable, vm)?
};
let mut tee_vec: Vec<PyObjectRef> = Vec::with_capacity(n);
for _ in 0..n {
let no_args = PyFuncArgs::from(vec![]);
tee_vec.push(vm.call_method(&copyable, "__copy__", no_args)?);
tee_vec.push(vm.call_method(&copyable, "__copy__", ())?);
}
Ok(PyTupleRef::with_elements(tee_vec, &vm.ctx))
+11 -18
View File
@@ -5,7 +5,7 @@ mod machinery;
mod _json {
use super::*;
use crate::exceptions::PyBaseExceptionRef;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::obj::objiter;
use crate::obj::objstr::PyStrRef;
use crate::obj::{objbool, objtype::PyTypeRef};
@@ -95,14 +95,14 @@ mod _json {
let parse_obj = vm.get_attribute(self.ctx.clone(), "parse_object")?;
return vm.invoke(
&parse_obj,
vec![
(
vm.ctx
.new_tuple(vec![pystr.into_object(), vm.ctx.new_int(next_idx)]),
vm.ctx.new_bool(self.strict),
self.strict,
scan_once,
vm.unwrap_or_none(self.object_hook.clone()),
vm.unwrap_or_none(self.object_pairs_hook.clone()),
],
self.object_hook.clone(),
self.object_pairs_hook.clone(),
),
);
}
'[' => {
@@ -140,7 +140,7 @@ mod _json {
($s:literal) => {
if s.starts_with($s) {
return Ok(vm.ctx.new_tuple(vec![
vm.invoke(&self.parse_constant, vec![vm.ctx.new_str($s.to_owned())])?,
vm.invoke(&self.parse_constant, ($s.to_owned(),))?,
vm.ctx.new_int(idx + $s.len()),
]));
}
@@ -178,12 +178,12 @@ mod _json {
let ret = if has_decimal || has_exponent {
// float
if let Some(ref parse_float) = self.parse_float {
vm.invoke(parse_float, vec![vm.ctx.new_str(buf.to_owned())])
vm.invoke(parse_float, (buf.to_owned(),))
} else {
Ok(vm.ctx.new_float(f64::from_str(buf).unwrap()))
}
} else if let Some(ref parse_int) = self.parse_int {
vm.invoke(parse_int, vec![vm.ctx.new_str(buf.to_owned())])
vm.invoke(parse_int, (buf.to_owned(),))
} else {
Ok(vm.ctx.new_int(BigInt::from_str(buf).unwrap()))
};
@@ -212,7 +212,7 @@ mod _json {
}
impl Callable for JsonScanner {
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let (pystr, idx) = args.bind::<(PyStrRef, isize)>(vm)?;
JsonScanner::call(zelf, pystr, idx, vm)
}
@@ -244,14 +244,7 @@ mod _json {
) -> PyBaseExceptionRef {
let get_error = || -> PyResult<_> {
let cls = vm.try_class("json", "JSONDecodeError")?;
let exc = vm.invoke(
cls.as_object(),
vec![
vm.ctx.new_str(e.msg),
s.into_object(),
vm.ctx.new_int(e.pos),
],
)?;
let exc = vm.invoke(cls.as_object(), (e.msg, s, e.pos))?;
PyBaseExceptionRef::try_from_object(vm, exc)
};
match get_error() {
+3 -3
View File
@@ -7,7 +7,7 @@ mod decl {
use crate::common::borrow::BorrowValue;
use crate::obj::objbytes::PyBytes;
use crate::obj::objcode::{PyCode, PyCodeRef};
use crate::pyobject::{IntoPyObject, PyObjectRef, PyResult, TryFromObject};
use crate::pyobject::{PyObjectRef, PyResult, TryFromObject};
use crate::vm::VirtualMachine;
#[pyfunction]
@@ -17,7 +17,7 @@ mod decl {
#[pyfunction]
fn dump(co: PyCodeRef, f: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
vm.call_method(&f, "write", vec![dumps(co).into_pyobject(vm)])?;
vm.call_method(&f, "write", (dumps(co),))?;
Ok(())
}
@@ -30,7 +30,7 @@ mod decl {
#[pyfunction]
fn load(f: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyCode> {
let read_res = vm.call_method(&f, "read", vec![])?;
let read_res = vm.call_method(&f, "read", ())?;
let bytes = PyBytesLike::try_from_object(vm, read_res)?;
loads(bytes, vm)
}
+1 -1
View File
@@ -251,7 +251,7 @@ fn try_magic_method(func_name: &str, vm: &VirtualMachine, value: &PyObjectRef) -
func_name,
)
})?;
vm.invoke(&method, vec![])
vm.invoke(&method, ())
}
fn math_trunc(value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
+5 -5
View File
@@ -13,7 +13,7 @@ use super::errno::errors;
use crate::byteslike::PyBytesLike;
use crate::common::lock::PyRwLock;
use crate::exceptions::{IntoPyException, PyBaseExceptionRef};
use crate::function::{IntoPyNativeFunc, OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, IntoPyNativeFunc, OptionalArg};
use crate::obj::objbytes::{PyBytes, PyBytesRef};
use crate::obj::objdict::PyDictRef;
use crate::obj::objint::{PyInt, PyIntRef};
@@ -115,7 +115,7 @@ impl TryFromObject for PyPathLike {
obj.class().name
)
})?;
let result = vm.invoke(&method, PyFuncArgs::default())?;
let result = vm.invoke(&method, ())?;
match1(&result)?.ok_or_else(|| {
vm.new_type_error(format!(
"expected {}.__fspath__() to return str or bytes, not '{}'",
@@ -334,7 +334,7 @@ mod _os {
#[cfg(not(any(unix, windows, target_os = "wasi")))]
#[pyfunction]
pub(crate) fn open(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
pub(crate) fn open(vm: &VirtualMachine, args: FuncArgs) -> PyResult {
Err(vm.new_os_error("os.open not implemented on this platform".to_owned()))
}
@@ -596,7 +596,7 @@ mod _os {
}
#[pymethod(name = "__exit__")]
fn exit(zelf: PyRef<Self>, _args: PyFuncArgs) {
fn exit(zelf: PyRef<Self>, _args: FuncArgs) {
zelf.close()
}
}
@@ -1957,7 +1957,7 @@ mod posix {
let id = PosixSpawnFileActionIdentifier::try_from(id).map_err(|_| {
vm.new_type_error("Unknown file_actions identifier".to_owned())
})?;
let args = PyFuncArgs::from(args.to_vec());
let args = FuncArgs::from(args.to_vec());
let ret = match id {
PosixSpawnFileActionIdentifier::Open => {
let (fd, path, oflag, mode): (_, PyPathLike, _, _) = args.bind(vm)?;
+1 -1
View File
@@ -62,7 +62,7 @@ impl TryFromObject for Selectable {
let meth = vm.get_method_or_type_error(obj.clone(), "fileno", || {
"select arg must be an int or object with a fileno() method".to_owned()
})?;
RawFd::try_from_object(vm, vm.invoke(&meth, vec![])?)
RawFd::try_from_object(vm, vm.invoke(&meth, ())?)
})?;
Ok(Selectable { obj, fno })
}
+1 -9
View File
@@ -33,15 +33,7 @@ mod _serde_json {
let mut err_msg = err.to_string();
let pos = err_msg.rfind(" at line ").unwrap();
err_msg.truncate(pos);
let decode_error = vm.invoke(
&from_serde,
vec![
vm.ctx.new_str(err_msg),
s.into_object(),
vm.ctx.new_int(err.line()),
vm.ctx.new_int(err.column()),
],
)?;
let decode_error = vm.invoke(&from_serde, (err_msg, s, err.line(), err.column()))?;
PyBaseExceptionRef::try_from_object(vm, decode_error)
}
}
+1 -1
View File
@@ -112,7 +112,7 @@ pub fn check_signals(vm: &VirtualMachine) -> PyResult<()> {
if triggerd {
let handler = &signal_handlers[signum];
if vm.is_callable(handler) {
vm.invoke(handler, vec![vm.ctx.new_int(signum), vm.ctx.none()])?;
vm.invoke(handler, (signum, vm.ctx.none()))?;
}
}
}
+2 -2
View File
@@ -12,7 +12,7 @@ use socket2::{Domain, Protocol, Socket, Type as SocketType};
use crate::byteslike::PyBytesLike;
use crate::exceptions::{IntoPyException, PyBaseExceptionRef};
use crate::function::{OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::obj::objbytearray::PyByteArrayRef;
use crate::obj::objbytes::PyBytesRef;
use crate::obj::objstr::{PyStr, PyStrRef};
@@ -82,7 +82,7 @@ impl PySocket {
}
#[pyslot]
fn tp_new(cls: PyTypeRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
fn tp_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
PySocket {
kind: AtomicCell::default(),
family: AtomicCell::default(),
+9 -9
View File
@@ -1,6 +1,6 @@
/// Implementation of the _thread module
use crate::exceptions::{self, IntoPyException};
use crate::function::{Args, KwArgs, OptionalArg, PyFuncArgs};
use crate::function::{FuncArgs, OptionalArg};
use crate::obj::objdict::PyDictRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtuple::PyTupleRef;
@@ -131,7 +131,7 @@ impl PyLock {
}
#[pymethod(magic)]
fn exit(&self, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn exit(&self, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
self.release(vm)
}
@@ -192,7 +192,7 @@ impl PyRLock {
}
#[pymethod(magic)]
fn exit(&self, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn exit(&self, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
self.release(vm)
}
@@ -222,10 +222,10 @@ fn _thread_start_new_thread(
kwargs: OptionalArg<PyDictRef>,
vm: &VirtualMachine,
) -> PyResult<u64> {
let args = PyFuncArgs::from((
Args::from(args.borrow_value().to_owned()),
KwArgs::from(kwargs.map_or_else(Default::default, |k| k.to_attributes())),
));
let args = FuncArgs::new(
args.borrow_value().to_owned(),
kwargs.map_or_else(Default::default, |k| k.to_attributes()),
);
let mut thread_builder = thread::Builder::new();
let stacksize = vm.state.stacksize.load();
if stacksize != 0 {
@@ -243,7 +243,7 @@ fn _thread_start_new_thread(
.map_err(|err| err.into_pyexception(vm))
}
fn run_thread(func: PyCallable, args: PyFuncArgs, vm: &VirtualMachine) {
fn run_thread(func: PyCallable, args: FuncArgs, vm: &VirtualMachine) {
if let Err(exc) = func.invoke(args, vm) {
// TODO: sys.unraisablehook
let stderr = std::io::stderr();
@@ -303,7 +303,7 @@ impl PyLocal {
}
#[pyslot]
fn tp_new(cls: PyTypeRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
fn tp_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
PyLocal {
data: ThreadLocal::new(),
}
+3 -3
View File
@@ -3,7 +3,7 @@ use std::{env, mem, path};
use crate::common::hash::{PyHash, PyUHash};
use crate::frame::FrameRef;
use crate::function::{Args, OptionalArg, PyFuncArgs};
use crate::function::{Args, FuncArgs, OptionalArg};
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyTypeRef;
use crate::pyobject::{
@@ -130,7 +130,7 @@ impl SysFlags {
}
#[pyslot]
fn tp_new(_cls: PyTypeRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
fn tp_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("cannot create 'sys.flags' instances".to_owned()))
}
}
@@ -237,7 +237,7 @@ fn sys_exit(code: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
Err(vm.new_exception(vm.ctx.exceptions.system_exit.clone(), vec![code]))
}
fn sys_audit(_args: PyFuncArgs) {
fn sys_audit(_args: FuncArgs) {
// TODO: sys.audit implementation
}
+1 -1
View File
@@ -47,7 +47,7 @@ impl VersionInfo {
#[pyslot]
fn tp_new(
_cls: crate::obj::objtype::PyTypeRef,
_args: crate::function::PyFuncArgs,
_args: crate::function::FuncArgs,
vm: &crate::VirtualMachine,
) -> crate::pyobject::PyResult {
Err(vm.new_type_error("cannot create 'sys.version_info' instances".to_owned()))
+20 -39
View File
@@ -19,7 +19,7 @@ use crate::common::{hash::HashSecret, lock::PyMutex, rc::PyRc};
use crate::exceptions::{self, PyBaseException, PyBaseExceptionRef};
use crate::frame::{ExecutionResult, Frame, FrameRef};
use crate::frozen;
use crate::function::PyFuncArgs;
use crate::function::{FuncArgs, IntoFuncArgs};
use crate::import;
use crate::obj::objbool;
use crate::obj::objcode::{PyCode, PyCodeRef};
@@ -124,7 +124,7 @@ pub struct PyGlobalState {
pub stacksize: AtomicCell<usize>,
pub thread_count: AtomicCell<usize>,
pub hash_secret: HashSecret,
pub atexit_funcs: PyMutex<Vec<(PyObjectRef, PyFuncArgs)>>,
pub atexit_funcs: PyMutex<Vec<(PyObjectRef, FuncArgs)>>,
}
pub const NSIG: usize = 64;
@@ -322,8 +322,7 @@ impl VirtualMachine {
let io = import::import_builtin(self, "_io")?;
let io_open = self.get_attribute(io, "open")?;
let set_stdio = |name, fd, mode: &str| {
let stdio =
self.invoke(&io_open, vec![self.ctx.new_int(fd), self.new_pyobj(mode)])?;
let stdio = self.invoke(&io_open, (fd, mode))?;
self.set_attr(
&self.sys_module,
format!("__{}__", name), // e.g. __stdin__
@@ -756,7 +755,7 @@ impl VirtualMachine {
if obj.class().is(&self.ctx.types.str_type) {
Ok(obj.clone().downcast().unwrap())
} else {
let s = self.call_method(&obj, "__str__", vec![])?;
let s = self.call_method(&obj, "__str__", ())?;
PyStrRef::try_from_object(self, s)
}
}
@@ -767,12 +766,12 @@ impl VirtualMachine {
}
pub fn to_repr(&self, obj: &PyObjectRef) -> PyResult<PyStrRef> {
let repr = self.call_method(obj, "__repr__", vec![])?;
let repr = self.call_method(obj, "__repr__", ())?;
TryFromObject::try_from_object(self, repr)
}
pub fn to_ascii(&self, obj: &PyObjectRef) -> PyResult {
let repr = self.call_method(obj, "__repr__", vec![])?;
let repr = self.call_method(obj, "__repr__", ())?;
let repr: PyStrRef = TryFromObject::try_from_object(self, repr)?;
let ascii = to_ascii(repr.borrow_value());
Ok(self.ctx.new_str(ascii))
@@ -783,7 +782,7 @@ impl VirtualMachine {
if let Ok(val) = TryFromObject::try_from_object(self, obj.clone()) {
Ok(val)
} else if obj.class().has_attr("__index__") {
self.call_method(obj, "__index__", vec![]).and_then(|r| {
self.call_method(obj, "__index__", ()).and_then(|r| {
if let Ok(val) = TryFromObject::try_from_object(self, r) {
Ok(val)
} else {
@@ -840,17 +839,8 @@ impl VirtualMachine {
let from_list = self
.ctx
.new_tuple(from_list.iter().map(|name| self.new_pyobj(name)).collect());
self.invoke(
&import_func,
vec![
self.new_pyobj(module),
globals,
locals,
from_list,
self.ctx.new_int(level),
],
)
.map_err(|exc| import::remove_importlib_frames(self, &exc))
self.invoke(&import_func, (module, globals, locals, from_list, level))
.map_err(|exc| import::remove_importlib_frames(self, &exc))
}
}
}
@@ -863,7 +853,7 @@ impl VirtualMachine {
if obj.class().is(cls) {
Ok(true)
} else {
let ret = self.call_method(cls.as_object(), "__instancecheck__", vec![obj.clone()])?;
let ret = self.call_method(cls.as_object(), "__instancecheck__", (obj.clone(),))?;
objbool::boolval(self, ret)
}
}
@@ -871,11 +861,7 @@ impl VirtualMachine {
/// Determines if `subclass` is a subclass of `cls`, either directly, indirectly or virtually
/// via the __subclasscheck__ magic method.
pub fn issubclass(&self, subclass: &PyTypeRef, cls: &PyTypeRef) -> PyResult<bool> {
let ret = self.call_method(
cls.as_object(),
"__subclasscheck__",
vec![subclass.clone().into_object()],
)?;
let ret = self.call_method(cls.as_object(), "__subclasscheck__", (subclass.clone(),))?;
objbool::boolval(self, ret)
}
@@ -901,7 +887,7 @@ impl VirtualMachine {
pub fn call_method<T>(&self, obj: &PyObjectRef, method_name: &str, args: T) -> PyResult
where
T: Into<PyFuncArgs>,
T: IntoFuncArgs,
{
flame_guard!(format!("call_method({:?})", method_name));
@@ -916,7 +902,7 @@ impl VirtualMachine {
}
}
fn _invoke(&self, callable: &PyObjectRef, args: PyFuncArgs) -> PyResult {
fn _invoke(&self, callable: &PyObjectRef, args: FuncArgs) -> PyResult {
vm_trace!("Invoke: {:?} {:?}", callable, args);
let slot_call = callable.class().mro_find_map(|cls| cls.slots.call.load());
match slot_call {
@@ -936,9 +922,9 @@ impl VirtualMachine {
#[inline]
pub fn invoke<T>(&self, func_ref: &PyObjectRef, args: T) -> PyResult
where
T: Into<PyFuncArgs>,
T: IntoFuncArgs,
{
self._invoke(func_ref, args.into())
self._invoke(func_ref, args.into_args(self))
}
/// Call registered trace function.
@@ -1024,15 +1010,11 @@ impl VirtualMachine {
V: Into<PyObjectRef>,
{
let attr_name = attr_name.try_into_ref(self)?;
self.call_method(
obj,
"__setattr__",
vec![attr_name.into_object(), attr_value.into()],
)
self.call_method(obj, "__setattr__", (attr_name, attr_value.into()))
}
pub fn del_attr(&self, obj: &PyObjectRef, attr_name: PyObjectRef) -> PyResult<()> {
self.call_method(&obj, "__delattr__", vec![attr_name])?;
self.call_method(&obj, "__delattr__", (attr_name,))?;
Ok(())
}
@@ -1075,7 +1057,7 @@ impl VirtualMachine {
{
if let Some(method_or_err) = self.get_method(obj.clone(), method) {
let method = method_or_err?;
let result = self.invoke(&method, vec![arg.clone()])?;
let result = self.invoke(&method, (arg.clone(),))?;
if let PyArithmaticValue::Implemented(x) = PyArithmaticValue::from_object(self, result)
{
return Ok(x);
@@ -1148,8 +1130,7 @@ impl VirtualMachine {
} else if let Some(attr) = cls_attr {
self.call_if_get_descriptor(attr, obj).map(Some)
} else if let Some(getter) = obj.clone_class().get_attr("__getattr__") {
self.invoke(&getter, vec![obj, name_str.into_object()])
.map(Some)
self.invoke(&getter, (obj, name_str)).map(Some)
} else {
Ok(None)
}
@@ -1500,7 +1481,7 @@ impl VirtualMachine {
pub fn _len(&self, obj: &PyObjectRef) -> Option<PyResult<usize>> {
self.get_method(obj.clone(), "__len__").map(|len| {
let len = self.invoke(&len?, vec![])?;
let len = self.invoke(&len?, ())?;
let len = len
.payload_if_subclass::<PyInt>(self)
.ok_or_else(|| {
+4 -7
View File
@@ -5,7 +5,7 @@ use wasm_bindgen::JsCast;
use wasm_bindgen_futures::{future_to_promise, JsFuture};
use rustpython_vm::common::rc::PyRc;
use rustpython_vm::function::{OptionalArg, PyFuncArgs};
use rustpython_vm::function::OptionalArg;
use rustpython_vm::import::import_file;
use rustpython_vm::obj::{objdict::PyDictRef, objstr::PyStrRef, objtype::PyTypeRef};
use rustpython_vm::pyobject::{
@@ -205,17 +205,14 @@ impl PyPromise {
} else {
vec![convert::js_to_py(vm, val)]
};
let res = vm.invoke(&on_fulfill.into_object(), PyFuncArgs::new(args, vec![]));
let res = vm.invoke(&on_fulfill.into_object(), args);
convert::pyresult_to_jsresult(vm, res)
}),
Err(err) => {
if let OptionalArg::Present(on_reject) = on_reject {
stored_vm.interp.enter(move |vm| {
let err = convert::js_to_py(vm, err);
let res = vm.invoke(
&on_reject.into_object(),
PyFuncArgs::new(vec![err], vec![]),
);
let res = vm.invoke(&on_reject.into_object(), (err,));
convert::pyresult_to_jsresult(vm, res)
})
} else {
@@ -243,7 +240,7 @@ impl PyPromise {
.expect("that the vm is valid when the promise resolves");
stored_vm.interp.enter(move |vm| {
let err = convert::js_to_py(vm, err);
let res = vm.invoke(&on_reject.into_object(), PyFuncArgs::new(vec![err], vec![]));
let res = vm.invoke(&on_reject.into_object(), (err,));
convert::pyresult_to_jsresult(vm, res)
})
};
+3 -3
View File
@@ -5,7 +5,7 @@ use rustpython_compiler::error::{CompileError, CompileErrorType};
use rustpython_parser::error::ParseErrorType;
use rustpython_vm::byteslike::PyBytesLike;
use rustpython_vm::exceptions::PyBaseExceptionRef;
use rustpython_vm::function::PyFuncArgs;
use rustpython_vm::function::FuncArgs;
use rustpython_vm::obj::objtype;
use rustpython_vm::pyobject::{ItemProtocol, PyObjectRef, PyResult, PyValue, TryFromObject};
use rustpython_vm::VirtualMachine;
@@ -84,7 +84,7 @@ pub fn py_to_js(vm: &VirtualMachine, py_obj: PyObjectRef) -> JsValue {
}
};
stored_vm_from_wasm(&wasm_vm).interp.enter(move |vm| {
let mut py_func_args = PyFuncArgs::default();
let mut py_func_args = FuncArgs::default();
if let Some(ref args) = args {
for arg in args.values() {
py_func_args.args.push(js_to_py(vm, arg?));
@@ -198,7 +198,7 @@ pub fn js_to_py(vm: &VirtualMachine, js_val: JsValue) -> PyObjectRef {
} else if js_val.is_function() {
let func = js_sys::Function::from(js_val);
vm.ctx
.new_method(move |args: PyFuncArgs, vm: &VirtualMachine| -> PyResult {
.new_method(move |args: FuncArgs, vm: &VirtualMachine| -> PyResult {
let this = Object::new();
for (k, v) in args.kwargs {
Reflect::set(&this, &k.into(), &py_to_js(vm, v))