diff --git a/derive/src/lib.rs b/derive/src/lib.rs index f52ca3e5553..ad743e72fef 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -38,7 +38,7 @@ fn impl_from_args(input: &DeriveInput) -> TokenStream2 { quote! { impl crate::function::FromArgs for #name { fn from_args( - vm: &mut crate::vm::VirtualMachine, + vm: &crate::vm::VirtualMachine, args: &mut crate::function::PyFuncArgs ) -> Result { Ok(#name { #(#fields)* }) diff --git a/src/main.rs b/src/main.rs index 1ff1b7ef424..d16eae0ce03 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,26 +45,26 @@ fn main() { .get_matches(); // Construct vm: - let mut vm = VirtualMachine::new(); + let vm = VirtualMachine::new(); // Figure out if a -c option was given: let result = if let Some(command) = matches.value_of("c") { - run_command(&mut vm, command.to_string()) + run_command(&vm, command.to_string()) } else if let Some(module) = matches.value_of("m") { - run_module(&mut vm, module) + run_module(&vm, module) } else { // Figure out if a script was passed: match matches.value_of("script") { - None => run_shell(&mut vm), - Some(filename) => run_script(&mut vm, filename), + None => run_shell(&vm), + Some(filename) => run_script(&vm, filename), } }; // See if any exception leaked out: - handle_exception(&mut vm, result); + handle_exception(&vm, result); } -fn _run_string(vm: &mut VirtualMachine, source: &str, source_path: String) -> PyResult { +fn _run_string(vm: &VirtualMachine, source: &str, source_path: String) -> PyResult { let code_obj = compile::compile( source, &compile::Mode::Exec, @@ -80,14 +80,14 @@ fn _run_string(vm: &mut VirtualMachine, source: &str, source_path: String) -> Py vm.run_code_obj(code_obj, vars) } -fn handle_exception(vm: &mut VirtualMachine, result: PyResult) { +fn handle_exception(vm: &VirtualMachine, result: PyResult) { if let Err(err) = result { print_exception(vm, &err); std::process::exit(1); } } -fn run_command(vm: &mut VirtualMachine, mut source: String) -> PyResult { +fn run_command(vm: &VirtualMachine, mut source: String) -> PyResult { debug!("Running command {}", source); // This works around https://github.com/RustPython/RustPython/issues/17 @@ -95,13 +95,13 @@ fn run_command(vm: &mut VirtualMachine, mut source: String) -> PyResult { _run_string(vm, &source, "".to_string()) } -fn run_module(vm: &mut VirtualMachine, module: &str) -> PyResult { +fn run_module(vm: &VirtualMachine, module: &str) -> PyResult { debug!("Running module {}", module); let current_path = PathBuf::from("."); import::import_module(vm, current_path, module) } -fn run_script(vm: &mut VirtualMachine, script_file: &str) -> PyResult { +fn run_script(vm: &VirtualMachine, script_file: &str) -> PyResult { debug!("Running file {}", script_file); // Parse an ast from it: let file_path = Path::new(script_file); @@ -114,7 +114,7 @@ fn run_script(vm: &mut VirtualMachine, script_file: &str) -> PyResult { } } -fn shell_exec(vm: &mut VirtualMachine, source: &str, scope: Scope) -> Result<(), CompileError> { +fn shell_exec(vm: &VirtualMachine, source: &str, scope: Scope) -> Result<(), CompileError> { match compile::compile( source, &compile::Mode::Single, @@ -153,7 +153,7 @@ fn get_history_path() -> PathBuf { xdg_dirs.place_cache_file("repl_history.txt").unwrap() } -fn run_shell(vm: &mut VirtualMachine) -> PyResult { +fn run_shell(vm: &VirtualMachine) -> PyResult { println!( "Welcome to the magnificent Rust Python {} interpreter", crate_version!() diff --git a/vm/src/builtins.rs b/vm/src/builtins.rs index 55aa2a75ecb..68e933db3e3 100644 --- a/vm/src/builtins.rs +++ b/vm/src/builtins.rs @@ -27,7 +27,7 @@ use crate::vm::VirtualMachine; #[cfg(not(target_arch = "wasm32"))] use crate::stdlib::io::io_open; -fn get_locals(vm: &mut VirtualMachine) -> PyObjectRef { +fn get_locals(vm: &VirtualMachine) -> PyObjectRef { let d = vm.new_dict(); // TODO: implement dict_iter_items? let locals = vm.get_locals(); @@ -38,11 +38,11 @@ fn get_locals(vm: &mut VirtualMachine) -> PyObjectRef { d } -fn dir_locals(vm: &mut VirtualMachine) -> PyObjectRef { +fn dir_locals(vm: &VirtualMachine) -> PyObjectRef { get_locals(vm) } -fn builtin_abs(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_abs(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(x, None)]); match vm.get_method(x.clone(), "__abs__") { Ok(attrib) => vm.invoke(attrib, PyFuncArgs::new(vec![], vec![])), @@ -50,7 +50,7 @@ fn builtin_abs(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn builtin_all(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_all(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(iterable, None)]); let items = vm.extract_elements(iterable)?; for item in items { @@ -62,7 +62,7 @@ fn builtin_all(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_bool(true)) } -fn builtin_any(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_any(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(iterable, None)]); let iterator = objiter::get_iter(vm, iterable)?; @@ -78,7 +78,7 @@ fn builtin_any(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { // builtin_ascii -fn builtin_bin(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_bin(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(number, Some(vm.ctx.int_type()))]); let n = objint::get_value(number); @@ -93,13 +93,13 @@ fn builtin_bin(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { // builtin_breakpoint -fn builtin_callable(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_callable(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, None)]); let is_callable = obj.typ().has_attr("__call__"); Ok(vm.new_bool(is_callable)) } -fn builtin_chr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_chr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(i, Some(vm.ctx.int_type()))]); let code_point = objint::get_value(i).to_u32().unwrap(); @@ -112,7 +112,7 @@ fn builtin_chr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_str(txt)) } -fn builtin_compile(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_compile(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -149,7 +149,7 @@ fn builtin_compile(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { }) } -fn builtin_delattr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_delattr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -158,7 +158,7 @@ fn builtin_delattr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { vm.del_attr(obj, attr.clone()) } -fn builtin_dir(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_dir(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { if args.args.is_empty() { Ok(dir_locals(vm)) } else { @@ -169,7 +169,7 @@ fn builtin_dir(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn builtin_divmod(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_divmod(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(x, None), (y, None)]); match vm.get_method(x.clone(), "__divmod__") { Ok(attrib) => vm.invoke(attrib, vec![y.clone()]), @@ -179,7 +179,7 @@ fn builtin_divmod(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { /// Implements `eval`. /// See also: https://docs.python.org/3/library/functions.html#eval -fn builtin_eval(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_eval(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -213,7 +213,7 @@ fn builtin_eval(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { /// Implements `exec` /// https://docs.python.org/3/library/functions.html#exec -fn builtin_exec(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_exec(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -246,7 +246,7 @@ fn builtin_exec(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } fn make_scope( - vm: &mut VirtualMachine, + vm: &VirtualMachine, globals: Option<&PyObjectRef>, locals: Option<&PyObjectRef>, ) -> PyResult { @@ -283,7 +283,7 @@ fn make_scope( Ok(Scope::new(locals, globals)) } -fn builtin_format(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_format(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -296,7 +296,7 @@ fn builtin_format(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { vm.call_method(obj, "__format__", vec![format_spec]) } -fn catch_attr_exception(ex: PyObjectRef, default: T, vm: &mut VirtualMachine) -> PyResult { +fn catch_attr_exception(ex: PyObjectRef, default: T, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&ex, &vm.ctx.exceptions.attribute_error) { Ok(default) } else { @@ -308,7 +308,7 @@ fn builtin_getattr( obj: PyObjectRef, attr: PyStringRef, default: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let ret = vm.get_attribute(obj.clone(), attr); if let OptionalArg::Present(default) = default { @@ -318,11 +318,11 @@ fn builtin_getattr( } } -fn builtin_globals(vm: &mut VirtualMachine, _args: PyFuncArgs) -> PyResult { +fn builtin_globals(vm: &VirtualMachine, _args: PyFuncArgs) -> PyResult { Ok(vm.current_scope().globals.clone()) } -fn builtin_hasattr(obj: PyObjectRef, attr: PyStringRef, vm: &mut VirtualMachine) -> PyResult { +fn builtin_hasattr(obj: PyObjectRef, attr: PyStringRef, vm: &VirtualMachine) -> PyResult { if let Err(ex) = vm.get_attribute(obj.clone(), attr) { catch_attr_exception(ex, false, vm) } else { @@ -330,7 +330,7 @@ fn builtin_hasattr(obj: PyObjectRef, attr: PyStringRef, vm: &mut VirtualMachine) } } -fn builtin_hash(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_hash(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, None)]); vm.call_method(obj, "__hash__", vec![]) @@ -338,7 +338,7 @@ fn builtin_hash(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { // builtin_help -fn builtin_hex(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_hex(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(number, Some(vm.ctx.int_type()))]); let n = objint::get_value(number); @@ -351,7 +351,7 @@ fn builtin_hex(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_str(s)) } -fn builtin_id(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_id(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, None)]); Ok(vm.context().new_int(obj.get_id())) @@ -359,7 +359,7 @@ fn builtin_id(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { // builtin_input -fn builtin_isinstance(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_isinstance(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -370,7 +370,7 @@ fn builtin_isinstance(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_bool(isinstance)) } -fn builtin_issubclass(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_issubclass(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -381,12 +381,12 @@ fn builtin_issubclass(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.context().new_bool(issubclass)) } -fn builtin_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_iter(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(iter_target, None)]); objiter::get_iter(vm, iter_target) } -fn builtin_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_len(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, None)]); let len_method_name = "__len__"; match vm.get_method(obj.clone(), len_method_name) { @@ -399,12 +399,12 @@ fn builtin_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn builtin_locals(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_locals(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args); Ok(vm.get_locals()) } -fn builtin_max(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_max(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let candidates = if args.args.len() > 1 { args.args.clone() } else if args.args.len() == 1 { @@ -453,7 +453,7 @@ fn builtin_max(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(x) } -fn builtin_min(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_min(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let candidates = if args.args.len() > 1 { args.args.clone() } else if args.args.len() == 1 { @@ -501,7 +501,7 @@ fn builtin_min(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(x) } -fn builtin_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_next(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -524,7 +524,7 @@ fn builtin_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn builtin_oct(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_oct(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(number, Some(vm.ctx.int_type()))]); let n = objint::get_value(number); @@ -537,7 +537,7 @@ fn builtin_oct(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_str(s)) } -fn builtin_ord(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_ord(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(string, Some(vm.ctx.str_type()))]); let string = objstr::get_value(string); let string_len = string.chars().count(); @@ -555,7 +555,7 @@ fn builtin_ord(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn builtin_pow(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_pow(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -591,11 +591,7 @@ pub struct PrintOptions { flush: bool, } -pub fn builtin_print( - objects: Args, - options: PrintOptions, - vm: &mut VirtualMachine, -) -> PyResult<()> { +pub fn builtin_print(objects: Args, options: PrintOptions, vm: &VirtualMachine) -> PyResult<()> { let stdout = io::stdout(); let mut stdout_lock = stdout.lock(); let mut first = true; @@ -624,11 +620,11 @@ pub fn builtin_print( Ok(()) } -fn builtin_repr(obj: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { +fn builtin_repr(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { vm.to_repr(&obj) } -fn builtin_reversed(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_reversed(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, None)]); match vm.get_method(obj.clone(), "__reversed__") { @@ -642,7 +638,7 @@ fn builtin_reversed(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } // builtin_reversed -fn builtin_round(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_round(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -664,7 +660,7 @@ fn builtin_setattr( obj: PyObjectRef, attr: PyStringRef, value: PyObjectRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult<()> { vm.set_attr(&obj, attr.into_object(), value)?; Ok(()) @@ -672,7 +668,7 @@ fn builtin_setattr( // builtin_slice -fn builtin_sorted(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult { +fn builtin_sorted(vm: &VirtualMachine, mut args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(iterable, None)]); let items = vm.extract_elements(iterable)?; let lst = vm.ctx.new_list(items); @@ -682,7 +678,7 @@ fn builtin_sorted(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult { Ok(lst) } -fn builtin_sum(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_sum(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(iterable, None)]); let items = vm.extract_elements(iterable)?; @@ -695,7 +691,7 @@ fn builtin_sum(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } // Should be renamed to builtin___import__? -fn builtin_import(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn builtin_import(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -815,7 +811,7 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef { py_mod } -pub fn builtin_build_class_(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult { +pub fn builtin_build_class_(vm: &VirtualMachine, mut args: PyFuncArgs) -> PyResult { let function = args.shift(); let name_arg = args.shift(); let bases = args.args.clone(); diff --git a/vm/src/dictdatatype.rs b/vm/src/dictdatatype.rs index df6b3bb5a83..436923ea958 100644 --- a/vm/src/dictdatatype.rs +++ b/vm/src/dictdatatype.rs @@ -33,7 +33,7 @@ impl Dict { /// Store a key pub fn insert( &mut self, - vm: &mut VirtualMachine, + vm: &VirtualMachine, key: &PyObjectRef, value: PyObjectRef, ) -> PyResult<()> { @@ -66,7 +66,7 @@ impl Dict { } } - pub fn contains(&self, vm: &mut VirtualMachine, key: &PyObjectRef) -> PyResult { + pub fn contains(&self, vm: &VirtualMachine, key: &PyObjectRef) -> PyResult { if let LookupResult::Existing(_index) = self.lookup(vm, key)? { Ok(true) } else { @@ -75,7 +75,7 @@ impl Dict { } /// Retrieve a key - pub fn get(&self, vm: &mut VirtualMachine, key: &PyObjectRef) -> PyResult { + pub fn get(&self, vm: &VirtualMachine, key: &PyObjectRef) -> PyResult { if let LookupResult::Existing(index) = self.lookup(vm, key)? { if let Some(entry) = &self.entries[index] { Ok(entry.value.clone()) @@ -89,7 +89,7 @@ impl Dict { } /// Delete a key - pub fn delete(&mut self, vm: &mut VirtualMachine, key: &PyObjectRef) -> PyResult<()> { + pub fn delete(&mut self, vm: &VirtualMachine, key: &PyObjectRef) -> PyResult<()> { if let LookupResult::Existing(index) = self.lookup(vm, key)? { self.entries[index] = None; self.size -= 1; @@ -118,7 +118,7 @@ impl Dict { } /// Lookup the index for the given key. - fn lookup(&self, vm: &mut VirtualMachine, key: &PyObjectRef) -> PyResult { + fn lookup(&self, vm: &VirtualMachine, key: &PyObjectRef) -> PyResult { let hash_value = calc_hash(vm, key)?; let perturb = hash_value; let mut hash_index: usize = hash_value; @@ -169,14 +169,14 @@ enum LookupResult { Existing(usize), // Existing record, index into entries } -fn calc_hash(vm: &mut VirtualMachine, key: &PyObjectRef) -> PyResult { +fn calc_hash(vm: &VirtualMachine, key: &PyObjectRef) -> PyResult { let hash = vm.call_method(key, "__hash__", vec![])?; Ok(objint::get_value(&hash).to_usize().unwrap()) } /// Invoke __eq__ on two keys fn do_eq( - vm: &mut VirtualMachine, + vm: &VirtualMachine, key1: &PyObjectRef, key2: &PyObjectRef, ) -> Result { diff --git a/vm/src/eval.rs b/vm/src/eval.rs index 7f44cde89ba..202286eb133 100644 --- a/vm/src/eval.rs +++ b/vm/src/eval.rs @@ -7,7 +7,7 @@ use crate::frame::Scope; use crate::pyobject::PyResult; use crate::vm::VirtualMachine; -pub fn eval(vm: &mut VirtualMachine, source: &str, scope: Scope, source_path: &str) -> PyResult { +pub fn eval(vm: &VirtualMachine, source: &str, scope: Scope, source_path: &str) -> PyResult { match compile::compile( source, &compile::Mode::Eval, diff --git a/vm/src/exceptions.rs b/vm/src/exceptions.rs index 68f4105c5eb..d37f1747171 100644 --- a/vm/src/exceptions.rs +++ b/vm/src/exceptions.rs @@ -4,7 +4,7 @@ use crate::obj::objtype; use crate::pyobject::{create_type, PyContext, PyObjectRef, PyResult, TypeProtocol}; use crate::vm::VirtualMachine; -fn exception_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn exception_init(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let zelf = args.args[0].clone(); let msg = if args.args.len() > 1 { args.args[1].clone() @@ -18,7 +18,7 @@ fn exception_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } // Print exception including traceback: -pub fn print_exception(vm: &mut VirtualMachine, exc: &PyObjectRef) { +pub fn print_exception(vm: &VirtualMachine, exc: &PyObjectRef) { if let Ok(tb) = vm.get_attribute(exc.clone(), "__traceback__") { println!("Traceback (most recent call last):"); if objtype::isinstance(&tb, &vm.ctx.list_type()) { @@ -61,7 +61,7 @@ pub fn print_exception(vm: &mut VirtualMachine, exc: &PyObjectRef) { } } -fn exception_str(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn exception_str(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/frame.rs b/vm/src/frame.rs index 576d988fb53..3a6809f0ea6 100644 --- a/vm/src/frame.rs +++ b/vm/src/frame.rs @@ -185,7 +185,7 @@ pub struct Frame { } impl PyValue for Frame { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.frame_type() } } @@ -223,7 +223,7 @@ impl Frame { } } - pub fn run(&self, vm: &mut VirtualMachine) -> Result { + pub fn run(&self, vm: &VirtualMachine) -> Result { let filename = &self.code.source_path.to_string(); // This is the name of the object being run: @@ -276,7 +276,7 @@ impl Frame { } // Execute a single instruction: - fn execute_instruction(&self, vm: &mut VirtualMachine) -> FrameResult { + fn execute_instruction(&self, vm: &VirtualMachine) -> FrameResult { let instruction = self.fetch_instruction(); { trace!("======="); @@ -780,7 +780,7 @@ impl Frame { fn get_elements( &self, - vm: &mut VirtualMachine, + vm: &VirtualMachine, size: usize, unpack: bool, ) -> Result, PyObjectRef> { @@ -799,12 +799,7 @@ impl Frame { } } - fn import( - &self, - vm: &mut VirtualMachine, - module: &str, - symbol: &Option, - ) -> FrameResult { + fn import(&self, vm: &VirtualMachine, module: &str, symbol: &Option) -> FrameResult { let module = vm.import(module)?; // If we're importing a symbol, look it up and use it, otherwise construct a module and return @@ -822,7 +817,7 @@ impl Frame { Ok(None) } - fn import_star(&self, vm: &mut VirtualMachine, module: &str) -> FrameResult { + fn import_star(&self, vm: &VirtualMachine, module: &str) -> FrameResult { let module = vm.import(module)?; // Grab all the names from the module and put them in the context @@ -833,7 +828,7 @@ impl Frame { } // Unwind all blocks: - fn unwind_blocks(&self, vm: &mut VirtualMachine) -> Option { + fn unwind_blocks(&self, vm: &VirtualMachine) -> Option { while let Some(block) = self.pop_block() { match block.typ { BlockType::Loop { .. } => {} @@ -857,7 +852,7 @@ impl Frame { None } - fn unwind_loop(&self, vm: &mut VirtualMachine) -> Block { + fn unwind_loop(&self, vm: &VirtualMachine) -> Block { loop { let block = self.current_block().expect("not in a loop"); match block.typ { @@ -879,7 +874,7 @@ impl Frame { } } - fn unwind_exception(&self, vm: &mut VirtualMachine, exc: PyObjectRef) -> Option { + fn unwind_exception(&self, vm: &VirtualMachine, exc: PyObjectRef) -> Option { // unwind block stack on exception and find any handlers: while let Some(block) = self.pop_block() { match block.typ { @@ -924,7 +919,7 @@ impl Frame { fn with_exit( &self, - vm: &mut VirtualMachine, + vm: &VirtualMachine, context_manager: &PyObjectRef, exc: Option, ) -> PyResult { @@ -947,18 +942,18 @@ impl Frame { vm.call_method(context_manager, "__exit__", args) } - fn store_name(&self, vm: &mut VirtualMachine, name: &str) -> FrameResult { + fn store_name(&self, vm: &VirtualMachine, name: &str) -> FrameResult { let obj = self.pop_value(); self.scope.store_name(&vm, name, obj); Ok(None) } - fn delete_name(&self, vm: &mut VirtualMachine, name: &str) -> FrameResult { + fn delete_name(&self, vm: &VirtualMachine, name: &str) -> FrameResult { self.scope.delete_name(vm, name); Ok(None) } - fn load_name(&self, vm: &mut VirtualMachine, name: &str) -> FrameResult { + fn load_name(&self, vm: &VirtualMachine, name: &str) -> FrameResult { match self.scope.load_name(&vm, name) { Some(value) => { self.push_value(value); @@ -973,11 +968,11 @@ impl Frame { } } - fn subscript(&self, vm: &mut VirtualMachine, a: PyObjectRef, b: PyObjectRef) -> PyResult { + fn subscript(&self, vm: &VirtualMachine, a: PyObjectRef, b: PyObjectRef) -> PyResult { vm.call_method(&a, "__getitem__", vec![b]) } - fn execute_store_subscript(&self, vm: &mut VirtualMachine) -> FrameResult { + fn execute_store_subscript(&self, vm: &VirtualMachine) -> FrameResult { let idx = self.pop_value(); let obj = self.pop_value(); let value = self.pop_value(); @@ -985,7 +980,7 @@ impl Frame { Ok(None) } - fn execute_delete_subscript(&self, vm: &mut VirtualMachine) -> FrameResult { + fn execute_delete_subscript(&self, vm: &VirtualMachine) -> FrameResult { let idx = self.pop_value(); let obj = self.pop_value(); vm.call_method(&obj, "__delitem__", vec![idx])?; @@ -1000,7 +995,7 @@ impl Frame { fn execute_binop( &self, - vm: &mut VirtualMachine, + vm: &VirtualMachine, op: &bytecode::BinaryOperator, inplace: bool, ) -> FrameResult { @@ -1042,7 +1037,7 @@ impl Frame { Ok(None) } - fn execute_unop(&self, vm: &mut VirtualMachine, op: &bytecode::UnaryOperator) -> FrameResult { + fn execute_unop(&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![])?, @@ -1064,7 +1059,7 @@ impl Frame { // https://docs.python.org/3/reference/expressions.html#membership-test-operations fn _membership( &self, - vm: &mut VirtualMachine, + vm: &VirtualMachine, needle: PyObjectRef, haystack: &PyObjectRef, ) -> PyResult { @@ -1073,7 +1068,7 @@ impl Frame { // not implemented. } - fn _in(&self, vm: &mut VirtualMachine, needle: PyObjectRef, haystack: PyObjectRef) -> PyResult { + fn _in(&self, vm: &VirtualMachine, needle: PyObjectRef, haystack: PyObjectRef) -> PyResult { match self._membership(vm, needle, &haystack) { Ok(found) => Ok(found), Err(_) => Err(vm.new_type_error(format!( @@ -1083,12 +1078,7 @@ impl Frame { } } - fn _not_in( - &self, - vm: &mut VirtualMachine, - needle: PyObjectRef, - haystack: PyObjectRef, - ) -> PyResult { + fn _not_in(&self, vm: &VirtualMachine, needle: PyObjectRef, haystack: PyObjectRef) -> PyResult { match self._membership(vm, needle, &haystack) { Ok(found) => Ok(vm.ctx.new_bool(!objbool::get_value(&found))), Err(_) => Err(vm.new_type_error(format!( @@ -1111,7 +1101,7 @@ impl Frame { fn execute_compare( &self, - vm: &mut VirtualMachine, + vm: &VirtualMachine, op: &bytecode::ComparisonOperator, ) -> FrameResult { let b = self.pop_value(); @@ -1133,21 +1123,21 @@ impl Frame { Ok(None) } - fn load_attr(&self, vm: &mut VirtualMachine, attr_name: &str) -> FrameResult { + fn load_attr(&self, vm: &VirtualMachine, attr_name: &str) -> FrameResult { let parent = self.pop_value(); let obj = vm.get_attribute(parent, attr_name)?; self.push_value(obj); Ok(None) } - fn store_attr(&self, vm: &mut VirtualMachine, attr_name: &str) -> FrameResult { + fn store_attr(&self, vm: &VirtualMachine, attr_name: &str) -> FrameResult { let parent = self.pop_value(); let value = self.pop_value(); vm.set_attr(&parent, vm.new_str(attr_name.to_string()), value)?; Ok(None) } - fn delete_attr(&self, vm: &mut VirtualMachine, attr_name: &str) -> FrameResult { + fn delete_attr(&self, vm: &VirtualMachine, attr_name: &str) -> FrameResult { let parent = self.pop_value(); let name = vm.ctx.new_str(attr_name.to_string()); vm.del_attr(&parent, name)?; diff --git a/vm/src/function.rs b/vm/src/function.rs index 8ce7ad12a3c..c5ec06cb1c9 100644 --- a/vm/src/function.rs +++ b/vm/src/function.rs @@ -79,7 +79,7 @@ impl PyFuncArgs { &self, key: &str, ty: PyObjectRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> Result, PyObjectRef> { match self.get_optional_kwarg(key) { Some(kwarg) => { @@ -131,7 +131,7 @@ impl PyFuncArgs { /// /// If the given `FromArgs` includes any conversions, exceptions raised /// during the conversion will halt the binding and return the error. - fn bind(mut self, vm: &mut VirtualMachine) -> PyResult { + fn bind(mut self, vm: &VirtualMachine) -> PyResult { let given_args = self.args.len(); let bound = match T::from_args(vm, &mut self) { Ok(args) => args, @@ -203,7 +203,7 @@ pub trait FromArgs: Sized { } /// Extracts this item from the next argument(s). - fn from_args(vm: &mut VirtualMachine, args: &mut PyFuncArgs) -> Result; + fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result; } /// A map of keyword arguments to their values. @@ -226,7 +226,7 @@ impl FromArgs for KwArgs where T: TryFromObject, { - fn from_args(vm: &mut VirtualMachine, args: &mut PyFuncArgs) -> Result { + fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result { let mut kwargs = HashMap::new(); for (name, value) in args.remaining_keyword() { kwargs.insert(name, T::try_from_object(vm, value)?); @@ -249,7 +249,7 @@ impl FromArgs for Args where T: TryFromObject, { - fn from_args(vm: &mut VirtualMachine, args: &mut PyFuncArgs) -> Result { + fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result { let mut varargs = Vec::new(); while let Some(value) = args.next_positional() { varargs.push(T::try_from_object(vm, value)?); @@ -275,7 +275,7 @@ where 1..=1 } - fn from_args(vm: &mut VirtualMachine, args: &mut PyFuncArgs) -> Result { + fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result { if let Some(value) = args.next_positional() { Ok(T::try_from_object(vm, value)?) } else { @@ -309,7 +309,7 @@ where 0..=1 } - fn from_args(vm: &mut VirtualMachine, args: &mut PyFuncArgs) -> Result { + fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result { if let Some(value) = args.next_positional() { Ok(Present(T::try_from_object(vm, value)?)) } else { @@ -321,7 +321,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: &mut VirtualMachine, _args: &mut PyFuncArgs) -> Result { + fn from_args(_vm: &VirtualMachine, _args: &mut PyFuncArgs) -> Result { Ok(()) } } @@ -349,7 +349,7 @@ macro_rules! tuple_from_py_func_args { min..=max } - fn from_args(vm: &mut VirtualMachine, args: &mut PyFuncArgs) -> Result { + fn from_args(vm: &VirtualMachine, args: &mut PyFuncArgs) -> Result { Ok(($($T::from_args(vm, args)?,)+)) } } @@ -366,14 +366,14 @@ tuple_from_py_func_args!(A, B, C, D); tuple_from_py_func_args!(A, B, C, D, E); /// A built-in Python function. -pub type PyNativeFunc = Box PyResult + 'static>; +pub type PyNativeFunc = Box PyResult + 'static>; /// Implemented by types that are or can generate built-in functions. /// /// For example, any function that: /// /// - Accepts a sequence of types that implement `FromArgs`, followed by a -/// `&mut VirtualMachine` +/// `&VirtualMachine` /// - Returns some type that implements `IntoPyObject` /// /// will generate a `PyNativeFunc` that performs the appropriate type and arity @@ -388,7 +388,7 @@ pub trait IntoPyNativeFunc { impl IntoPyNativeFunc for F where - F: Fn(&mut VirtualMachine, PyFuncArgs) -> PyResult + 'static, + F: Fn(&VirtualMachine, PyFuncArgs) -> PyResult + 'static, { fn into_func(self) -> PyNativeFunc { Box::new(self) @@ -409,7 +409,7 @@ macro_rules! into_py_native_func_tuple { ($(($n:tt, $T:ident)),*) => { impl IntoPyNativeFunc<($($T,)*), R> for F where - F: Fn($($T,)* &mut VirtualMachine) -> R + 'static, + F: Fn($($T,)* &VirtualMachine) -> R + 'static, $($T: FromArgs,)* ($($T,)*): FromArgs, R: IntoPyObject, diff --git a/vm/src/import.rs b/vm/src/import.rs index 0b27eb72c93..8e8fe33849c 100644 --- a/vm/src/import.rs +++ b/vm/src/import.rs @@ -12,13 +12,9 @@ use crate::pyobject::{DictProtocol, PyResult}; use crate::util; use crate::vm::VirtualMachine; -fn import_uncached_module( - vm: &mut VirtualMachine, - current_path: PathBuf, - module: &str, -) -> PyResult { +fn import_uncached_module(vm: &VirtualMachine, current_path: PathBuf, module: &str) -> PyResult { // Check for Rust-native modules - if let Some(module) = vm.stdlib_inits.get(module) { + if let Some(module) = vm.stdlib_inits.borrow().get(module) { return Ok(module(&vm.ctx).clone()); } @@ -48,11 +44,7 @@ fn import_uncached_module( Ok(vm.ctx.new_module(module, attrs)) } -pub fn import_module( - vm: &mut VirtualMachine, - current_path: PathBuf, - module_name: &str, -) -> PyResult { +pub fn import_module(vm: &VirtualMachine, current_path: PathBuf, module_name: &str) -> PyResult { // First, see if we already loaded the module: let sys_modules = vm.get_attribute(vm.sys_module.clone(), "modules")?; if let Some(module) = sys_modules.get_item(module_name) { @@ -64,7 +56,7 @@ pub fn import_module( } fn find_source( - vm: &mut VirtualMachine, + vm: &VirtualMachine, current_path: PathBuf, name: &str, ) -> Result { diff --git a/vm/src/obj/objbool.rs b/vm/src/obj/objbool.rs index 1a5b10d0155..4feb1300bdd 100644 --- a/vm/src/obj/objbool.rs +++ b/vm/src/obj/objbool.rs @@ -15,18 +15,18 @@ use super::objtuple::PyTuple; use super::objtype; impl IntoPyObject for bool { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { Ok(vm.ctx.new_bool(self)) } } impl TryFromObject for bool { - fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { boolval(vm, obj) } } -pub fn boolval(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult { +pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { if let Some(s) = obj.payload::() { return Ok(!s.value.is_empty()); } @@ -70,7 +70,7 @@ The class bool is a subclass of the class int, and cannot be subclassed."; context.set_attr(&bool_type, "__doc__", context.new_str(bool_doc.to_string())); } -pub fn not(vm: &mut VirtualMachine, obj: &PyObjectRef) -> PyResult { +pub fn not(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult { if objtype::isinstance(obj, &vm.ctx.bool_type()) { let value = get_value(obj); Ok(vm.ctx.new_bool(!value)) @@ -84,7 +84,7 @@ pub fn get_value(obj: &PyObjectRef) -> bool { !obj.payload::().unwrap().value.is_zero() } -fn bool_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> Result { +fn bool_repr(vm: &VirtualMachine, args: PyFuncArgs) -> Result { arg_check!(vm, args, required = [(obj, Some(vm.ctx.bool_type()))]); let v = get_value(obj); let s = if v { @@ -95,7 +95,7 @@ fn bool_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> Result PyResult { +fn bool_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/obj/objbuiltinfunc.rs b/vm/src/obj/objbuiltinfunc.rs index ca181fea4dc..259c94b6276 100644 --- a/vm/src/obj/objbuiltinfunc.rs +++ b/vm/src/obj/objbuiltinfunc.rs @@ -10,7 +10,7 @@ pub struct PyBuiltinFunction { } impl PyValue for PyBuiltinFunction { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.builtin_function_or_method_type() } } diff --git a/vm/src/obj/objbytearray.rs b/vm/src/obj/objbytearray.rs index 745d07e59fe..c7038fe9ac3 100644 --- a/vm/src/obj/objbytearray.rs +++ b/vm/src/obj/objbytearray.rs @@ -29,7 +29,7 @@ impl PyByteArray { } impl PyValue for PyByteArray { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.bytearray_type() } } @@ -147,7 +147,7 @@ pub fn init(context: &PyContext) { fn bytearray_new( cls: PyClassRef, val_option: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { // Create bytes data: let value = if let OptionalArg::Present(ival) = val_option { @@ -169,14 +169,14 @@ fn bytearray_new( PyByteArray::new(value).into_ref_with_type(vm, cls.clone()) } -fn bytesarray_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytesarray_len(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(a, Some(vm.ctx.bytearray_type()))]); let byte_vec = get_value(a).to_vec(); Ok(vm.ctx.new_int(byte_vec.len())) } -fn bytearray_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_eq(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -191,31 +191,31 @@ fn bytearray_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(result)) } -fn bytearray_isalnum(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_isalnum(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); let bytes = get_value(zelf); Ok(vm.new_bool(!bytes.is_empty() && bytes.iter().all(|x| char::from(*x).is_alphanumeric()))) } -fn bytearray_isalpha(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_isalpha(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); let bytes = get_value(zelf); Ok(vm.new_bool(!bytes.is_empty() && bytes.iter().all(|x| char::from(*x).is_alphabetic()))) } -fn bytearray_isascii(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_isascii(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); let bytes = get_value(zelf); Ok(vm.new_bool(!bytes.is_empty() && bytes.iter().all(|x| char::from(*x).is_ascii()))) } -fn bytearray_isdigit(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_isdigit(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); let bytes = get_value(zelf); Ok(vm.new_bool(!bytes.is_empty() && bytes.iter().all(|x| char::from(*x).is_digit(10)))) } -fn bytearray_islower(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_islower(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); let bytes = get_value(zelf); Ok(vm.new_bool( @@ -227,13 +227,13 @@ fn bytearray_islower(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { )) } -fn bytearray_isspace(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_isspace(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); let bytes = get_value(zelf); Ok(vm.new_bool(!bytes.is_empty() && bytes.iter().all(|x| char::from(*x).is_whitespace()))) } -fn bytearray_isupper(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_isupper(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); let bytes = get_value(zelf); Ok(vm.new_bool( @@ -245,7 +245,7 @@ fn bytearray_isupper(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { )) } -fn bytearray_istitle(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_istitle(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); let bytes = get_value(zelf); @@ -284,7 +284,7 @@ fn is_cased(c: char) -> bool { } /* -fn bytearray_getitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_getitem(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -308,7 +308,7 @@ fn bytearray_to_hex(bytearray: &[u8]) -> String { }) } -fn bytearray_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytearray_type()))]); let value = get_value(obj); let data = @@ -316,13 +316,13 @@ fn bytearray_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_str(format!("bytearray(b'{}')", data))) } -fn bytearray_clear(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_clear(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytearray_type()))]); get_mut_value(zelf).clear(); Ok(vm.get_none()) } -fn bytearray_pop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_pop(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytearray_type()))]); let mut value = get_mut_value(obj); @@ -333,13 +333,13 @@ fn bytearray_pop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn bytearray_lower(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_lower(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytearray_type()))]); let value = get_value(obj).to_vec().to_ascii_lowercase(); Ok(vm.ctx.new_bytearray(value)) } -fn bytearray_upper(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytearray_upper(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytearray_type()))]); let value = get_value(obj).to_vec().to_ascii_uppercase(); Ok(vm.ctx.new_bytearray(value)) diff --git a/vm/src/obj/objbytes.rs b/vm/src/obj/objbytes.rs index 38222360fc5..dc1f930a46b 100644 --- a/vm/src/obj/objbytes.rs +++ b/vm/src/obj/objbytes.rs @@ -34,7 +34,7 @@ impl Deref for PyBytes { } impl PyValue for PyBytes { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.bytes_type() } } @@ -76,7 +76,7 @@ pub fn init(context: &PyContext) { fn bytes_new( cls: PyClassRef, val_option: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { // Create bytes data: let value = if let OptionalArg::Present(ival) = val_option { @@ -95,7 +95,7 @@ fn bytes_new( PyBytes::new(value).into_ref_with_type(vm, cls) } -fn bytes_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_eq(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -110,7 +110,7 @@ fn bytes_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(result)) } -fn bytes_ge(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_ge(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -125,7 +125,7 @@ fn bytes_ge(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(result)) } -fn bytes_gt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_gt(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -140,7 +140,7 @@ fn bytes_gt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(result)) } -fn bytes_le(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_le(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -155,7 +155,7 @@ fn bytes_le(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(result)) } -fn bytes_lt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_lt(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -170,14 +170,14 @@ fn bytes_lt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(result)) } -fn bytes_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_len(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(a, Some(vm.ctx.bytes_type()))]); let byte_vec = get_value(a).to_vec(); Ok(vm.ctx.new_int(byte_vec.len())) } -fn bytes_hash(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_hash(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytes_type()))]); let data = get_value(zelf); let mut hasher = std::collections::hash_map::DefaultHasher::new(); @@ -190,14 +190,14 @@ pub fn get_value<'a>(obj: &'a PyObjectRef) -> impl Deref> + 'a &obj.payload::().unwrap().value } -fn bytes_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytes_type()))]); let value = get_value(obj); let data = String::from_utf8(value.to_vec()).unwrap(); Ok(vm.new_str(format!("b'{}'", data))) } -fn bytes_iter(obj: PyBytesRef, _vm: &mut VirtualMachine) -> PyIteratorValue { +fn bytes_iter(obj: PyBytesRef, _vm: &VirtualMachine) -> PyIteratorValue { PyIteratorValue { position: Cell::new(0), iterated_obj: obj.into_object(), diff --git a/vm/src/obj/objclassmethod.rs b/vm/src/obj/objclassmethod.rs index 8a1baad31ce..725f508e98f 100644 --- a/vm/src/obj/objclassmethod.rs +++ b/vm/src/obj/objclassmethod.rs @@ -9,7 +9,7 @@ pub struct PyClassMethod { pub type PyClassMethodRef = PyRef; impl PyValue for PyClassMethod { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.classmethod_type() } } @@ -18,7 +18,7 @@ impl PyClassMethodRef { fn new( cls: PyClassRef, callable: PyObjectRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { PyClassMethod { callable: callable.clone(), @@ -26,7 +26,7 @@ impl PyClassMethodRef { .into_ref_with_type(vm, cls) } - fn get(self, _inst: PyObjectRef, owner: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn get(self, _inst: PyObjectRef, owner: PyObjectRef, vm: &VirtualMachine) -> PyResult { Ok(vm .ctx .new_bound_method(self.callable.clone(), owner.clone())) diff --git a/vm/src/obj/objcode.rs b/vm/src/obj/objcode.rs index 2b0a4b93541..21df7f2cc1e 100644 --- a/vm/src/obj/objcode.rs +++ b/vm/src/obj/objcode.rs @@ -26,7 +26,7 @@ impl fmt::Debug for PyCode { } impl PyValue for PyCode { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.code_type() } } @@ -39,7 +39,7 @@ pub fn init(context: &PyContext) { for (name, f) in &[ ( "co_argcount", - code_co_argcount as fn(&mut VirtualMachine, PyFuncArgs) -> PyResult, + code_co_argcount as fn(&VirtualMachine, PyFuncArgs) -> PyResult, ), ("co_consts", code_co_consts), ("co_filename", code_co_filename), @@ -59,12 +59,12 @@ pub fn get_value(obj: &PyObjectRef) -> bytecode::CodeObject { } } -fn code_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn code_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(_cls, None)]); Err(vm.new_type_error("Cannot directly create code object".to_string())) } -fn code_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn code_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(o, Some(vm.ctx.code_type()))]); let code = get_value(o); @@ -78,33 +78,33 @@ fn code_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_str(repr)) } -fn member_code_obj(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn member_code_obj(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.code_type()))]); Ok(get_value(zelf)) } -fn code_co_argcount(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn code_co_argcount(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let code_obj = member_code_obj(vm, args)?; Ok(vm.ctx.new_int(code_obj.arg_names.len())) } -fn code_co_filename(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn code_co_filename(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let code_obj = member_code_obj(vm, args)?; let source_path = code_obj.source_path; Ok(vm.new_str(source_path)) } -fn code_co_firstlineno(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn code_co_firstlineno(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let code_obj = member_code_obj(vm, args)?; Ok(vm.ctx.new_int(code_obj.first_line_number)) } -fn code_co_kwonlyargcount(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn code_co_kwonlyargcount(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let code_obj = member_code_obj(vm, args)?; Ok(vm.ctx.new_int(code_obj.kwonlyarg_names.len())) } -fn code_co_consts(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn code_co_consts(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let code_obj = member_code_obj(vm, args)?; let consts = code_obj .get_constants() @@ -113,7 +113,7 @@ fn code_co_consts(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_tuple(consts)) } -fn code_co_name(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn code_co_name(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let code_obj = member_code_obj(vm, args)?; Ok(vm.new_str(code_obj.obj_name)) } diff --git a/vm/src/obj/objcomplex.rs b/vm/src/obj/objcomplex.rs index ab07b60ba9d..7443306512a 100644 --- a/vm/src/obj/objcomplex.rs +++ b/vm/src/obj/objcomplex.rs @@ -16,7 +16,7 @@ pub struct PyComplex { type PyComplexRef = PyRef; impl PyValue for PyComplex { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.complex_type() } } @@ -71,7 +71,7 @@ fn complex_new( cls: PyClassRef, real: OptionalArg, imag: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let real = match real { OptionalArg::Missing => 0.0, @@ -87,26 +87,26 @@ fn complex_new( PyComplex { value }.into_ref_with_type(vm, cls) } -fn complex_real(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_real(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.complex_type()))]); let Complex64 { re, .. } = get_value(zelf); Ok(vm.ctx.new_float(re)) } -fn complex_imag(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_imag(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.complex_type()))]); let Complex64 { im, .. } = get_value(zelf); Ok(vm.ctx.new_float(im)) } -fn complex_abs(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_abs(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.complex_type()))]); let Complex64 { re, im } = get_value(zelf); Ok(vm.ctx.new_float(re.hypot(im))) } -fn complex_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_add(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -126,7 +126,7 @@ fn complex_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn complex_radd(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_radd(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -145,14 +145,14 @@ fn complex_radd(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn complex_conjugate(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_conjugate(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(i, Some(vm.ctx.complex_type()))]); let v1 = get_value(i); Ok(vm.ctx.new_complex(v1.conj())) } -fn complex_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_eq(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -177,12 +177,12 @@ fn complex_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(result)) } -fn complex_neg(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_neg(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.complex_type()))]); Ok(vm.ctx.new_complex(-get_value(zelf))) } -fn complex_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn complex_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, Some(vm.ctx.complex_type()))]); let v = get_value(obj); let repr = if v.re == 0. { diff --git a/vm/src/obj/objdict.rs b/vm/src/obj/objdict.rs index 8219ab71f52..ad134f5aeba 100644 --- a/vm/src/obj/objdict.rs +++ b/vm/src/obj/objdict.rs @@ -30,7 +30,7 @@ impl fmt::Debug for PyDict { } impl PyValue for PyDict { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.dict_type() } } @@ -45,7 +45,7 @@ pub fn get_mut_elements<'a>(obj: &'a PyObjectRef) -> impl DerefMut PyAttributes { attrs } -pub fn attributes_to_py_dict(vm: &mut VirtualMachine, attributes: PyAttributes) -> PyResult { +pub fn attributes_to_py_dict(vm: &VirtualMachine, attributes: PyAttributes) -> PyResult { let dict = vm.ctx.new_dict(); for (key, value) in attributes { let key = vm.ctx.new_str(key); @@ -133,7 +133,7 @@ pub fn attributes_to_py_dict(vm: &mut VirtualMachine, attributes: PyAttributes) } // Python dict methods: -fn dict_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn dict_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -149,7 +149,7 @@ fn dict_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } else { let iter = objiter::get_iter(vm, dict_obj)?; loop { - fn err(vm: &mut VirtualMachine) -> PyObjectRef { + fn err(vm: &VirtualMachine) -> PyObjectRef { vm.new_type_error("Iterator must have exactly two elements".to_string()) } let element = match objiter::get_next_object(vm, &iter)? { @@ -174,11 +174,11 @@ fn dict_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } impl PyDictRef { - fn len(self, _vm: &mut VirtualMachine) -> usize { + fn len(self, _vm: &VirtualMachine) -> usize { self.entries.borrow().len() } - fn repr(self, vm: &mut VirtualMachine) -> PyResult { + fn repr(self, vm: &VirtualMachine) -> PyResult { let s = if let Some(_guard) = ReprGuard::enter(self.as_object()) { let elements = get_key_value_pairs(self.as_object()); let mut str_parts = vec![]; @@ -195,11 +195,11 @@ impl PyDictRef { Ok(vm.new_str(s)) } - fn contains(self, key: PyStringRef, _vm: &mut VirtualMachine) -> bool { + fn contains(self, key: PyStringRef, _vm: &VirtualMachine) -> bool { self.entries.borrow().contains_key(&key.value) } - fn delitem(self, key: PyStringRef, vm: &mut VirtualMachine) -> PyResult<()> { + fn delitem(self, key: PyStringRef, vm: &VirtualMachine) -> PyResult<()> { let key = &key.value; // Delete the item: let mut elements = self.entries.borrow_mut(); @@ -209,12 +209,12 @@ impl PyDictRef { } } - fn clear(self, _vm: &mut VirtualMachine) { + fn clear(self, _vm: &VirtualMachine) { self.entries.borrow_mut().clear() } /// When iterating over a dictionary, we iterate over the keys of it. - fn iter(self, vm: &mut VirtualMachine) -> PyIteratorValue { + fn iter(self, vm: &VirtualMachine) -> PyIteratorValue { let keys = self .entries .borrow() @@ -229,7 +229,7 @@ impl PyDictRef { } } - fn values(self, vm: &mut VirtualMachine) -> PyIteratorValue { + fn values(self, vm: &VirtualMachine) -> PyIteratorValue { let values = self .entries .borrow() @@ -244,7 +244,7 @@ impl PyDictRef { } } - fn items(self, vm: &mut VirtualMachine) -> PyIteratorValue { + fn items(self, vm: &VirtualMachine) -> PyIteratorValue { let items = self .entries .borrow() @@ -259,12 +259,12 @@ impl PyDictRef { } } - fn setitem(self, needle: PyObjectRef, value: PyObjectRef, _vm: &mut VirtualMachine) { + fn setitem(self, needle: PyObjectRef, value: PyObjectRef, _vm: &VirtualMachine) { let mut elements = self.entries.borrow_mut(); set_item_in_content(&mut elements, &needle, &value) } - fn getitem(self, key: PyStringRef, vm: &mut VirtualMachine) -> PyResult { + fn getitem(self, key: PyStringRef, vm: &VirtualMachine) -> PyResult { let key = &key.value; // What we are looking for: @@ -280,7 +280,7 @@ impl PyDictRef { self, key: PyStringRef, default: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyObjectRef { // What we are looking for: let key = &key.value; diff --git a/vm/src/obj/objellipsis.rs b/vm/src/obj/objellipsis.rs index a0ed8f6441c..03c9d69e8ad 100644 --- a/vm/src/obj/objellipsis.rs +++ b/vm/src/obj/objellipsis.rs @@ -12,12 +12,12 @@ pub fn init(context: &PyContext) { ); } -fn ellipsis_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn ellipsis_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(_cls, None)]); Ok(vm.ctx.ellipsis()) } -fn ellipsis_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn ellipsis_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(_cls, None)]); Ok(vm.new_str("Ellipsis".to_string())) } diff --git a/vm/src/obj/objenumerate.rs b/vm/src/obj/objenumerate.rs index fb7ae7c7167..5a66b7b5e2a 100644 --- a/vm/src/obj/objenumerate.rs +++ b/vm/src/obj/objenumerate.rs @@ -20,7 +20,7 @@ pub struct PyEnumerate { type PyEnumerateRef = PyRef; impl PyValue for PyEnumerate { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.enumerate_type() } } @@ -29,7 +29,7 @@ fn enumerate_new( cls: PyClassRef, iterable: PyObjectRef, start: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let counter = match start { OptionalArg::Present(start) => start.value.clone(), @@ -44,7 +44,7 @@ fn enumerate_new( .into_ref_with_type(vm, cls) } -fn enumerate_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn enumerate_next(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/obj/objfilter.rs b/vm/src/obj/objfilter.rs index da329c809a1..d83f70cc5c5 100644 --- a/vm/src/obj/objfilter.rs +++ b/vm/src/obj/objfilter.rs @@ -14,12 +14,12 @@ pub struct PyFilter { } impl PyValue for PyFilter { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.filter_type() } } -fn filter_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn filter_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -35,7 +35,7 @@ fn filter_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { )) } -fn filter_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn filter_next(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(filter, Some(vm.ctx.filter_type()))]); if let Some(PyFilter { diff --git a/vm/src/obj/objfloat.rs b/vm/src/obj/objfloat.rs index 7c5389a58b6..849b31d408f 100644 --- a/vm/src/obj/objfloat.rs +++ b/vm/src/obj/objfloat.rs @@ -16,13 +16,13 @@ pub struct PyFloat { } impl PyValue for PyFloat { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.float_type() } } impl IntoPyObject for f64 { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { Ok(vm.ctx.new_float(self)) } } @@ -36,7 +36,7 @@ impl From for PyFloat { pub type PyFloatRef = PyRef; impl PyFloatRef { - fn eq(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn eq(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { let value = self.value; let result = if objtype::isinstance(&other, &vm.ctx.float_type()) { let other = get_value(&other); @@ -55,7 +55,7 @@ impl PyFloatRef { vm.ctx.new_bool(result) } - fn lt(self, i2: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn lt(self, i2: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { let v1 = self.value; if objtype::isinstance(&i2, &vm.ctx.float_type()) { vm.ctx.new_bool(v1 < get_value(&i2)) @@ -67,7 +67,7 @@ impl PyFloatRef { } } - fn le(self, i2: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn le(self, i2: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { let v1 = self.value; if objtype::isinstance(&i2, &vm.ctx.float_type()) { vm.ctx.new_bool(v1 <= get_value(&i2)) @@ -79,7 +79,7 @@ impl PyFloatRef { } } - fn gt(self, i2: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn gt(self, i2: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { let v1 = self.value; if objtype::isinstance(&i2, &vm.ctx.float_type()) { vm.ctx.new_bool(v1 > get_value(&i2)) @@ -91,7 +91,7 @@ impl PyFloatRef { } } - fn ge(self, i2: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn ge(self, i2: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { let v1 = self.value; if objtype::isinstance(&i2, &vm.ctx.float_type()) { vm.ctx.new_bool(v1 >= get_value(&i2)) @@ -103,11 +103,11 @@ impl PyFloatRef { } } - fn abs(self, _vm: &mut VirtualMachine) -> f64 { + fn abs(self, _vm: &VirtualMachine) -> f64 { self.value.abs() } - fn add(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn add(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { let v1 = self.value; if objtype::isinstance(&other, &vm.ctx.float_type()) { vm.ctx.new_float(v1 + get_value(&other)) @@ -119,7 +119,7 @@ impl PyFloatRef { } } - fn divmod(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn divmod(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.float_type()) || objtype::isinstance(&other, &vm.ctx.int_type()) { @@ -131,7 +131,7 @@ impl PyFloatRef { } } - fn floordiv(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn floordiv(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let v1 = self.value; let v2 = if objtype::isinstance(&other, &vm.ctx.float_type) { get_value(&other) @@ -150,7 +150,7 @@ impl PyFloatRef { } } - fn new_float(cls: PyObjectRef, arg: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn new_float(cls: PyObjectRef, arg: PyObjectRef, vm: &VirtualMachine) -> PyResult { let value = if objtype::isinstance(&arg, &vm.ctx.float_type()) { get_value(&arg) } else if objtype::isinstance(&arg, &vm.ctx.int_type()) { @@ -191,7 +191,7 @@ impl PyFloatRef { Ok(PyObject::new(PyFloat { value }, cls.clone())) } - fn mod_(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn mod_(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let v1 = self.value; let v2 = if objtype::isinstance(&other, &vm.ctx.float_type) { get_value(&other) @@ -210,11 +210,11 @@ impl PyFloatRef { } } - fn neg(self, _vm: &mut VirtualMachine) -> f64 { + fn neg(self, _vm: &VirtualMachine) -> f64 { -self.value } - fn pow(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn pow(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { let v1 = self.value; if objtype::isinstance(&other, &vm.ctx.float_type()) { vm.ctx.new_float(v1.powf(get_value(&other))) @@ -226,7 +226,7 @@ impl PyFloatRef { } } - fn sub(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn sub(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let v1 = self.value; if objtype::isinstance(&other, &vm.ctx.float_type()) { Ok(vm.ctx.new_float(v1 - get_value(&other))) @@ -239,7 +239,7 @@ impl PyFloatRef { } } - fn rsub(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn rsub(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let v1 = self.value; if objtype::isinstance(&other, &vm.ctx.float_type()) { Ok(vm.ctx.new_float(get_value(&other) - v1)) @@ -252,11 +252,11 @@ impl PyFloatRef { } } - fn repr(self, _vm: &mut VirtualMachine) -> String { + fn repr(self, _vm: &VirtualMachine) -> String { self.value.to_string() } - fn truediv(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn truediv(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let v1 = self.value; let v2 = if objtype::isinstance(&other, &vm.ctx.float_type) { get_value(&other) @@ -275,7 +275,7 @@ impl PyFloatRef { } } - fn rtruediv(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn rtruediv(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let v1 = self.value; let v2 = if objtype::isinstance(&other, &vm.ctx.float_type) { get_value(&other) @@ -294,7 +294,7 @@ impl PyFloatRef { } } - fn mul(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn mul(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let v1 = self.value; if objtype::isinstance(&other, &vm.ctx.float_type) { Ok(vm.ctx.new_float(v1 * get_value(&other))) @@ -307,16 +307,16 @@ impl PyFloatRef { } } - fn is_integer(self, _vm: &mut VirtualMachine) -> bool { + fn is_integer(self, _vm: &VirtualMachine) -> bool { let v = self.value; (v - v.round()).abs() < std::f64::EPSILON } - fn real(self, _vm: &mut VirtualMachine) -> Self { + fn real(self, _vm: &VirtualMachine) -> Self { self } - fn as_integer_ratio(self, vm: &mut VirtualMachine) -> PyResult { + fn as_integer_ratio(self, vm: &VirtualMachine) -> PyResult { let value = self.value; if value.is_infinite() { return Err( @@ -339,7 +339,7 @@ pub fn get_value(obj: &PyObjectRef) -> f64 { obj.payload::().unwrap().value } -pub fn make_float(vm: &mut VirtualMachine, obj: &PyObjectRef) -> PyResult { +pub fn make_float(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult { if objtype::isinstance(obj, &vm.ctx.float_type()) { Ok(get_value(obj)) } else if let Ok(method) = vm.get_method(obj.clone(), "__float__") { diff --git a/vm/src/obj/objframe.rs b/vm/src/obj/objframe.rs index c3ebad300d6..2d179fa24d7 100644 --- a/vm/src/obj/objframe.rs +++ b/vm/src/obj/objframe.rs @@ -15,24 +15,24 @@ pub fn init(context: &PyContext) { context.set_attr(&frame_type, "f_code", context.new_property(frame_fcode)); } -fn frame_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn frame_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(_cls, None)]); Err(vm.new_type_error("Cannot directly create frame object".to_string())) } -fn frame_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn frame_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(_frame, Some(vm.ctx.frame_type()))]); let repr = "".to_string(); Ok(vm.new_str(repr)) } -fn frame_flocals(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn frame_flocals(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(frame, Some(vm.ctx.frame_type()))]); let frame = get_value(frame); Ok(frame.scope.get_locals().clone()) } -fn frame_fcode(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn frame_fcode(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(frame, Some(vm.ctx.frame_type()))]); Ok(vm.ctx.new_code_object(get_value(frame).code.clone())) } diff --git a/vm/src/obj/objfunction.rs b/vm/src/obj/objfunction.rs index f2c0bbafe9c..c4c480d67b4 100644 --- a/vm/src/obj/objfunction.rs +++ b/vm/src/obj/objfunction.rs @@ -22,7 +22,7 @@ impl PyFunction { } impl PyValue for PyFunction { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.function_type() } } @@ -41,7 +41,7 @@ impl PyMethod { } impl PyValue for PyMethod { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.bound_method_type() } } @@ -59,7 +59,7 @@ pub fn init(context: &PyContext) { }); } -fn bind_method(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bind_method(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -73,7 +73,7 @@ fn bind_method(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn function_code(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn function_code(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { match args.args[0].payload() { Some(PyFunction { ref code, .. }) => Ok(code.clone()), None => Err(vm.new_type_error("no code".to_string())), diff --git a/vm/src/obj/objgenerator.rs b/vm/src/obj/objgenerator.rs index 2fe08c13878..208bcb43f95 100644 --- a/vm/src/obj/objgenerator.rs +++ b/vm/src/obj/objgenerator.rs @@ -14,7 +14,7 @@ pub struct PyGenerator { type PyGeneratorRef = PyRef; impl PyValue for PyGenerator { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.generator_type() } } @@ -38,22 +38,22 @@ pub fn init(context: &PyContext) { ); } -pub fn new_generator(frame: PyObjectRef, vm: &mut VirtualMachine) -> PyGeneratorRef { +pub fn new_generator(frame: PyObjectRef, vm: &VirtualMachine) -> PyGeneratorRef { PyGenerator { frame }.into_ref(vm) } -fn generator_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn generator_iter(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(o, Some(vm.ctx.generator_type()))]); Ok(o.clone()) } -fn generator_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn generator_next(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(o, Some(vm.ctx.generator_type()))]); let value = vm.get_none(); send(vm, o, &value) } -fn generator_send(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn generator_send(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -62,7 +62,7 @@ fn generator_send(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { send(vm, o, value) } -fn send(vm: &mut VirtualMachine, gen: &PyObjectRef, value: &PyObjectRef) -> PyResult { +fn send(vm: &VirtualMachine, gen: &PyObjectRef, value: &PyObjectRef) -> PyResult { if let Some(PyGenerator { ref frame }) = gen.payload() { if let Some(frame) = frame.payload::() { frame.push_value(value.clone()); diff --git a/vm/src/obj/objint.rs b/vm/src/obj/objint.rs index d1b1388ceab..553042ed5f2 100644 --- a/vm/src/obj/objint.rs +++ b/vm/src/obj/objint.rs @@ -31,13 +31,13 @@ impl PyInt { } impl IntoPyObject for BigInt { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { Ok(vm.ctx.new_int(self)) } } impl PyValue for PyInt { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.int_type() } } @@ -45,7 +45,7 @@ impl PyValue for PyInt { macro_rules! impl_into_pyobject_int { ($($t:ty)*) => {$( impl IntoPyObject for $t { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { Ok(vm.ctx.new_int(self)) } } @@ -57,7 +57,7 @@ impl_into_pyobject_int!(isize i8 i16 i32 i64 usize u8 u16 u32 u64) ; macro_rules! impl_try_from_object_int { ($(($t:ty, $to_prim:ident),)*) => {$( impl TryFromObject for $t { - fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { match PyRef::::try_from_object(vm, obj)?.value.$to_prim() { Some(value) => Ok(value), None => Err( @@ -86,11 +86,11 @@ impl_try_from_object_int!( ); impl PyIntRef { - fn pass_value(self, _vm: &mut VirtualMachine) -> Self { + fn pass_value(self, _vm: &VirtualMachine) -> Self { self } - fn eq(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn eq(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_bool(self.value == *get_value(&other)) } else { @@ -98,7 +98,7 @@ impl PyIntRef { } } - fn ne(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn ne(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_bool(self.value != *get_value(&other)) } else { @@ -106,7 +106,7 @@ impl PyIntRef { } } - fn lt(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn lt(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_bool(self.value < *get_value(&other)) } else { @@ -114,7 +114,7 @@ impl PyIntRef { } } - fn le(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn le(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_bool(self.value <= *get_value(&other)) } else { @@ -122,7 +122,7 @@ impl PyIntRef { } } - fn gt(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn gt(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_bool(self.value > *get_value(&other)) } else { @@ -130,7 +130,7 @@ impl PyIntRef { } } - fn ge(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn ge(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_bool(self.value >= *get_value(&other)) } else { @@ -138,7 +138,7 @@ impl PyIntRef { } } - fn add(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn add(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_int((&self.value) + get_value(&other)) } else { @@ -146,7 +146,7 @@ impl PyIntRef { } } - fn sub(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn sub(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_int((&self.value) - get_value(&other)) } else { @@ -154,7 +154,7 @@ impl PyIntRef { } } - fn rsub(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn rsub(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_int(get_value(&other) - (&self.value)) } else { @@ -162,7 +162,7 @@ impl PyIntRef { } } - fn mul(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn mul(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_int((&self.value) * get_value(&other)) } else { @@ -170,7 +170,7 @@ impl PyIntRef { } } - fn truediv(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn truediv(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.int_type()) { div_ints(vm, &self.value, &get_value(&other)) } else { @@ -178,7 +178,7 @@ impl PyIntRef { } } - fn rtruediv(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn rtruediv(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.int_type()) { div_ints(vm, &get_value(&other), &self.value) } else { @@ -186,7 +186,7 @@ impl PyIntRef { } } - fn floordiv(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn floordiv(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.int_type()) { let v2 = get_value(&other); if *v2 != BigInt::zero() { @@ -199,7 +199,7 @@ impl PyIntRef { } } - fn lshift(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn lshift(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if !objtype::isinstance(&other, &vm.ctx.int_type()) { return Err(vm.new_type_error(format!( "unsupported operand type(s) for << '{}' and '{}'", @@ -222,7 +222,7 @@ impl PyIntRef { } } - fn rshift(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn rshift(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if !objtype::isinstance(&other, &vm.ctx.int_type()) { return Err(vm.new_type_error(format!( "unsupported operand type(s) for >> '{}' and '{}'", @@ -245,7 +245,7 @@ impl PyIntRef { } } - fn xor(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn xor(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_int((&self.value) ^ get_value(&other)) } else { @@ -253,7 +253,7 @@ impl PyIntRef { } } - fn rxor(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn rxor(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_int(get_value(&other) ^ (&self.value)) } else { @@ -261,7 +261,7 @@ impl PyIntRef { } } - fn or(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn or(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { vm.ctx.new_int((&self.value) | get_value(&other)) } else { @@ -269,7 +269,7 @@ impl PyIntRef { } } - fn and(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn and(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { let v2 = get_value(&other); vm.ctx.new_int((&self.value) & v2) @@ -278,7 +278,7 @@ impl PyIntRef { } } - fn pow(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn pow(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&other, &vm.ctx.int_type()) { let v2 = get_value(&other).to_u32().unwrap(); vm.ctx.new_int(self.value.pow(v2)) @@ -290,7 +290,7 @@ impl PyIntRef { } } - fn mod_(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn mod_(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.int_type()) { let v2 = get_value(&other); if *v2 != BigInt::zero() { @@ -303,7 +303,7 @@ impl PyIntRef { } } - fn divmod(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn divmod(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.int_type()) { let v2 = get_value(&other); if *v2 != BigInt::zero() { @@ -319,37 +319,37 @@ impl PyIntRef { } } - fn neg(self, _vm: &mut VirtualMachine) -> BigInt { + fn neg(self, _vm: &VirtualMachine) -> BigInt { -(&self.value) } - fn hash(self, _vm: &mut VirtualMachine) -> u64 { + fn hash(self, _vm: &VirtualMachine) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); self.value.hash(&mut hasher); hasher.finish() } - fn abs(self, _vm: &mut VirtualMachine) -> BigInt { + fn abs(self, _vm: &VirtualMachine) -> BigInt { self.value.abs() } - fn round(self, _precision: OptionalArg, _vm: &mut VirtualMachine) -> Self { + fn round(self, _precision: OptionalArg, _vm: &VirtualMachine) -> Self { self } - fn float(self, _vm: &mut VirtualMachine) -> f64 { + fn float(self, _vm: &VirtualMachine) -> f64 { self.value.to_f64().unwrap() } - fn invert(self, _vm: &mut VirtualMachine) -> BigInt { + fn invert(self, _vm: &VirtualMachine) -> BigInt { !(&self.value) } - fn repr(self, _vm: &mut VirtualMachine) -> String { + fn repr(self, _vm: &VirtualMachine) -> String { self.value.to_string() } - fn format(self, spec: PyRef, vm: &mut VirtualMachine) -> PyResult { + fn format(self, spec: PyRef, vm: &VirtualMachine) -> PyResult { let format_spec = FormatSpec::parse(&spec.value); match format_spec.format_int(&self.value) { Ok(string) => Ok(string), @@ -357,20 +357,20 @@ impl PyIntRef { } } - fn bool(self, _vm: &mut VirtualMachine) -> bool { + fn bool(self, _vm: &VirtualMachine) -> bool { !self.value.is_zero() } - fn bit_length(self, _vm: &mut VirtualMachine) -> usize { + fn bit_length(self, _vm: &VirtualMachine) -> usize { self.value.bits() } - fn imag(self, _vm: &mut VirtualMachine) -> usize { + fn imag(self, _vm: &VirtualMachine) -> usize { 0 } } -fn int_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn int_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -393,7 +393,7 @@ fn int_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } // Casting function: -pub fn to_int(vm: &mut VirtualMachine, obj: &PyObjectRef, base: u32) -> PyResult { +pub fn to_int(vm: &VirtualMachine, obj: &PyObjectRef, base: u32) -> PyResult { let val = if objtype::isinstance(obj, &vm.ctx.int_type()) { get_value(obj).clone() } else if objtype::isinstance(obj, &vm.ctx.float_type()) { @@ -426,7 +426,7 @@ pub fn get_value(obj: &PyObjectRef) -> &BigInt { } #[inline] -fn div_ints(vm: &mut VirtualMachine, i1: &BigInt, i2: &BigInt) -> PyResult { +fn div_ints(vm: &VirtualMachine, i1: &BigInt, i2: &BigInt) -> PyResult { if i2.is_zero() { return Err(vm.new_zero_division_error("integer division by zero".to_string())); } diff --git a/vm/src/obj/objiter.rs b/vm/src/obj/objiter.rs index 4c527776d70..1b7709d748a 100644 --- a/vm/src/obj/objiter.rs +++ b/vm/src/obj/objiter.rs @@ -18,14 +18,14 @@ use super::objtype; * in the vm when a for loop is entered. Next, it is used when the builtin * function 'iter' is called. */ -pub fn get_iter(vm: &mut VirtualMachine, iter_target: &PyObjectRef) -> PyResult { +pub fn get_iter(vm: &VirtualMachine, iter_target: &PyObjectRef) -> PyResult { vm.call_method(iter_target, "__iter__", vec![]) // let type_str = objstr::get_value(&vm.to_str(iter_target.typ()).unwrap()); // let type_error = vm.new_type_error(format!("Cannot iterate over {}", type_str)); // return Err(type_error); } -pub fn call_next(vm: &mut VirtualMachine, iter_obj: &PyObjectRef) -> PyResult { +pub fn call_next(vm: &VirtualMachine, iter_obj: &PyObjectRef) -> PyResult { vm.call_method(iter_obj, "__next__", vec![]) } @@ -33,7 +33,7 @@ pub fn call_next(vm: &mut VirtualMachine, iter_obj: &PyObjectRef) -> PyResult { * Helper function to retrieve the next object (or none) from an iterator. */ pub fn get_next_object( - vm: &mut VirtualMachine, + vm: &VirtualMachine, iter_obj: &PyObjectRef, ) -> PyResult> { let next_obj: PyResult = call_next(vm, iter_obj); @@ -52,7 +52,7 @@ pub fn get_next_object( } /* Retrieve all elements from an iterator */ -pub fn get_all(vm: &mut VirtualMachine, iter_obj: &PyObjectRef) -> PyResult> { +pub fn get_all(vm: &VirtualMachine, iter_obj: &PyObjectRef) -> PyResult> { let mut elements = vec![]; loop { let element = get_next_object(vm, iter_obj)?; @@ -64,12 +64,12 @@ pub fn get_all(vm: &mut VirtualMachine, iter_obj: &PyObjectRef) -> PyResult PyObjectRef { +pub fn new_stop_iteration(vm: &VirtualMachine) -> PyObjectRef { let stop_iteration_type = vm.ctx.exceptions.stop_iteration.clone(); vm.new_exception(stop_iteration_type, "End of iterator".to_string()) } -fn contains(vm: &mut VirtualMachine, args: PyFuncArgs, iter_type: PyObjectRef) -> PyResult { +fn contains(vm: &VirtualMachine, args: PyFuncArgs, iter_type: PyObjectRef) -> PyResult { arg_check!( vm, args, @@ -93,9 +93,7 @@ fn contains(vm: &mut VirtualMachine, args: PyFuncArgs, iter_type: PyObjectRef) - pub fn iter_type_init(context: &PyContext, iter_type: &PyObjectRef) { let contains_func = { let cloned_iter_type = iter_type.clone(); - move |vm: &mut VirtualMachine, args: PyFuncArgs| { - contains(vm, args, cloned_iter_type.clone()) - } + move |vm: &VirtualMachine, args: PyFuncArgs| contains(vm, args, cloned_iter_type.clone()) }; context.set_attr( &iter_type, @@ -104,7 +102,7 @@ pub fn iter_type_init(context: &PyContext, iter_type: &PyObjectRef) { ); let iter_func = { let cloned_iter_type = iter_type.clone(); - move |vm: &mut VirtualMachine, args: PyFuncArgs| { + move |vm: &VirtualMachine, args: PyFuncArgs| { arg_check!( vm, args, @@ -118,13 +116,13 @@ pub fn iter_type_init(context: &PyContext, iter_type: &PyObjectRef) { } // Sequence iterator: -fn iter_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn iter_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(iter_target, None)]); get_iter(vm, iter_target) } -fn iter_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn iter_next(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(iter, Some(vm.ctx.iter_type()))]); if let Some(PyIteratorValue { diff --git a/vm/src/obj/objlist.rs b/vm/src/obj/objlist.rs index 903cd760b42..1b3a9b4fa97 100644 --- a/vm/src/obj/objlist.rs +++ b/vm/src/obj/objlist.rs @@ -40,7 +40,7 @@ impl From> for PyList { } impl PyValue for PyList { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.list_type() } } @@ -48,17 +48,17 @@ impl PyValue for PyList { pub type PyListRef = PyRef; impl PyListRef { - pub fn append(self, x: PyObjectRef, _vm: &mut VirtualMachine) { + pub fn append(self, x: PyObjectRef, _vm: &VirtualMachine) { self.elements.borrow_mut().push(x); } - fn extend(self, x: PyObjectRef, vm: &mut VirtualMachine) -> PyResult<()> { + fn extend(self, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let mut new_elements = vm.extract_elements(&x)?; self.elements.borrow_mut().append(&mut new_elements); Ok(()) } - fn insert(self, position: isize, element: PyObjectRef, _vm: &mut VirtualMachine) { + fn insert(self, position: isize, element: PyObjectRef, _vm: &VirtualMachine) { let mut vec = self.elements.borrow_mut(); let vec_len = vec.len().to_isize().unwrap(); // This unbounded position can be < 0 or > vec.len() @@ -72,7 +72,7 @@ impl PyListRef { vec.insert(position, element.clone()); } - fn add(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn add(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.list_type()) { let e1 = self.elements.borrow(); let e2 = get_elements(&other); @@ -83,7 +83,7 @@ impl PyListRef { } } - fn iadd(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn iadd(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.list_type()) { self.elements .borrow_mut() @@ -94,23 +94,23 @@ impl PyListRef { } } - fn clear(self, _vm: &mut VirtualMachine) { + fn clear(self, _vm: &VirtualMachine) { self.elements.borrow_mut().clear(); } - fn copy(self, vm: &mut VirtualMachine) -> PyObjectRef { + fn copy(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_list(self.elements.borrow().clone()) } - fn len(self, _vm: &mut VirtualMachine) -> usize { + fn len(self, _vm: &VirtualMachine) -> usize { self.elements.borrow().len() } - fn reverse(self, _vm: &mut VirtualMachine) { + fn reverse(self, _vm: &VirtualMachine) { self.elements.borrow_mut().reverse(); } - fn getitem(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn getitem(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { get_item( vm, self.as_object(), @@ -119,14 +119,14 @@ impl PyListRef { ) } - fn iter(self, _vm: &mut VirtualMachine) -> PyIteratorValue { + fn iter(self, _vm: &VirtualMachine) -> PyIteratorValue { PyIteratorValue { position: Cell::new(0), iterated_obj: self.into_object(), } } - fn setitem(self, key: PyObjectRef, value: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn setitem(self, key: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { let mut elements = self.elements.borrow_mut(); if objtype::isinstance(&key, &vm.ctx.int_type()) { @@ -145,7 +145,7 @@ impl PyListRef { } } - fn repr(self, vm: &mut VirtualMachine) -> PyResult { + fn repr(self, vm: &VirtualMachine) -> PyResult { let s = if let Some(_guard) = ReprGuard::enter(self.as_object()) { let mut str_parts = vec![]; for elem in self.elements.borrow().iter() { @@ -159,12 +159,12 @@ impl PyListRef { Ok(s) } - fn mul(self, counter: isize, vm: &mut VirtualMachine) -> PyObjectRef { + fn mul(self, counter: isize, vm: &VirtualMachine) -> PyObjectRef { let new_elements = seq_mul(&self.elements.borrow(), counter); vm.ctx.new_list(new_elements) } - fn count(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn count(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { let mut count: usize = 0; for element in self.elements.borrow().iter() { if needle.is(element) { @@ -179,7 +179,7 @@ impl PyListRef { Ok(count) } - fn contains(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn contains(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { for element in self.elements.borrow().iter() { if needle.is(element) { return Ok(true); @@ -193,7 +193,7 @@ impl PyListRef { Ok(false) } - fn index(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn index(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { for (index, element) in self.elements.borrow().iter().enumerate() { if needle.is(element) { return Ok(index); @@ -207,7 +207,7 @@ impl PyListRef { Err(vm.new_value_error(format!("'{}' is not in list", needle_str))) } - fn pop(self, i: OptionalArg, vm: &mut VirtualMachine) -> PyResult { + fn pop(self, i: OptionalArg, vm: &VirtualMachine) -> PyResult { let mut i = i.into_option().unwrap_or(-1); let mut elements = self.elements.borrow_mut(); if i < 0 { @@ -222,7 +222,7 @@ impl PyListRef { } } - fn remove(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult<()> { + fn remove(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let mut ri: Option = None; for (index, element) in self.elements.borrow().iter().enumerate() { if needle.is(element) { @@ -245,7 +245,7 @@ impl PyListRef { } } - fn eq(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn eq(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if self.as_object().is(&other) { return Ok(vm.new_bool(true)); } @@ -260,7 +260,7 @@ impl PyListRef { } } - fn lt(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn lt(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.list_type()) { let zelf = self.elements.borrow(); let other = get_elements(&other); @@ -271,7 +271,7 @@ impl PyListRef { } } - fn gt(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn gt(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.list_type()) { let zelf = self.elements.borrow(); let other = get_elements(&other); @@ -282,7 +282,7 @@ impl PyListRef { } } - fn ge(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn ge(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.list_type()) { let zelf = self.elements.borrow(); let other = get_elements(&other); @@ -293,7 +293,7 @@ impl PyListRef { } } - fn le(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn le(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.list_type()) { let zelf = self.elements.borrow(); let other = get_elements(&other); @@ -308,7 +308,7 @@ impl PyListRef { fn list_new( cls: PyRef, iterable: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { if !objtype::issubclass(cls.as_object(), &vm.ctx.list_type()) { return Err(vm.new_type_error(format!("{} is not a subtype of list", cls))); @@ -324,7 +324,7 @@ fn list_new( } fn quicksort( - vm: &mut VirtualMachine, + vm: &VirtualMachine, keys: &mut [PyObjectRef], values: &mut [PyObjectRef], ) -> PyResult<()> { @@ -338,7 +338,7 @@ fn quicksort( } fn partition( - vm: &mut VirtualMachine, + vm: &VirtualMachine, keys: &mut [PyObjectRef], values: &mut [PyObjectRef], ) -> PyResult { @@ -365,7 +365,7 @@ fn partition( } fn do_sort( - vm: &mut VirtualMachine, + vm: &VirtualMachine, values: &mut Vec, key_func: Option, reverse: bool, @@ -388,7 +388,7 @@ fn do_sort( Ok(()) } -fn list_sort(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn list_sort(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(list, Some(vm.ctx.list_type()))]); let key_func = args.get_optional_kwarg("key"); let reverse = args.get_optional_kwarg("reverse"); diff --git a/vm/src/obj/objmap.rs b/vm/src/obj/objmap.rs index 029d3bae91a..74aabe1072a 100644 --- a/vm/src/obj/objmap.rs +++ b/vm/src/obj/objmap.rs @@ -13,7 +13,7 @@ pub struct PyMap { type PyMapRef = PyRef; impl PyValue for PyMap { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.map_type() } } @@ -22,7 +22,7 @@ fn map_new( cls: PyClassRef, function: PyObjectRef, iterables: Args, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let iterators = iterables .into_iter() @@ -35,7 +35,7 @@ fn map_new( .into_ref_with_type(vm, cls.clone()) } -fn map_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn map_next(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(map, Some(vm.ctx.map_type()))]); if let Some(PyMap { diff --git a/vm/src/obj/objmemory.rs b/vm/src/obj/objmemory.rs index 5386faaf2eb..aa679855145 100644 --- a/vm/src/obj/objmemory.rs +++ b/vm/src/obj/objmemory.rs @@ -8,12 +8,12 @@ pub struct PyMemoryView { } impl PyValue for PyMemoryView { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.memoryview_type() } } -pub fn new_memory_view(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +pub fn new_memory_view(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(cls, None), (bytes_object, None)]); vm.ctx.set_attr(&cls, "obj", bytes_object.clone()); Ok(PyObject::new( diff --git a/vm/src/obj/objmodule.rs b/vm/src/obj/objmodule.rs index da7d2824862..fe6e3fca1d1 100644 --- a/vm/src/obj/objmodule.rs +++ b/vm/src/obj/objmodule.rs @@ -10,13 +10,13 @@ pub struct PyModule { pub type PyModuleRef = PyRef; impl PyValue for PyModule { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.module_type() } } impl PyModuleRef { - fn dir(self: PyModuleRef, vm: &mut VirtualMachine) -> PyResult { + fn dir(self: PyModuleRef, vm: &VirtualMachine) -> PyResult { let keys = self .dict .get_key_value_pairs() @@ -26,7 +26,7 @@ impl PyModuleRef { Ok(vm.ctx.new_list(keys)) } - fn set_attr(self, attr: PyStringRef, value: PyObjectRef, vm: &mut VirtualMachine) { + fn set_attr(self, attr: PyStringRef, value: PyObjectRef, vm: &VirtualMachine) { self.dict.set_item(&vm.ctx, &attr.value, value) } } diff --git a/vm/src/obj/objnone.rs b/vm/src/obj/objnone.rs index 1c005121990..6bee900312f 100644 --- a/vm/src/obj/objnone.rs +++ b/vm/src/obj/objnone.rs @@ -12,7 +12,7 @@ pub struct PyNone; pub type PyNoneRef = PyRef; impl PyValue for PyNone { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.none().typ() } } @@ -20,13 +20,13 @@ impl PyValue for PyNone { // This allows a built-in function to not return a value, mapping to // Python's behavior of returning `None` in this situation. impl IntoPyObject for () { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { Ok(vm.ctx.none()) } } impl IntoPyObject for Option { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { match self { Some(x) => x.into_pyobject(vm), None => Ok(vm.ctx.none()), @@ -35,15 +35,15 @@ impl IntoPyObject for Option { } impl PyNoneRef { - fn repr(self, _vm: &mut VirtualMachine) -> PyResult { + fn repr(self, _vm: &VirtualMachine) -> PyResult { Ok("None".to_string()) } - fn bool(self, _vm: &mut VirtualMachine) -> PyResult { + fn bool(self, _vm: &VirtualMachine) -> PyResult { Ok(false) } - fn get_attribute(self, name: PyStringRef, vm: &mut VirtualMachine) -> PyResult { + fn get_attribute(self, name: PyStringRef, vm: &VirtualMachine) -> PyResult { trace!("None.__getattribute__({:?}, {:?})", self, name); let cls = self.typ().into_object(); @@ -60,7 +60,7 @@ impl PyNoneRef { get_func: PyObjectRef, obj: PyObjectRef, cls: PyObjectRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { if let Ok(property) = PyPropertyRef::try_from_object(vm, descriptor.clone()) { property.instance_binding_get(obj, vm) @@ -95,7 +95,7 @@ impl PyNoneRef { } } -fn none_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn none_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/obj/objobject.rs b/vm/src/obj/objobject.rs index f7e91a8d586..86c5469022b 100644 --- a/vm/src/obj/objobject.rs +++ b/vm/src/obj/objobject.rs @@ -13,14 +13,14 @@ use crate::vm::VirtualMachine; pub struct PyInstance; impl PyValue for PyInstance { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.object() } } pub type PyInstanceRef = PyRef; -pub fn new_instance(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult { +pub fn new_instance(vm: &VirtualMachine, mut args: PyFuncArgs) -> PyResult { // more or less __new__ operator let cls = args.shift(); Ok(if cls.is(&vm.ctx.object) { @@ -30,7 +30,7 @@ pub fn new_instance(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult { }) } -fn object_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_eq(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -39,7 +39,7 @@ fn object_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.not_implemented()) } -fn object_ne(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_ne(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -49,7 +49,7 @@ fn object_ne(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.not_implemented()) } -fn object_lt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_lt(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -59,7 +59,7 @@ fn object_lt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.not_implemented()) } -fn object_le(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_le(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -69,7 +69,7 @@ fn object_le(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.not_implemented()) } -fn object_gt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_gt(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -79,7 +79,7 @@ fn object_gt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.not_implemented()) } -fn object_ge(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_ge(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -89,7 +89,7 @@ fn object_ge(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.not_implemented()) } -fn object_hash(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_hash(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(_zelf, Some(vm.ctx.object()))]); // For now default to non hashable @@ -100,7 +100,7 @@ fn object_setattr( obj: PyInstanceRef, attr_name: PyStringRef, value: PyObjectRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult<()> { trace!("object.__setattr__({:?}, {}, {:?})", obj, attr_name, value); let cls = obj.as_object().typ(); @@ -126,11 +126,7 @@ fn object_setattr( } } -fn object_delattr( - obj: PyInstanceRef, - attr_name: PyStringRef, - vm: &mut VirtualMachine, -) -> PyResult<()> { +fn object_delattr(obj: PyInstanceRef, attr_name: PyStringRef, vm: &VirtualMachine) -> PyResult<()> { let cls = obj.as_object().typ(); if let Some(attr) = cls.get_attr(&attr_name.value) { @@ -154,19 +150,19 @@ fn object_delattr( } } -fn object_str(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_str(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.object()))]); vm.call_method(zelf, "__repr__", vec![]) } -fn object_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, Some(vm.ctx.object()))]); let type_name = objtype::get_type_name(&obj.typ()); let address = obj.get_id(); Ok(vm.new_str(format!("<{} object at 0x{:x}>", type_name, address))) } -pub fn object_dir(obj: PyObjectRef, vm: &mut VirtualMachine) -> PyList { +pub fn object_dir(obj: PyObjectRef, vm: &VirtualMachine) -> PyList { let attributes = get_attributes(&obj); let attributes: Vec = attributes .keys() @@ -178,7 +174,7 @@ pub fn object_dir(obj: PyObjectRef, vm: &mut VirtualMachine) -> PyList { fn object_format( obj: PyObjectRef, format_spec: PyStringRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { if format_spec.value.is_empty() { vm.to_str(&obj) @@ -223,24 +219,24 @@ pub fn init(context: &PyContext) { context.set_attr(&object, "__doc__", context.new_str(object_doc.to_string())); } -fn object_init(vm: &mut VirtualMachine, _args: PyFuncArgs) -> PyResult { +fn object_init(vm: &VirtualMachine, _args: PyFuncArgs) -> PyResult { Ok(vm.ctx.none()) } -fn object_class(obj: PyObjectRef, _vm: &mut VirtualMachine) -> PyObjectRef { +fn object_class(obj: PyObjectRef, _vm: &VirtualMachine) -> PyObjectRef { obj.typ() } fn object_class_setter( instance: PyObjectRef, _value: PyObjectRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let type_repr = vm.to_pystr(&instance.typ())?; Err(vm.new_type_error(format!("can't change class of type '{}'", type_repr))) } -fn object_dict(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_dict(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { if let Some(ref dict) = args.args[0].dict { let new_dict = vm.new_dict(); for (attr, value) in dict.borrow().iter() { @@ -252,7 +248,7 @@ fn object_dict(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn object_getattribute(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn object_getattribute(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/obj/objproperty.rs b/vm/src/obj/objproperty.rs index 44461c41b84..d1791f2485f 100644 --- a/vm/src/obj/objproperty.rs +++ b/vm/src/obj/objproperty.rs @@ -16,7 +16,7 @@ pub struct PyReadOnlyProperty { } impl PyValue for PyReadOnlyProperty { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.readonly_property_type() } } @@ -28,7 +28,7 @@ impl PyReadOnlyPropertyRef { self, obj: PyObjectRef, _owner: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { if obj.is(&vm.ctx.none) { Ok(self.into_object()) @@ -47,7 +47,7 @@ pub struct PyProperty { } impl PyValue for PyProperty { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.property_type() } } @@ -61,7 +61,7 @@ impl PyPropertyRef { fset: OptionalArg, fdel: OptionalArg, _doc: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { PyProperty { getter: fget.into_option(), @@ -74,11 +74,7 @@ impl PyPropertyRef { // Descriptor methods // specialised version that doesn't check for None - pub(crate) fn instance_binding_get( - self, - obj: PyObjectRef, - vm: &mut VirtualMachine, - ) -> PyResult { + pub(crate) fn instance_binding_get(self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { if let Some(getter) = self.getter.as_ref() { vm.invoke(getter.clone(), obj) } else { @@ -90,7 +86,7 @@ impl PyPropertyRef { self, obj: PyObjectRef, _owner: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { if let Some(getter) = self.getter.as_ref() { if obj.is(&vm.ctx.none) { @@ -103,7 +99,7 @@ impl PyPropertyRef { } } - fn set(self, obj: PyObjectRef, value: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn set(self, obj: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { if let Some(setter) = self.setter.as_ref() { vm.invoke(setter.clone(), vec![obj, value]) } else { @@ -111,7 +107,7 @@ impl PyPropertyRef { } } - fn delete(self, obj: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn delete(self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { if let Some(deleter) = self.deleter.as_ref() { vm.invoke(deleter.clone(), obj) } else { @@ -121,21 +117,21 @@ impl PyPropertyRef { // Access functions - fn fget(self, _vm: &mut VirtualMachine) -> Option { + fn fget(self, _vm: &VirtualMachine) -> Option { self.getter.clone() } - fn fset(self, _vm: &mut VirtualMachine) -> Option { + fn fset(self, _vm: &VirtualMachine) -> Option { self.setter.clone() } - fn fdel(self, _vm: &mut VirtualMachine) -> Option { + fn fdel(self, _vm: &VirtualMachine) -> Option { self.deleter.clone() } // Python builder functions - fn getter(self, getter: Option, vm: &mut VirtualMachine) -> PyResult { + fn getter(self, getter: Option, vm: &VirtualMachine) -> PyResult { PyProperty { getter: getter.or_else(|| self.getter.clone()), setter: self.setter.clone(), @@ -144,7 +140,7 @@ impl PyPropertyRef { .into_ref_with_type(vm, self.typ()) } - fn setter(self, setter: Option, vm: &mut VirtualMachine) -> PyResult { + fn setter(self, setter: Option, vm: &VirtualMachine) -> PyResult { PyProperty { getter: self.getter.clone(), setter: setter.or_else(|| self.setter.clone()), @@ -153,7 +149,7 @@ impl PyPropertyRef { .into_ref_with_type(vm, self.typ()) } - fn deleter(self, deleter: Option, vm: &mut VirtualMachine) -> PyResult { + fn deleter(self, deleter: Option, vm: &VirtualMachine) -> PyResult { PyProperty { getter: self.getter.clone(), setter: self.setter.clone(), diff --git a/vm/src/obj/objrange.rs b/vm/src/obj/objrange.rs index 49f1a9e9888..0730762a840 100644 --- a/vm/src/obj/objrange.rs +++ b/vm/src/obj/objrange.rs @@ -25,7 +25,7 @@ pub struct PyRange { } impl PyValue for PyRange { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.range_type() } } @@ -196,7 +196,7 @@ pub fn init(context: &PyContext) { context.set_attr(&range_type, "step", context.new_property(range_step)); } -fn range_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -232,7 +232,7 @@ fn range_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn range_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_iter(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(range, Some(vm.ctx.range_type()))]); Ok(PyObject::new( @@ -244,7 +244,7 @@ fn range_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { )) } -fn range_reversed(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_reversed(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.range_type()))]); let range = get_value(zelf).reversed(); @@ -258,7 +258,7 @@ fn range_reversed(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { )) } -fn range_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_len(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.range_type()))]); if let Some(len) = get_value(zelf).try_len() { @@ -268,7 +268,7 @@ fn range_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn range_getitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_getitem(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -328,7 +328,7 @@ fn range_getitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn range_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.range_type()))]); let repr = get_value(zelf).repr(); @@ -336,7 +336,7 @@ fn range_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_str(repr)) } -fn range_bool(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_bool(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.range_type()))]); let len = get_value(zelf).len(); @@ -344,7 +344,7 @@ fn range_bool(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(len > 0)) } -fn range_contains(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_contains(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -362,7 +362,7 @@ fn range_contains(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bool(result)) } -fn range_index(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_index(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -383,7 +383,7 @@ fn range_index(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn range_count(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_count(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -399,17 +399,17 @@ fn range_count(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn range_start(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_start(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.range_type()))]); Ok(vm.ctx.new_int(get_value(zelf).start)) } -fn range_stop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_stop(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.range_type()))]); Ok(vm.ctx.new_int(get_value(zelf).end)) } -fn range_step(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn range_step(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, Some(vm.ctx.range_type()))]); Ok(vm.ctx.new_int(get_value(zelf).step)) } diff --git a/vm/src/obj/objsequence.rs b/vm/src/obj/objsequence.rs index 2fd97d27903..ad9c7bf3612 100644 --- a/vm/src/obj/objsequence.rs +++ b/vm/src/obj/objsequence.rs @@ -61,11 +61,7 @@ pub trait PySliceableSequence { start..stop } - fn get_slice_items( - &self, - vm: &mut VirtualMachine, - slice: &PyObjectRef, - ) -> Result + fn get_slice_items(&self, vm: &VirtualMachine, slice: &PyObjectRef) -> Result where Self: Sized, { @@ -142,7 +138,7 @@ impl PySliceableSequence for Vec { } pub fn get_item( - vm: &mut VirtualMachine, + vm: &VirtualMachine, sequence: &PyObjectRef, elements: &[PyObjectRef], subscript: PyObjectRef, @@ -186,7 +182,7 @@ pub fn get_item( } pub fn seq_equal( - vm: &mut VirtualMachine, + vm: &VirtualMachine, zelf: &[PyObjectRef], other: &[PyObjectRef], ) -> Result { @@ -207,7 +203,7 @@ pub fn seq_equal( } pub fn seq_lt( - vm: &mut VirtualMachine, + vm: &VirtualMachine, zelf: &[PyObjectRef], other: &[PyObjectRef], ) -> Result { @@ -247,7 +243,7 @@ pub fn seq_lt( } pub fn seq_gt( - vm: &mut VirtualMachine, + vm: &VirtualMachine, zelf: &[PyObjectRef], other: &[PyObjectRef], ) -> Result { @@ -286,7 +282,7 @@ pub fn seq_gt( } pub fn seq_ge( - vm: &mut VirtualMachine, + vm: &VirtualMachine, zelf: &[PyObjectRef], other: &[PyObjectRef], ) -> Result { @@ -294,7 +290,7 @@ pub fn seq_ge( } pub fn seq_le( - vm: &mut VirtualMachine, + vm: &VirtualMachine, zelf: &[PyObjectRef], other: &[PyObjectRef], ) -> Result { diff --git a/vm/src/obj/objset.rs b/vm/src/obj/objset.rs index 2b462614682..b11c21aa39d 100644 --- a/vm/src/obj/objset.rs +++ b/vm/src/obj/objset.rs @@ -32,7 +32,7 @@ impl fmt::Debug for PySet { } impl PyValue for PySet { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.set_type() } } @@ -42,10 +42,10 @@ pub fn get_elements(obj: &PyObjectRef) -> HashMap { } fn perform_action_with_hash( - vm: &mut VirtualMachine, + vm: &VirtualMachine, elements: &mut HashMap, item: &PyObjectRef, - f: &Fn(&mut VirtualMachine, &mut HashMap, u64, &PyObjectRef) -> PyResult, + f: &Fn(&VirtualMachine, &mut HashMap, u64, &PyObjectRef) -> PyResult, ) -> PyResult { let hash: PyObjectRef = vm.call_method(item, "__hash__", vec![])?; @@ -57,12 +57,12 @@ fn perform_action_with_hash( } fn insert_into_set( - vm: &mut VirtualMachine, + vm: &VirtualMachine, elements: &mut HashMap, item: &PyObjectRef, ) -> PyResult { fn insert( - vm: &mut VirtualMachine, + vm: &VirtualMachine, elements: &mut HashMap, key: u64, value: &PyObjectRef, @@ -73,7 +73,7 @@ fn insert_into_set( perform_action_with_hash(vm, elements, item, &insert) } -fn set_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_add(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { trace!("set.add called with: {:?}", args); arg_check!( vm, @@ -86,7 +86,7 @@ fn set_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn set_remove(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_remove(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { trace!("set.remove called with: {:?}", args); arg_check!( vm, @@ -96,7 +96,7 @@ fn set_remove(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { match s.payload::() { Some(set) => { fn remove( - vm: &mut VirtualMachine, + vm: &VirtualMachine, elements: &mut HashMap, key: u64, value: &PyObjectRef, @@ -115,7 +115,7 @@ fn set_remove(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn set_discard(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_discard(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { trace!("set.discard called with: {:?}", args); arg_check!( vm, @@ -125,7 +125,7 @@ fn set_discard(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { match s.payload::() { Some(set) => { fn discard( - vm: &mut VirtualMachine, + vm: &VirtualMachine, elements: &mut HashMap, key: u64, _value: &PyObjectRef, @@ -139,7 +139,7 @@ fn set_discard(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn set_clear(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_clear(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { trace!("set.clear called"); arg_check!(vm, args, required = [(s, Some(vm.ctx.set_type()))]); match s.payload::() { @@ -155,7 +155,7 @@ fn set_clear(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { fn set_new( cls: PyClassRef, iterable: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { if !objtype::issubclass(cls.as_object(), &vm.ctx.set_type()) { return Err(vm.new_type_error(format!("{} is not a subtype of set", cls))); @@ -179,14 +179,14 @@ fn set_new( .into_ref_with_type(vm, cls) } -fn set_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_len(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { trace!("set.len called with: {:?}", args); arg_check!(vm, args, required = [(s, Some(vm.ctx.set_type()))]); let elements = get_elements(s); Ok(vm.context().new_int(elements.len())) } -fn set_copy(obj: PySetRef, _vm: &mut VirtualMachine) -> PySet { +fn set_copy(obj: PySetRef, _vm: &VirtualMachine) -> PySet { trace!("set.copy called with: {:?}", obj); let elements = obj.elements.borrow().clone(); PySet { @@ -194,7 +194,7 @@ fn set_copy(obj: PySetRef, _vm: &mut VirtualMachine) -> PySet { } } -fn set_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(o, Some(vm.ctx.set_type()))]); let elements = get_elements(o); @@ -214,7 +214,7 @@ fn set_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_str(s)) } -pub fn set_contains(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +pub fn set_contains(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -234,7 +234,7 @@ pub fn set_contains(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_bool(false)) } -fn set_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_eq(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_compare_inner( vm, args, @@ -243,7 +243,7 @@ fn set_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { ) } -fn set_ge(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_ge(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_compare_inner( vm, args, @@ -252,7 +252,7 @@ fn set_ge(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { ) } -fn set_gt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_gt(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_compare_inner( vm, args, @@ -261,7 +261,7 @@ fn set_gt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { ) } -fn set_le(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_le(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_compare_inner( vm, args, @@ -270,7 +270,7 @@ fn set_le(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { ) } -fn set_lt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_lt(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_compare_inner( vm, args, @@ -280,7 +280,7 @@ fn set_lt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } fn set_compare_inner( - vm: &mut VirtualMachine, + vm: &VirtualMachine, args: PyFuncArgs, size_func: &Fn(usize, usize) -> bool, swap: bool, @@ -327,7 +327,7 @@ fn set_compare_inner( Ok(vm.new_bool(true)) } -fn set_union(zelf: PySetRef, other: PySetRef, _vm: &mut VirtualMachine) -> PySet { +fn set_union(zelf: PySetRef, other: PySetRef, _vm: &VirtualMachine) -> PySet { let mut elements = zelf.elements.borrow().clone(); elements.extend(other.elements.borrow().clone()); @@ -336,18 +336,18 @@ fn set_union(zelf: PySetRef, other: PySetRef, _vm: &mut VirtualMachine) -> PySet } } -fn set_intersection(zelf: PySetRef, other: PySetRef, vm: &mut VirtualMachine) -> PyResult { +fn set_intersection(zelf: PySetRef, other: PySetRef, vm: &VirtualMachine) -> PyResult { set_combine_inner(zelf, other, vm, SetCombineOperation::Intersection) } -fn set_difference(zelf: PySetRef, other: PySetRef, vm: &mut VirtualMachine) -> PyResult { +fn set_difference(zelf: PySetRef, other: PySetRef, vm: &VirtualMachine) -> PyResult { set_combine_inner(zelf, other, vm, SetCombineOperation::Difference) } fn set_symmetric_difference( zelf: PySetRef, other: PySetRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let mut elements = HashMap::new(); @@ -378,7 +378,7 @@ enum SetCombineOperation { fn set_combine_inner( zelf: PySetRef, other: PySetRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, op: SetCombineOperation, ) -> PyResult { let mut elements = HashMap::new(); @@ -399,7 +399,7 @@ fn set_combine_inner( }) } -fn set_pop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_pop(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(s, Some(vm.ctx.set_type()))]); match s.payload::() { @@ -414,12 +414,12 @@ fn set_pop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn set_update(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_update(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_ior(vm, args)?; Ok(vm.get_none()) } -fn set_ior(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_ior(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -438,26 +438,26 @@ fn set_ior(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(zelf.clone()) } -fn set_intersection_update(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_intersection_update(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_combine_update_inner(vm, args, SetCombineOperation::Intersection)?; Ok(vm.get_none()) } -fn set_iand(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_iand(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_combine_update_inner(vm, args, SetCombineOperation::Intersection) } -fn set_difference_update(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_difference_update(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_combine_update_inner(vm, args, SetCombineOperation::Difference)?; Ok(vm.get_none()) } -fn set_isub(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_isub(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_combine_update_inner(vm, args, SetCombineOperation::Difference) } fn set_combine_update_inner( - vm: &mut VirtualMachine, + vm: &VirtualMachine, args: PyFuncArgs, op: SetCombineOperation, ) -> PyResult { @@ -486,12 +486,12 @@ fn set_combine_update_inner( Ok(zelf.clone()) } -fn set_symmetric_difference_update(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_symmetric_difference_update(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { set_ixor(vm, args)?; Ok(vm.get_none()) } -fn set_ixor(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn set_ixor(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -518,7 +518,7 @@ fn set_ixor(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(zelf.clone()) } -fn set_iter(zelf: PySetRef, vm: &mut VirtualMachine) -> PyIteratorValue { +fn set_iter(zelf: PySetRef, vm: &VirtualMachine) -> PyIteratorValue { let items = zelf.elements.borrow().values().cloned().collect(); let set_list = vm.ctx.new_list(items); PyIteratorValue { @@ -527,7 +527,7 @@ fn set_iter(zelf: PySetRef, vm: &mut VirtualMachine) -> PyIteratorValue { } } -fn frozenset_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn frozenset_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(o, Some(vm.ctx.frozenset_type()))]); let elements = get_elements(o); diff --git a/vm/src/obj/objslice.rs b/vm/src/obj/objslice.rs index 8d65bc331ef..263490565d6 100644 --- a/vm/src/obj/objslice.rs +++ b/vm/src/obj/objslice.rs @@ -15,12 +15,12 @@ pub struct PySlice { } impl PyValue for PySlice { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.slice_type() } } -fn slice_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn slice_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { no_kwargs!(vm, args); let (cls, start, stop, step): ( &PyObjectRef, @@ -64,7 +64,7 @@ fn slice_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { )) } -fn get_property_value(vm: &mut VirtualMachine, value: &Option) -> PyResult { +fn get_property_value(vm: &VirtualMachine, value: &Option) -> PyResult { if let Some(value) = value { Ok(vm.ctx.new_int(value.clone())) } else { @@ -72,7 +72,7 @@ fn get_property_value(vm: &mut VirtualMachine, value: &Option) -> PyResu } } -fn slice_start(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn slice_start(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(slice, Some(vm.ctx.slice_type()))]); if let Some(PySlice { start, .. }) = &slice.payload() { get_property_value(vm, start) @@ -81,7 +81,7 @@ fn slice_start(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn slice_stop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn slice_stop(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(slice, Some(vm.ctx.slice_type()))]); if let Some(PySlice { stop, .. }) = &slice.payload() { get_property_value(vm, stop) @@ -90,7 +90,7 @@ fn slice_stop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn slice_step(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn slice_step(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(slice, Some(vm.ctx.slice_type()))]); if let Some(PySlice { step, .. }) = &slice.payload() { get_property_value(vm, step) diff --git a/vm/src/obj/objstaticmethod.rs b/vm/src/obj/objstaticmethod.rs index 78307bcc3e8..f8430979da0 100644 --- a/vm/src/obj/objstaticmethod.rs +++ b/vm/src/obj/objstaticmethod.rs @@ -9,7 +9,7 @@ pub struct PyStaticMethod { pub type PyStaticMethodRef = PyRef; impl PyValue for PyStaticMethod { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.staticmethod_type() } } @@ -18,7 +18,7 @@ impl PyStaticMethodRef { fn new( cls: PyClassRef, callable: PyObjectRef, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { PyStaticMethod { callable: callable.clone(), @@ -26,7 +26,7 @@ impl PyStaticMethodRef { .into_ref_with_type(vm, cls) } - fn get(self, _inst: PyObjectRef, _owner: PyObjectRef, _vm: &mut VirtualMachine) -> PyResult { + fn get(self, _inst: PyObjectRef, _owner: PyObjectRef, _vm: &VirtualMachine) -> PyResult { Ok(self.callable.clone()) } } diff --git a/vm/src/obj/objstr.rs b/vm/src/obj/objstr.rs index 51e29768cb9..826396925c7 100644 --- a/vm/src/obj/objstr.rs +++ b/vm/src/obj/objstr.rs @@ -34,13 +34,13 @@ impl fmt::Display for PyString { } impl TryIntoRef for String { - fn try_into_ref(self, vm: &mut VirtualMachine) -> PyResult> { + fn try_into_ref(self, vm: &VirtualMachine) -> PyResult> { Ok(PyString { value: self }.into_ref(vm)) } } impl TryIntoRef for &str { - fn try_into_ref(self, vm: &mut VirtualMachine) -> PyResult> { + fn try_into_ref(self, vm: &VirtualMachine) -> PyResult> { Ok(PyString { value: self.to_string(), } @@ -49,7 +49,7 @@ impl TryIntoRef for &str { } impl PyStringRef { - fn add(self, rhs: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn add(self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&rhs, &vm.ctx.str_type()) { Ok(format!("{}{}", self.value, get_value(&rhs))) } else { @@ -57,7 +57,7 @@ impl PyStringRef { } } - fn eq(self, rhs: PyObjectRef, vm: &mut VirtualMachine) -> bool { + fn eq(self, rhs: PyObjectRef, vm: &VirtualMachine) -> bool { if objtype::isinstance(&rhs, &vm.ctx.str_type()) { self.value == get_value(&rhs) } else { @@ -65,15 +65,15 @@ impl PyStringRef { } } - fn contains(self, needle: PyStringRef, _vm: &mut VirtualMachine) -> bool { + fn contains(self, needle: PyStringRef, _vm: &VirtualMachine) -> bool { self.value.contains(&needle.value) } - fn getitem(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn getitem(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { subscript(vm, &self.value, needle) } - fn gt(self, rhs: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn gt(self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&rhs, &vm.ctx.str_type()) { Ok(self.value > get_value(&rhs)) } else { @@ -81,7 +81,7 @@ impl PyStringRef { } } - fn ge(self, rhs: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn ge(self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&rhs, &vm.ctx.str_type()) { Ok(self.value >= get_value(&rhs)) } else { @@ -89,7 +89,7 @@ impl PyStringRef { } } - fn lt(self, rhs: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn lt(self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&rhs, &vm.ctx.str_type()) { Ok(self.value < get_value(&rhs)) } else { @@ -97,7 +97,7 @@ impl PyStringRef { } } - fn le(self, rhs: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn le(self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&rhs, &vm.ctx.str_type()) { Ok(self.value <= get_value(&rhs)) } else { @@ -105,17 +105,17 @@ impl PyStringRef { } } - fn hash(self, _vm: &mut VirtualMachine) -> usize { + fn hash(self, _vm: &VirtualMachine) -> usize { let mut hasher = std::collections::hash_map::DefaultHasher::new(); self.value.hash(&mut hasher); hasher.finish() as usize } - fn len(self, _vm: &mut VirtualMachine) -> usize { + fn len(self, _vm: &VirtualMachine) -> usize { self.value.chars().count() } - fn mul(self, val: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn mul(self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&val, &vm.ctx.int_type()) { let value = &self.value; let multiplier = objint::get_value(&val).to_i32().unwrap(); @@ -129,11 +129,11 @@ impl PyStringRef { } } - fn str(self, _vm: &mut VirtualMachine) -> PyStringRef { + fn str(self, _vm: &VirtualMachine) -> PyStringRef { self } - fn repr(self, _vm: &mut VirtualMachine) -> String { + fn repr(self, _vm: &VirtualMachine) -> String { let value = &self.value; let quote_char = if count_char(value, '\'') > count_char(value, '"') { '"' @@ -163,20 +163,20 @@ impl PyStringRef { formatted } - fn lower(self, _vm: &mut VirtualMachine) -> String { + fn lower(self, _vm: &VirtualMachine) -> String { self.value.to_lowercase() } // casefold is much more aggressive than lower - fn casefold(self, _vm: &mut VirtualMachine) -> String { + fn casefold(self, _vm: &VirtualMachine) -> String { caseless::default_case_fold_str(&self.value) } - fn upper(self, _vm: &mut VirtualMachine) -> String { + fn upper(self, _vm: &VirtualMachine) -> String { self.value.to_uppercase() } - fn capitalize(self, _vm: &mut VirtualMachine) -> String { + fn capitalize(self, _vm: &VirtualMachine) -> String { let (first_part, lower_str) = self.value.split_at(1); format!("{}{}", first_part.to_uppercase(), lower_str) } @@ -185,7 +185,7 @@ impl PyStringRef { self, pattern: OptionalArg, num: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyObjectRef { let value = &self.value; let pattern = match pattern { @@ -206,7 +206,7 @@ impl PyStringRef { self, pattern: OptionalArg, num: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyObjectRef { let value = &self.value; let pattern = match pattern { @@ -223,15 +223,15 @@ impl PyStringRef { vm.ctx.new_list(elements) } - fn strip(self, _vm: &mut VirtualMachine) -> String { + fn strip(self, _vm: &VirtualMachine) -> String { self.value.trim().to_string() } - fn lstrip(self, _vm: &mut VirtualMachine) -> String { + fn lstrip(self, _vm: &VirtualMachine) -> String { self.value.trim_start().to_string() } - fn rstrip(self, _vm: &mut VirtualMachine) -> String { + fn rstrip(self, _vm: &VirtualMachine) -> String { self.value.trim_end().to_string() } @@ -240,7 +240,7 @@ impl PyStringRef { suffix: PyStringRef, start: OptionalArg, end: OptionalArg, - _vm: &mut VirtualMachine, + _vm: &VirtualMachine, ) -> bool { if let Some((start, end)) = adjust_indices(start, end, self.value.len()) { self.value[start..end].ends_with(&suffix.value) @@ -254,7 +254,7 @@ impl PyStringRef { prefix: PyStringRef, start: OptionalArg, end: OptionalArg, - _vm: &mut VirtualMachine, + _vm: &VirtualMachine, ) -> bool { if let Some((start, end)) = adjust_indices(start, end, self.value.len()) { self.value[start..end].starts_with(&prefix.value) @@ -263,15 +263,15 @@ impl PyStringRef { } } - fn isalnum(self, _vm: &mut VirtualMachine) -> bool { + fn isalnum(self, _vm: &VirtualMachine) -> bool { !self.value.is_empty() && self.value.chars().all(char::is_alphanumeric) } - fn isnumeric(self, _vm: &mut VirtualMachine) -> bool { + fn isnumeric(self, _vm: &VirtualMachine) -> bool { !self.value.is_empty() && self.value.chars().all(char::is_numeric) } - fn isdigit(self, _vm: &mut VirtualMachine) -> bool { + fn isdigit(self, _vm: &VirtualMachine) -> bool { // python's isdigit also checks if exponents are digits, these are the unicodes for exponents let valid_unicodes: [u16; 10] = [ 0x2070, 0x00B9, 0x00B2, 0x00B3, 0x2074, 0x2075, 0x2076, 0x2077, 0x2078, 0x2079, @@ -287,7 +287,7 @@ impl PyStringRef { } } - fn isdecimal(self, _vm: &mut VirtualMachine) -> bool { + fn isdecimal(self, _vm: &VirtualMachine) -> bool { if self.value.is_empty() { false } else { @@ -295,11 +295,11 @@ impl PyStringRef { } } - fn title(self, _vm: &mut VirtualMachine) -> String { + fn title(self, _vm: &VirtualMachine) -> String { make_title(&self.value) } - fn swapcase(self, _vm: &mut VirtualMachine) -> String { + fn swapcase(self, _vm: &VirtualMachine) -> String { let mut swapped_str = String::with_capacity(self.value.len()); for c in self.value.chars() { // to_uppercase returns an iterator, to_ascii_uppercase returns the char @@ -314,7 +314,7 @@ impl PyStringRef { swapped_str } - fn isalpha(self, _vm: &mut VirtualMachine) -> bool { + fn isalpha(self, _vm: &VirtualMachine) -> bool { !self.value.is_empty() && self.value.chars().all(char::is_alphanumeric) } @@ -323,7 +323,7 @@ impl PyStringRef { old: Self, new: Self, num: OptionalArg, - _vm: &mut VirtualMachine, + _vm: &VirtualMachine, ) -> String { match num.into_option() { Some(num) => self.value.replacen(&old.value, &new.value, num), @@ -333,11 +333,11 @@ impl PyStringRef { // cpython's isspace ignores whitespace, including \t and \n, etc, unless the whole string is empty // which is why isspace is using is_ascii_whitespace. Same for isupper & islower - fn isspace(self, _vm: &mut VirtualMachine) -> bool { + fn isspace(self, _vm: &VirtualMachine) -> bool { !self.value.is_empty() && self.value.chars().all(|c| c.is_ascii_whitespace()) } - fn isupper(self, _vm: &mut VirtualMachine) -> bool { + fn isupper(self, _vm: &VirtualMachine) -> bool { !self.value.is_empty() && self .value @@ -346,7 +346,7 @@ impl PyStringRef { .all(char::is_uppercase) } - fn islower(self, _vm: &mut VirtualMachine) -> bool { + fn islower(self, _vm: &VirtualMachine) -> bool { !self.value.is_empty() && self .value @@ -355,12 +355,12 @@ impl PyStringRef { .all(char::is_lowercase) } - fn isascii(self, _vm: &mut VirtualMachine) -> bool { + fn isascii(self, _vm: &VirtualMachine) -> bool { !self.value.is_empty() && self.value.chars().all(|c| c.is_ascii()) } // doesn't implement keep new line delimiter just yet - fn splitlines(self, vm: &mut VirtualMachine) -> PyObjectRef { + fn splitlines(self, vm: &VirtualMachine) -> PyObjectRef { let elements = self .value .split('\n') @@ -369,7 +369,7 @@ impl PyStringRef { vm.ctx.new_list(elements) } - fn join(self, iterable: PyIterable, vm: &mut VirtualMachine) -> PyResult { + fn join(self, iterable: PyIterable, vm: &VirtualMachine) -> PyResult { let mut joined = String::new(); for (idx, elem) in iterable.iter(vm)?.enumerate() { @@ -388,7 +388,7 @@ impl PyStringRef { sub: Self, start: OptionalArg, end: OptionalArg, - _vm: &mut VirtualMachine, + _vm: &VirtualMachine, ) -> isize { let value = &self.value; if let Some((start, end)) = adjust_indices(start, end, value.len()) { @@ -406,7 +406,7 @@ impl PyStringRef { sub: Self, start: OptionalArg, end: OptionalArg, - _vm: &mut VirtualMachine, + _vm: &VirtualMachine, ) -> isize { let value = &self.value; if let Some((start, end)) = adjust_indices(start, end, value.len()) { @@ -424,7 +424,7 @@ impl PyStringRef { sub: Self, start: OptionalArg, end: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let value = &self.value; if let Some((start, end)) = adjust_indices(start, end, value.len()) { @@ -442,7 +442,7 @@ impl PyStringRef { sub: Self, start: OptionalArg, end: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let value = &self.value; if let Some((start, end)) = adjust_indices(start, end, value.len()) { @@ -455,7 +455,7 @@ impl PyStringRef { } } - fn partition(self, sub: PyStringRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn partition(self, sub: PyStringRef, vm: &VirtualMachine) -> PyObjectRef { let value = &self.value; let sub = &sub.value; let mut new_tup = Vec::new(); @@ -473,7 +473,7 @@ impl PyStringRef { vm.ctx.new_tuple(new_tup) } - fn rpartition(self, sub: PyStringRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn rpartition(self, sub: PyStringRef, vm: &VirtualMachine) -> PyObjectRef { let value = &self.value; let sub = &sub.value; let mut new_tup = Vec::new(); @@ -492,7 +492,7 @@ impl PyStringRef { vm.ctx.new_tuple(new_tup) } - fn istitle(self, _vm: &mut VirtualMachine) -> bool { + fn istitle(self, _vm: &VirtualMachine) -> bool { if self.value.is_empty() { false } else { @@ -505,7 +505,7 @@ impl PyStringRef { sub: Self, start: OptionalArg, end: OptionalArg, - _vm: &mut VirtualMachine, + _vm: &VirtualMachine, ) -> usize { let value = &self.value; if let Some((start, end)) = adjust_indices(start, end, value.len()) { @@ -515,7 +515,7 @@ impl PyStringRef { } } - fn zfill(self, len: usize, _vm: &mut VirtualMachine) -> String { + fn zfill(self, len: usize, _vm: &VirtualMachine) -> String { let value = &self.value; if len <= value.len() { value.to_string() @@ -524,7 +524,7 @@ impl PyStringRef { } } - fn get_fill_char<'a>(rep: &'a OptionalArg, vm: &mut VirtualMachine) -> PyResult<&'a str> { + fn get_fill_char<'a>(rep: &'a OptionalArg, vm: &VirtualMachine) -> PyResult<&'a str> { let rep_str = match rep { OptionalArg::Present(ref st) => &st.value, OptionalArg::Missing => " ", @@ -538,34 +538,19 @@ impl PyStringRef { } } - fn ljust( - self, - len: usize, - rep: OptionalArg, - vm: &mut VirtualMachine, - ) -> PyResult { + fn ljust(self, len: usize, rep: OptionalArg, vm: &VirtualMachine) -> PyResult { let value = &self.value; let rep_char = PyStringRef::get_fill_char(&rep, vm)?; Ok(format!("{}{}", value, rep_char.repeat(len))) } - fn rjust( - self, - len: usize, - rep: OptionalArg, - vm: &mut VirtualMachine, - ) -> PyResult { + fn rjust(self, len: usize, rep: OptionalArg, vm: &VirtualMachine) -> PyResult { let value = &self.value; let rep_char = PyStringRef::get_fill_char(&rep, vm)?; Ok(format!("{}{}", rep_char.repeat(len), value)) } - fn center( - self, - len: usize, - rep: OptionalArg, - vm: &mut VirtualMachine, - ) -> PyResult { + fn center(self, len: usize, rep: OptionalArg, vm: &VirtualMachine) -> PyResult { let value = &self.value; let rep_char = PyStringRef::get_fill_char(&rep, vm)?; let left_buff: usize = (len - value.len()) / 2; @@ -578,7 +563,7 @@ impl PyStringRef { )) } - fn expandtabs(self, tab_stop: OptionalArg, _vm: &mut VirtualMachine) -> String { + fn expandtabs(self, tab_stop: OptionalArg, _vm: &VirtualMachine) -> String { let tab_stop = tab_stop.into_option().unwrap_or(8 as usize); let mut expanded_str = String::new(); let mut tab_size = tab_stop; @@ -601,7 +586,7 @@ impl PyStringRef { expanded_str } - fn isidentifier(self, _vm: &mut VirtualMachine) -> bool { + fn isidentifier(self, _vm: &VirtualMachine) -> bool { let value = &self.value; // a string is not an identifier if it has whitespace or starts with a number if !value.chars().any(|c| c.is_ascii_whitespace()) @@ -620,13 +605,13 @@ impl PyStringRef { } impl PyValue for PyString { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.str_type() } } impl IntoPyObject for String { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { Ok(vm.ctx.new_str(self)) } } @@ -713,7 +698,7 @@ fn count_char(s: &str, c: char) -> usize { s.chars().filter(|x| *x == c).count() } -fn str_format(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn str_format(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { if args.args.is_empty() { return Err( vm.new_type_error("descriptor 'format' of 'str' object needs an argument".to_string()) @@ -741,11 +726,7 @@ fn str_format(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn call_object_format( - vm: &mut VirtualMachine, - argument: PyObjectRef, - format_spec: &str, -) -> PyResult { +fn call_object_format(vm: &VirtualMachine, argument: PyObjectRef, format_spec: &str) -> PyResult { let returned_type = vm.ctx.new_str(format_spec.to_string()); let result = vm.call_method(&argument, "__format__", vec![returned_type])?; if !objtype::isinstance(&result, &vm.ctx.str_type()) { @@ -757,7 +738,7 @@ fn call_object_format( } fn perform_format( - vm: &mut VirtualMachine, + vm: &VirtualMachine, format_string: &FormatString, arguments: &PyFuncArgs, ) -> PyResult { @@ -814,7 +795,7 @@ fn perform_format( fn str_new( cls: PyClassRef, object: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { let string = match object { OptionalArg::Present(ref input) => vm.to_str(input)?.into_object(), @@ -890,7 +871,7 @@ fn to_graphemes>(value: S) -> Vec { .collect() } -pub fn subscript(vm: &mut VirtualMachine, value: &str, b: PyObjectRef) -> PyResult { +pub fn subscript(vm: &VirtualMachine, value: &str, b: PyObjectRef) -> PyResult { if objtype::isinstance(&b, &vm.ctx.int_type()) { match objint::get_value(&b).to_i32() { Some(pos) => { diff --git a/vm/src/obj/objsuper.rs b/vm/src/obj/objsuper.rs index 594624213d6..390e5918331 100644 --- a/vm/src/obj/objsuper.rs +++ b/vm/src/obj/objsuper.rs @@ -21,7 +21,7 @@ pub struct PySuper { } impl PyValue for PySuper { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.super_type() } } @@ -56,7 +56,7 @@ pub fn init(context: &PyContext) { ); } -fn super_getattribute(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn super_getattribute(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -81,7 +81,7 @@ fn super_getattribute(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn super_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn super_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { trace!("super.__new__ {:?}", args.args); arg_check!( vm, diff --git a/vm/src/obj/objtuple.rs b/vm/src/obj/objtuple.rs index d1986bce0d9..7438e1c90a6 100644 --- a/vm/src/obj/objtuple.rs +++ b/vm/src/obj/objtuple.rs @@ -38,7 +38,7 @@ impl From> for PyTuple { } impl PyValue for PyTuple { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.tuple_type() } } @@ -46,7 +46,7 @@ impl PyValue for PyTuple { pub type PyTupleRef = PyRef; impl PyTupleRef { - fn lt(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn lt(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.tuple_type()) { let zelf = self.elements.borrow(); let other = get_elements(&other); @@ -57,7 +57,7 @@ impl PyTupleRef { } } - fn gt(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn gt(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.tuple_type()) { let zelf = self.elements.borrow(); let other = get_elements(&other); @@ -68,7 +68,7 @@ impl PyTupleRef { } } - fn ge(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn ge(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.tuple_type()) { let zelf = self.elements.borrow(); let other = get_elements(&other); @@ -79,7 +79,7 @@ impl PyTupleRef { } } - fn le(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn le(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.tuple_type()) { let zelf = self.elements.borrow(); let other = get_elements(&other); @@ -90,7 +90,7 @@ impl PyTupleRef { } } - fn add(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn add(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.tuple_type()) { let e1 = self.elements.borrow(); let e2 = get_elements(&other); @@ -101,7 +101,7 @@ impl PyTupleRef { } } - fn count(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn count(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { let mut count: usize = 0; for element in self.elements.borrow().iter() { if element.is(&needle) { @@ -116,7 +116,7 @@ impl PyTupleRef { Ok(count) } - fn eq(self, other: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn eq(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if objtype::isinstance(&other, &vm.ctx.tuple_type()) { let zelf = &self.elements.borrow(); let other = get_elements(&other); @@ -127,7 +127,7 @@ impl PyTupleRef { } } - fn hash(self, vm: &mut VirtualMachine) -> PyResult { + fn hash(self, vm: &VirtualMachine) -> PyResult { let mut hasher = std::collections::hash_map::DefaultHasher::new(); for element in self.elements.borrow().iter() { let hash_result = vm.call_method(element, "__hash__", vec![])?; @@ -137,18 +137,18 @@ impl PyTupleRef { Ok(hasher.finish()) } - fn iter(self, _vm: &mut VirtualMachine) -> PyIteratorValue { + fn iter(self, _vm: &VirtualMachine) -> PyIteratorValue { PyIteratorValue { position: Cell::new(0), iterated_obj: self.into_object(), } } - fn len(self, _vm: &mut VirtualMachine) -> usize { + fn len(self, _vm: &VirtualMachine) -> usize { self.elements.borrow().len() } - fn repr(self, vm: &mut VirtualMachine) -> PyResult { + fn repr(self, vm: &VirtualMachine) -> PyResult { let s = if let Some(_guard) = ReprGuard::enter(self.as_object()) { let mut str_parts = vec![]; for elem in self.elements.borrow().iter() { @@ -167,12 +167,12 @@ impl PyTupleRef { Ok(s) } - fn mul(self, counter: isize, vm: &mut VirtualMachine) -> PyObjectRef { + fn mul(self, counter: isize, vm: &VirtualMachine) -> PyObjectRef { let new_elements = seq_mul(&self.elements.borrow(), counter); vm.ctx.new_tuple(new_elements) } - fn getitem(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn getitem(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { get_item( vm, self.as_object(), @@ -181,7 +181,7 @@ impl PyTupleRef { ) } - fn index(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn index(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { for (index, element) in self.elements.borrow().iter().enumerate() { if element.is(&needle) { return Ok(index); @@ -194,7 +194,7 @@ impl PyTupleRef { Err(vm.new_value_error("tuple.index(x): x not in tuple".to_string())) } - fn contains(self, needle: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn contains(self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { for element in self.elements.borrow().iter() { if element.is(&needle) { return Ok(true); @@ -211,7 +211,7 @@ impl PyTupleRef { fn tuple_new( cls: PyClassRef, iterable: OptionalArg, - vm: &mut VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { if !objtype::issubclass(cls.as_object(), &vm.ctx.tuple_type()) { return Err(vm.new_type_error(format!("{} is not a subtype of tuple", cls))); diff --git a/vm/src/obj/objtype.rs b/vm/src/obj/objtype.rs index 78c946dbc15..d5648f07be1 100644 --- a/vm/src/obj/objtype.rs +++ b/vm/src/obj/objtype.rs @@ -30,7 +30,7 @@ impl fmt::Display for PyClass { pub type PyClassRef = PyRef; impl PyValue for PyClass { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.type_type() } } @@ -81,17 +81,17 @@ impl PyClassRef { } } - fn mro(self, _vm: &mut VirtualMachine) -> PyTuple { + fn mro(self, _vm: &VirtualMachine) -> PyTuple { let elements: Vec = _mro(&self).iter().map(|x| x.as_object().clone()).collect(); PyTuple::from(elements) } - fn set_mro(self, _value: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn set_mro(self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult { Err(vm.new_attribute_error("read-only attribute".to_string())) } - fn dir(self, vm: &mut VirtualMachine) -> PyList { + fn dir(self, vm: &VirtualMachine) -> PyList { let attributes = get_attributes(self); let attributes: Vec = attributes .keys() @@ -100,19 +100,19 @@ impl PyClassRef { PyList::from(attributes) } - fn instance_check(self, obj: PyObjectRef, _vm: &mut VirtualMachine) -> bool { + fn instance_check(self, obj: PyObjectRef, _vm: &VirtualMachine) -> bool { isinstance(&obj, self.as_object()) } - fn subclass_check(self, subclass: PyObjectRef, _vm: &mut VirtualMachine) -> bool { + fn subclass_check(self, subclass: PyObjectRef, _vm: &VirtualMachine) -> bool { issubclass(&subclass, self.as_object()) } - fn repr(self, _vm: &mut VirtualMachine) -> String { + fn repr(self, _vm: &VirtualMachine) -> String { format!("", self.name) } - fn prepare(_name: PyStringRef, _bases: PyObjectRef, vm: &mut VirtualMachine) -> PyObjectRef { + fn prepare(_name: PyStringRef, _bases: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { vm.new_dict() } } @@ -170,7 +170,7 @@ pub fn get_type_name(typ: &PyObjectRef) -> String { } } -pub fn type_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +pub fn type_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { debug!("type.__new__ {:?}", args); if args.args.len() == 2 { arg_check!( @@ -197,7 +197,7 @@ pub fn type_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } pub fn type_new_class( - vm: &mut VirtualMachine, + vm: &VirtualMachine, typ: &PyObjectRef, name: &PyObjectRef, bases: &PyObjectRef, @@ -218,7 +218,7 @@ pub fn type_new_class( ) } -pub fn type_call(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult { +pub fn type_call(vm: &VirtualMachine, mut args: PyFuncArgs) -> PyResult { debug!("type_call: {:?}", args); let cls = args.shift(); let new = cls.get_attr("__new__").unwrap(); @@ -234,7 +234,7 @@ pub fn type_call(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult { Ok(obj) } -pub fn type_getattribute(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +pub fn type_getattribute(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/obj/objweakref.rs b/vm/src/obj/objweakref.rs index 69d7027370a..e6dd1e1e692 100644 --- a/vm/src/obj/objweakref.rs +++ b/vm/src/obj/objweakref.rs @@ -23,7 +23,7 @@ impl PyWeak { } impl PyValue for PyWeak { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.weakref_type() } } @@ -32,11 +32,11 @@ pub type PyWeakRef = PyRef; impl PyWeakRef { // TODO callbacks - fn create(cls: PyClassRef, referent: PyObjectRef, vm: &mut VirtualMachine) -> PyResult { + fn create(cls: PyClassRef, referent: PyObjectRef, vm: &VirtualMachine) -> PyResult { PyWeak::downgrade(referent).into_ref_with_type(vm, cls) } - fn call(self, vm: &mut VirtualMachine) -> PyObjectRef { + fn call(self, vm: &VirtualMachine) -> PyObjectRef { self.referent.upgrade().unwrap_or_else(|| vm.get_none()) } } diff --git a/vm/src/obj/objzip.rs b/vm/src/obj/objzip.rs index 8250337e0a5..0a3c5453a40 100644 --- a/vm/src/obj/objzip.rs +++ b/vm/src/obj/objzip.rs @@ -10,12 +10,12 @@ pub struct PyZip { } impl PyValue for PyZip { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.zip_type() } } -fn zip_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn zip_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { no_kwargs!(vm, args); let cls = &args.args[0]; let iterables = &args.args[1..]; @@ -26,7 +26,7 @@ fn zip_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(PyObject::new(PyZip { iterators }, cls.clone())) } -fn zip_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn zip_next(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zip, Some(vm.ctx.zip_type()))]); if let Some(PyZip { ref iterators }) = zip.payload() { diff --git a/vm/src/pyobject.rs b/vm/src/pyobject.rs index 5780cf62012..d6e84b653b5 100644 --- a/vm/src/pyobject.rs +++ b/vm/src/pyobject.rs @@ -165,7 +165,7 @@ pub fn create_type(name: &str, type_type: &PyObjectRef, base: &PyObjectRef) -> P pub struct PyNotImplemented; impl PyValue for PyNotImplemented { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.not_implemented().typ() } } @@ -174,7 +174,7 @@ impl PyValue for PyNotImplemented { pub struct PyEllipsis; impl PyValue for PyEllipsis { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.ellipsis_type.clone() } } @@ -660,7 +660,7 @@ impl PyContext { }; } - pub fn unwrap_constant(&mut self, value: &bytecode::Constant) -> PyObjectRef { + pub fn unwrap_constant(&self, value: &bytecode::Constant) -> PyObjectRef { match *value { bytecode::Constant::Integer { ref value } => self.new_int(value.clone()), bytecode::Constant::Float { ref value } => self.new_float(*value), @@ -744,7 +744,7 @@ impl TryFromObject for PyRef where T: PyValue, { - fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { if objtype::isinstance(&obj, &T::class(vm)) { Ok(PyRef { obj, @@ -763,7 +763,7 @@ where } impl IntoPyObject for PyRef { - fn into_pyobject(self, _vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, _vm: &VirtualMachine) -> PyResult { Ok(self.obj) } } @@ -976,7 +976,7 @@ impl PyIterable { /// /// This operation may fail if an exception is raised while invoking the /// `__iter__` method of the iterable object. - pub fn iter<'a>(&self, vm: &'a mut VirtualMachine) -> PyResult> { + pub fn iter<'a>(&self, vm: &'a VirtualMachine) -> PyResult> { let iter_obj = vm.invoke( self.method.clone(), PyFuncArgs { @@ -994,7 +994,7 @@ impl PyIterable { } pub struct PyIterator<'a, T> { - vm: &'a mut VirtualMachine, + vm: &'a VirtualMachine, obj: PyObjectRef, _item: std::marker::PhantomData, } @@ -1024,7 +1024,7 @@ impl TryFromObject for PyIterable where T: TryFromObject, { - fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { Ok(PyIterable { method: vm.get_method(obj, "__iter__")?, _item: std::marker::PhantomData, @@ -1033,13 +1033,13 @@ where } impl TryFromObject for PyObjectRef { - fn try_from_object(_vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult { + fn try_from_object(_vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { Ok(obj) } } impl TryFromObject for Option { - fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { if vm.get_none().is(&obj) { Ok(None) } else { @@ -1051,11 +1051,11 @@ impl TryFromObject for Option { /// Allows coercion of a types into PyRefs, so that we can write functions that can take /// refs, pyobject refs or basic types. pub trait TryIntoRef { - fn try_into_ref(self, vm: &mut VirtualMachine) -> PyResult>; + fn try_into_ref(self, vm: &VirtualMachine) -> PyResult>; } impl TryIntoRef for PyRef { - fn try_into_ref(self, _vm: &mut VirtualMachine) -> PyResult> { + fn try_into_ref(self, _vm: &VirtualMachine) -> PyResult> { Ok(self) } } @@ -1064,7 +1064,7 @@ impl TryIntoRef for PyObjectRef where T: PyValue, { - fn try_into_ref(self, vm: &mut VirtualMachine) -> PyResult> { + fn try_into_ref(self, vm: &VirtualMachine) -> PyResult> { TryFromObject::try_from_object(vm, self) } } @@ -1075,7 +1075,7 @@ where /// so can be accepted as a argument to a built-in function. pub trait TryFromObject: Sized { /// Attempt to convert a Python object to a value of this type. - fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult; + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult; } /// Implemented by any type that can be returned from a built-in Python function. @@ -1084,11 +1084,11 @@ pub trait TryFromObject: Sized { /// and should be implemented by many primitive Rust types, allowing a built-in /// function to simply return a `bool` or a `usize` for example. pub trait IntoPyObject { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult; + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult; } impl IntoPyObject for PyObjectRef { - fn into_pyobject(self, _vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, _vm: &VirtualMachine) -> PyResult { Ok(self) } } @@ -1097,7 +1097,7 @@ impl IntoPyObject for PyResult where T: IntoPyObject, { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { self.and_then(|res| T::into_pyobject(res, vm)) } } @@ -1108,7 +1108,7 @@ impl IntoPyObject for T where T: PyValue + Sized, { - fn into_pyobject(self, vm: &mut VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { Ok(PyObject::new(self, T::class(vm))) } } @@ -1122,7 +1122,7 @@ pub struct PyIteratorValue { } impl PyValue for PyIteratorValue { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.iter_type() } } @@ -1163,16 +1163,16 @@ impl PyObject { } pub trait PyValue: fmt::Debug + Sized + 'static { - fn class(vm: &mut VirtualMachine) -> PyObjectRef; + fn class(vm: &VirtualMachine) -> PyObjectRef; - fn into_ref(self, vm: &mut VirtualMachine) -> PyRef { + fn into_ref(self, vm: &VirtualMachine) -> PyRef { PyRef { obj: PyObject::new(self, Self::class(vm)), _payload: PhantomData, } } - fn into_ref_with_type(self, vm: &mut VirtualMachine, cls: PyClassRef) -> PyResult> { + fn into_ref_with_type(self, vm: &VirtualMachine, cls: PyClassRef) -> PyResult> { let class = Self::class(vm); if objtype::issubclass(&cls.obj, &class) { Ok(PyRef { diff --git a/vm/src/stdlib/ast.rs b/vm/src/stdlib/ast.rs index c3c7c3903ac..a3010a5199d 100644 --- a/vm/src/stdlib/ast.rs +++ b/vm/src/stdlib/ast.rs @@ -612,7 +612,7 @@ fn string_to_ast(ctx: &PyContext, string: &ast::StringGroup) -> PyObjectRef { } } -fn ast_parse(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn ast_parse(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(source, Some(vm.ctx.str_type()))]); let source_string = objstr::get_value(source); diff --git a/vm/src/stdlib/dis.rs b/vm/src/stdlib/dis.rs index f583cc5a8df..04209d8b3ba 100644 --- a/vm/src/stdlib/dis.rs +++ b/vm/src/stdlib/dis.rs @@ -3,7 +3,7 @@ use crate::obj::objcode; use crate::pyobject::{PyContext, PyObjectRef, PyResult, TypeProtocol}; use crate::vm::VirtualMachine; -fn dis_dis(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn dis_dis(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(obj, None)]); // Method or function: @@ -14,7 +14,7 @@ fn dis_dis(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { dis_disassemble(vm, PyFuncArgs::new(vec![obj.clone()], vec![])) } -fn dis_disassemble(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn dis_disassemble(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(co, Some(vm.ctx.code_type()))]); let code = objcode::get_value(co); diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index 5ba8197fbf5..1ce303c5f36 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -42,23 +42,23 @@ struct PyStringIO { type PyStringIORef = PyRef; impl PyValue for PyStringIO { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.class("io", "StringIO") } } impl PyStringIORef { - fn write(self, data: objstr::PyStringRef, _vm: &mut VirtualMachine) { + fn write(self, data: objstr::PyStringRef, _vm: &VirtualMachine) { let data = data.value.clone(); self.data.borrow_mut().push_str(&data); } - fn getvalue(self, _vm: &mut VirtualMachine) -> String { + fn getvalue(self, _vm: &VirtualMachine) -> String { self.data.borrow().clone() } } -fn string_io_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn string_io_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(cls, None)]); Ok(PyObject::new( @@ -69,23 +69,23 @@ fn string_io_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { )) } -fn bytes_io_init(vm: &mut VirtualMachine, _args: PyFuncArgs) -> PyResult { +fn bytes_io_init(vm: &VirtualMachine, _args: PyFuncArgs) -> PyResult { // TODO Ok(vm.get_none()) } -fn bytes_io_getvalue(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn bytes_io_getvalue(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args); // TODO Ok(vm.get_none()) } -fn io_base_cm_enter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn io_base_cm_enter(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(instance, None)]); Ok(instance.clone()) } -fn io_base_cm_exit(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn io_base_cm_exit(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -100,13 +100,13 @@ fn io_base_cm_exit(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } -fn buffered_io_base_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn buffered_io_base_init(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(buffered, None), (raw, None)]); vm.ctx.set_attr(&buffered, "raw", raw.clone()); Ok(vm.get_none()) } -fn buffered_reader_read(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn buffered_reader_read(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(buffered, None)]); let buff_size = 8 * 1024; let buffer = vm.ctx.new_bytearray(vec![0; buff_size]); @@ -136,7 +136,7 @@ fn buffered_reader_read(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bytes(result)) } -fn file_io_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn file_io_init(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -162,7 +162,7 @@ fn file_io_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn file_io_read(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn file_io_read(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(file_io, None)]); let py_name = vm.get_attribute(file_io.clone(), "name")?; let f = match File::open(objstr::get_value(&py_name)) { @@ -186,7 +186,7 @@ fn file_io_read(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bytes(bytes)) } -fn file_io_readinto(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn file_io_readinto(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(file_io, None), (obj, None)]); if !obj.readonly() { @@ -222,7 +222,7 @@ fn file_io_readinto(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } -fn file_io_write(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn file_io_write(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -256,7 +256,7 @@ fn file_io_write(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn buffered_writer_write(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn buffered_writer_write(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -269,7 +269,7 @@ fn buffered_writer_write(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult vm.call_method(&raw, "write", vec![obj.clone()]) } -fn text_io_wrapper_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn text_io_wrapper_init(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -280,7 +280,7 @@ fn text_io_wrapper_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } -fn text_io_base_read(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn text_io_base_read(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(text_io_base, None)]); let raw = vm.ctx.get_attr(&text_io_base, "buffer").unwrap(); @@ -296,7 +296,7 @@ fn text_io_base_read(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -pub fn io_open(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +pub fn io_open(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/stdlib/json.rs b/vm/src/stdlib/json.rs index 81fb364d48d..da373a955c5 100644 --- a/vm/src/stdlib/json.rs +++ b/vm/src/stdlib/json.rs @@ -188,12 +188,12 @@ impl<'de> Visitor<'de> for PyObjectDeserializer<'de> { } } -pub fn ser_pyobject(vm: &mut VirtualMachine, obj: &PyObjectRef) -> PyResult { +pub fn ser_pyobject(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult { let serializer = PyObjectSerializer { pyobject: obj, vm }; serde_json::to_string(&serializer).map_err(|err| vm.new_type_error(err.to_string())) } -pub fn de_pyobject(vm: &mut VirtualMachine, s: &str) -> PyResult { +pub fn de_pyobject(vm: &VirtualMachine, s: &str) -> PyResult { let de = PyObjectDeserializer { vm }; // TODO: Support deserializing string sub-classes de.deserialize(&mut serde_json::Deserializer::from_str(s)) @@ -214,7 +214,7 @@ pub fn de_pyobject(vm: &mut VirtualMachine, s: &str) -> PyResult { } /// Implement json.dumps -fn json_dumps(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn json_dumps(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { // TODO: Implement non-trivial serialisation case arg_check!(vm, args, required = [(obj, None)]); let string = ser_pyobject(vm, obj)?; @@ -222,7 +222,7 @@ fn json_dumps(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } /// Implement json.loads -fn json_loads(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn json_loads(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { // TODO: Implement non-trivial deserialization case arg_check!(vm, args, required = [(string, Some(vm.ctx.str_type()))]); diff --git a/vm/src/stdlib/keyword.rs b/vm/src/stdlib/keyword.rs index ff192cffb6d..fe27399c550 100644 --- a/vm/src/stdlib/keyword.rs +++ b/vm/src/stdlib/keyword.rs @@ -9,7 +9,7 @@ use crate::obj::objstr; use crate::pyobject::{PyContext, PyObjectRef, PyResult, TypeProtocol}; use crate::vm::VirtualMachine; -fn keyword_iskeyword(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn keyword_iskeyword(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(s, Some(vm.ctx.str_type()))]); let s = objstr::get_value(s); let keywords = lexer::get_keywords(); diff --git a/vm/src/stdlib/math.rs b/vm/src/stdlib/math.rs index a8f035625b3..5af599cb7d6 100644 --- a/vm/src/stdlib/math.rs +++ b/vm/src/stdlib/math.rs @@ -14,7 +14,7 @@ use crate::vm::VirtualMachine; // Helper macro: macro_rules! make_math_func { ( $fname:ident, $fun:ident ) => { - fn $fname(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { + fn $fname(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let value = objfloat::make_float(vm, value)?; let value = value.$fun(); @@ -27,19 +27,19 @@ macro_rules! make_math_func { // Number theory functions: make_math_func!(math_fabs, abs); -fn math_isfinite(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_isfinite(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let value = objfloat::make_float(vm, value)?.is_finite(); Ok(vm.ctx.new_bool(value)) } -fn math_isinf(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_isinf(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let value = objfloat::make_float(vm, value)?.is_infinite(); Ok(vm.ctx.new_bool(value)) } -fn math_isnan(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_isnan(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let value = objfloat::make_float(vm, value)?.is_nan(); Ok(vm.ctx.new_bool(value)) @@ -49,7 +49,7 @@ fn math_isnan(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { make_math_func!(math_exp, exp); make_math_func!(math_expm1, exp_m1); -fn math_log(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_log(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(x, None)], optional = [(base, None)]); let x = objfloat::make_float(vm, x)?; match base { @@ -61,7 +61,7 @@ fn math_log(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn math_log1p(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_log1p(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(x, None)]); let x = objfloat::make_float(vm, x)?; Ok(vm.ctx.new_float((x + 1.0).ln())) @@ -70,7 +70,7 @@ fn math_log1p(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { make_math_func!(math_log2, log2); make_math_func!(math_log10, log10); -fn math_pow(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_pow(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(x, None), (y, None)]); let x = objfloat::make_float(vm, x)?; let y = objfloat::make_float(vm, y)?; @@ -84,7 +84,7 @@ make_math_func!(math_acos, acos); make_math_func!(math_asin, asin); make_math_func!(math_atan, atan); -fn math_atan2(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_atan2(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(y, None), (x, None)]); let y = objfloat::make_float(vm, y)?; let x = objfloat::make_float(vm, x)?; @@ -93,7 +93,7 @@ fn math_atan2(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { make_math_func!(math_cos, cos); -fn math_hypot(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_hypot(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(x, None), (y, None)]); let x = objfloat::make_float(vm, x)?; let y = objfloat::make_float(vm, y)?; @@ -103,13 +103,13 @@ fn math_hypot(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { make_math_func!(math_sin, sin); make_math_func!(math_tan, tan); -fn math_degrees(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_degrees(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let x = objfloat::make_float(vm, value)?; Ok(vm.ctx.new_float(x * (180.0 / std::f64::consts::PI))) } -fn math_radians(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_radians(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let x = objfloat::make_float(vm, value)?; Ok(vm.ctx.new_float(x * (std::f64::consts::PI / 180.0))) @@ -124,7 +124,7 @@ make_math_func!(math_sinh, sinh); make_math_func!(math_tanh, tanh); // Special functions: -fn math_erf(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_erf(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let x = objfloat::make_float(vm, value)?; @@ -135,7 +135,7 @@ fn math_erf(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn math_erfc(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_erfc(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let x = objfloat::make_float(vm, value)?; @@ -146,7 +146,7 @@ fn math_erfc(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn math_gamma(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_gamma(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let x = objfloat::make_float(vm, value)?; @@ -159,7 +159,7 @@ fn math_gamma(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn math_lgamma(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn math_lgamma(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(value, None)]); let x = objfloat::make_float(vm, value)?; diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index 0bb616ff018..42b4160ca8d 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -50,7 +50,7 @@ pub fn raw_file_number(handle: File) -> i64 { unimplemented!(); } -pub fn os_close(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +pub fn os_close(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(fileno, Some(vm.ctx.int_type()))]); let raw_fileno = objint::get_value(&fileno); @@ -63,7 +63,7 @@ pub fn os_close(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } -pub fn os_open(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +pub fn os_open(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -96,7 +96,7 @@ pub fn os_open(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_int(raw_file_number(handle))) } -fn os_error(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn os_error(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/stdlib/platform.rs b/vm/src/stdlib/platform.rs index f22b8be0e2c..a87383a723b 100644 --- a/vm/src/stdlib/platform.rs +++ b/vm/src/stdlib/platform.rs @@ -10,18 +10,18 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef { }) } -fn platform_python_implementation(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn platform_python_implementation(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args); Ok(vm.new_str("RustPython".to_string())) } -fn platform_python_version(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn platform_python_version(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args); // TODO: fetch version from somewhere. Ok(vm.new_str("4.0.0".to_string())) } -fn platform_python_compiler(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn platform_python_compiler(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args); let version = rustc_version_runtime::version_meta(); Ok(vm.new_str(format!("rustc {}", version.semver))) diff --git a/vm/src/stdlib/pystruct.rs b/vm/src/stdlib/pystruct.rs index 5da654b691c..9dadc520a9d 100644 --- a/vm/src/stdlib/pystruct.rs +++ b/vm/src/stdlib/pystruct.rs @@ -43,23 +43,23 @@ fn parse_format_string(fmt: String) -> Vec { codes } -fn get_int(vm: &mut VirtualMachine, arg: &PyObjectRef) -> PyResult { +fn get_int(vm: &VirtualMachine, arg: &PyObjectRef) -> PyResult { objint::to_int(vm, arg, 10) } -fn pack_i8(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_i8(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { let v = get_int(vm, arg)?.to_i8().unwrap(); data.write_i8(v).unwrap(); Ok(()) } -fn pack_u8(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_u8(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { let v = get_int(vm, arg)?.to_u8().unwrap(); data.write_u8(v).unwrap(); Ok(()) } -fn pack_bool(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_bool(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { if objtype::isinstance(&arg, &vm.ctx.bool_type()) { let v = if objbool::get_value(arg) { 1 } else { 0 }; data.write_u8(v).unwrap(); @@ -69,43 +69,43 @@ fn pack_bool(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> Py } } -fn pack_i16(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_i16(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { let v = get_int(vm, arg)?.to_i16().unwrap(); data.write_i16::(v).unwrap(); Ok(()) } -fn pack_u16(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_u16(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { let v = get_int(vm, arg)?.to_u16().unwrap(); data.write_u16::(v).unwrap(); Ok(()) } -fn pack_i32(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_i32(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { let v = get_int(vm, arg)?.to_i32().unwrap(); data.write_i32::(v).unwrap(); Ok(()) } -fn pack_u32(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_u32(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { let v = get_int(vm, arg)?.to_u32().unwrap(); data.write_u32::(v).unwrap(); Ok(()) } -fn pack_i64(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_i64(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { let v = get_int(vm, arg)?.to_i64().unwrap(); data.write_i64::(v).unwrap(); Ok(()) } -fn pack_u64(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_u64(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { let v = get_int(vm, arg)?.to_u64().unwrap(); data.write_u64::(v).unwrap(); Ok(()) } -fn pack_f32(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_f32(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { if objtype::isinstance(&arg, &vm.ctx.float_type()) { let v = objfloat::get_value(arg) as f32; data.write_f32::(v).unwrap(); @@ -115,7 +115,7 @@ fn pack_f32(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyR } } -fn pack_f64(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { +fn pack_f64(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyResult<()> { if objtype::isinstance(&arg, &vm.ctx.float_type()) { let v = objfloat::get_value(arg) as f64; data.write_f64::(v).unwrap(); @@ -125,7 +125,7 @@ fn pack_f64(vm: &mut VirtualMachine, arg: &PyObjectRef, data: &mut Write) -> PyR } } -fn struct_pack(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn struct_pack(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { if args.args.is_empty() { Err(vm.new_type_error(format!( "Expected at least 1 argument (got: {})", @@ -178,84 +178,84 @@ fn struct_pack(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn unpack_i8(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_i8(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_i8() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_int(v)), } } -fn unpack_u8(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_u8(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_u8() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_int(v)), } } -fn unpack_bool(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_bool(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_u8() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_bool(v > 0)), } } -fn unpack_i16(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_i16(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_i16::() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_int(v)), } } -fn unpack_u16(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_u16(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_u16::() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_int(v)), } } -fn unpack_i32(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_i32(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_i32::() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_int(v)), } } -fn unpack_u32(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_u32(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_u32::() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_int(v)), } } -fn unpack_i64(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_i64(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_i64::() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_int(v)), } } -fn unpack_u64(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_u64(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_u64::() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_int(v)), } } -fn unpack_f32(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_f32(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_f32::() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_float(f64::from(v))), } } -fn unpack_f64(vm: &mut VirtualMachine, rdr: &mut Read) -> PyResult { +fn unpack_f64(vm: &VirtualMachine, rdr: &mut Read) -> PyResult { match rdr.read_f64::() { Err(err) => panic!("Error in reading {:?}", err), Ok(v) => Ok(vm.ctx.new_float(v)), } } -fn struct_unpack(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn struct_unpack(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/stdlib/random.rs b/vm/src/stdlib/random.rs index 2ad1e51c0b7..82c1f410c34 100644 --- a/vm/src/stdlib/random.rs +++ b/vm/src/stdlib/random.rs @@ -16,12 +16,12 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef { }) } -fn random_gauss(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn random_gauss(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { // TODO: is this the same? random_normalvariate(vm, args) } -fn random_normalvariate(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn random_normalvariate(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -38,7 +38,7 @@ fn random_normalvariate(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(py_value) } -fn random_random(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn random_random(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args); let value = rand::random::(); let py_value = vm.ctx.new_float(value); @@ -47,7 +47,7 @@ fn random_random(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { /* * TODO: enable this function: -fn random_weibullvariate(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn random_weibullvariate(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(alpha, Some(vm.ctx.float_type())), (beta, Some(vm.ctx.float_type()))]); let alpha = objfloat::get_value(alpha); let beta = objfloat::get_value(beta); diff --git a/vm/src/stdlib/re.rs b/vm/src/stdlib/re.rs index 8fc7e359edb..863e24c4061 100644 --- a/vm/src/stdlib/re.rs +++ b/vm/src/stdlib/re.rs @@ -16,7 +16,7 @@ use crate::pyobject::{PyContext, PyObject, PyObjectRef, PyResult, PyValue, TypeP use crate::vm::VirtualMachine; impl PyValue for Regex { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.class("re", "Pattern") } } @@ -45,7 +45,7 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef { /// Implement re.match /// See also: /// https://docs.python.org/3/library/re.html#re.match -fn re_match(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn re_match(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -63,7 +63,7 @@ fn re_match(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { /// Implement re.search /// See also: /// https://docs.python.org/3/library/re.html#re.search -fn re_search(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn re_search(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -80,19 +80,19 @@ fn re_search(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { do_search(vm, ®ex, search_text) } -fn do_match(vm: &mut VirtualMachine, regex: &Regex, search_text: String) -> PyResult { +fn do_match(vm: &VirtualMachine, regex: &Regex, search_text: String) -> PyResult { // TODO: implement match! do_search(vm, regex, search_text) } -fn do_search(vm: &mut VirtualMachine, regex: &Regex, search_text: String) -> PyResult { +fn do_search(vm: &VirtualMachine, regex: &Regex, search_text: String) -> PyResult { match regex.find(&search_text) { None => Ok(vm.get_none()), Some(result) => create_match(vm, &result), } } -fn make_regex(vm: &mut VirtualMachine, pattern: &PyObjectRef) -> PyResult { +fn make_regex(vm: &VirtualMachine, pattern: &PyObjectRef) -> PyResult { let pattern_str = objstr::get_value(pattern); match Regex::new(&pattern_str) { @@ -109,13 +109,13 @@ struct PyMatch { } impl PyValue for PyMatch { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.class("re", "Match") } } /// Take a found regular expression and convert it to proper match object. -fn create_match(vm: &mut VirtualMachine, match_value: &Match) -> PyResult { +fn create_match(vm: &VirtualMachine, match_value: &Match) -> PyResult { // Return match object: // TODO: implement match object // TODO: how to refer to match object defined in this @@ -136,7 +136,7 @@ fn create_match(vm: &mut VirtualMachine, match_value: &Match) -> PyResult { /// Compile a regular expression into a Pattern object. /// See also: /// https://docs.python.org/3/library/re.html#re.compile -fn re_compile(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn re_compile(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -151,7 +151,7 @@ fn re_compile(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(PyObject::new(regex, pattern_class.clone())) } -fn pattern_match(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn pattern_match(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -163,7 +163,7 @@ fn pattern_match(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { do_match(vm, ®ex, search_text) } -fn pattern_search(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn pattern_search(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -177,14 +177,14 @@ fn pattern_search(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { /// Returns start of match /// see: https://docs.python.org/3/library/re.html#re.Match.start -fn match_start(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn match_start(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, None)]); // TODO: implement groups let m = get_match(zelf); Ok(vm.new_int(m.start)) } -fn match_end(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn match_end(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, None)]); // TODO: implement groups let m = get_match(zelf); diff --git a/vm/src/stdlib/socket.rs b/vm/src/stdlib/socket.rs index f09a52f5528..4e75cfa417b 100644 --- a/vm/src/stdlib/socket.rs +++ b/vm/src/stdlib/socket.rs @@ -23,7 +23,7 @@ enum AddressFamily { } impl AddressFamily { - fn from_i32(vm: &mut VirtualMachine, value: i32) -> Result { + fn from_i32(vm: &VirtualMachine, value: i32) -> Result { match value { 1 => Ok(AddressFamily::Unix), 2 => Ok(AddressFamily::Inet), @@ -40,7 +40,7 @@ enum SocketKind { } impl SocketKind { - fn from_i32(vm: &mut VirtualMachine, value: i32) -> Result { + fn from_i32(vm: &VirtualMachine, value: i32) -> Result { match value { 1 => Ok(SocketKind::Stream), 2 => Ok(SocketKind::Dgram), @@ -118,7 +118,7 @@ pub struct Socket { } impl PyValue for Socket { - fn class(_vm: &mut VirtualMachine) -> PyObjectRef { + fn class(_vm: &VirtualMachine) -> PyObjectRef { // TODO unimplemented!() } @@ -138,7 +138,7 @@ fn get_socket<'a>(obj: &'a PyObjectRef) -> impl Deref + 'a { obj.payload::().unwrap() } -fn socket_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -159,7 +159,7 @@ fn socket_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { )) } -fn socket_connect(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_connect(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -194,7 +194,7 @@ fn socket_connect(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn socket_bind(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_bind(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -229,10 +229,7 @@ fn socket_bind(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn get_address_string( - vm: &mut VirtualMachine, - address: &PyObjectRef, -) -> Result { +fn get_address_string(vm: &VirtualMachine, address: &PyObjectRef) -> Result { let args = PyFuncArgs { args: get_elements(address).to_vec(), kwargs: vec![], @@ -253,7 +250,7 @@ fn get_address_string( )) } -fn socket_listen(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_listen(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -262,7 +259,7 @@ fn socket_listen(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } -fn socket_accept(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_accept(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, None)]); let socket = get_socket(zelf); @@ -290,7 +287,7 @@ fn socket_accept(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_tuple(vec![sock_obj, addr_tuple])) } -fn socket_recv(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_recv(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -309,7 +306,7 @@ fn socket_recv(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_bytes(buffer)) } -fn socket_recvfrom(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_recvfrom(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -334,7 +331,7 @@ fn socket_recvfrom(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_tuple(vec![vm.ctx.new_bytes(buffer), addr_tuple])) } -fn socket_send(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_send(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -352,7 +349,7 @@ fn socket_send(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } -fn socket_sendto(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_sendto(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -393,7 +390,7 @@ fn socket_sendto(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn socket_close(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_close(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, None)]); let socket = get_socket(zelf); @@ -401,7 +398,7 @@ fn socket_close(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } -fn socket_getsockname(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn socket_getsockname(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(zelf, None)]); let socket = get_socket(zelf); @@ -416,7 +413,7 @@ fn socket_getsockname(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } -fn get_addr_tuple(vm: &mut VirtualMachine, addr: SocketAddr) -> PyResult { +fn get_addr_tuple(vm: &VirtualMachine, addr: SocketAddr) -> PyResult { let port = vm.ctx.new_int(addr.port()); let ip = vm.ctx.new_str(addr.ip().to_string()); diff --git a/vm/src/stdlib/time_module.rs b/vm/src/stdlib/time_module.rs index c43ae037eff..dfe3ab8e353 100644 --- a/vm/src/stdlib/time_module.rs +++ b/vm/src/stdlib/time_module.rs @@ -8,7 +8,7 @@ use crate::obj::objfloat; use crate::pyobject::{PyContext, PyObjectRef, PyResult, TypeProtocol}; use crate::vm::VirtualMachine; -fn time_sleep(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn time_sleep(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(seconds, Some(vm.ctx.float_type()))]); let seconds = objfloat::get_value(seconds); let secs: u64 = seconds.trunc() as u64; @@ -22,7 +22,7 @@ fn duration_to_f64(d: Duration) -> f64 { (d.as_secs() as f64) + (f64::from(d.subsec_nanos()) / 1e9) } -fn time_time(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn time_time(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args); let x = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(v) => duration_to_f64(v), diff --git a/vm/src/stdlib/tokenize.rs b/vm/src/stdlib/tokenize.rs index 1027e1f030a..0aa5df3d2a7 100644 --- a/vm/src/stdlib/tokenize.rs +++ b/vm/src/stdlib/tokenize.rs @@ -11,7 +11,7 @@ use crate::obj::objstr; use crate::pyobject::{PyContext, PyObjectRef, PyResult, TypeProtocol}; use crate::vm::VirtualMachine; -fn tokenize_tokenize(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn tokenize_tokenize(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(readline, Some(vm.ctx.str_type()))]); let source = objstr::get_value(readline); diff --git a/vm/src/stdlib/types.rs b/vm/src/stdlib/types.rs index 9768f8dc137..279cdbdf9e1 100644 --- a/vm/src/stdlib/types.rs +++ b/vm/src/stdlib/types.rs @@ -7,7 +7,7 @@ use crate::obj::objtype; use crate::pyobject::{PyContext, PyObjectRef, PyResult, TypeProtocol}; use crate::VirtualMachine; -fn types_new_class(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn types_new_class(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, diff --git a/vm/src/sysmodule.rs b/vm/src/sysmodule.rs index 982404fc0ab..8a45bc1c7ee 100644 --- a/vm/src/sysmodule.rs +++ b/vm/src/sysmodule.rs @@ -18,7 +18,7 @@ fn argv(ctx: &PyContext) -> PyObjectRef { ctx.new_list(argv) } -fn frame_idx(vm: &mut VirtualMachine, offset: Option<&PyObjectRef>) -> Result { +fn frame_idx(vm: &VirtualMachine, offset: Option<&PyObjectRef>) -> Result { if let Some(int) = offset { if let Some(offset) = objint::get_value(&int).to_usize() { if offset > vm.frames.borrow().len() - 1 { @@ -30,7 +30,7 @@ fn frame_idx(vm: &mut VirtualMachine, offset: Option<&PyObjectRef>) -> Result PyResult { +fn getframe(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -44,13 +44,13 @@ fn getframe(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(frame.clone()) } -fn sys_getrefcount(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn sys_getrefcount(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(object, None)]); let size = Rc::strong_count(&object); Ok(vm.ctx.new_int(size)) } -fn sys_getsizeof(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn sys_getsizeof(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(object, None)]); // TODO: implement default optional argument. let size = mem::size_of_val(&object); diff --git a/vm/src/vm.rs b/vm/src/vm.rs index 11e9aab3839..d8bdda02036 100644 --- a/vm/src/vm.rs +++ b/vm/src/vm.rs @@ -45,7 +45,7 @@ use num_bigint::BigInt; pub struct VirtualMachine { pub builtins: PyObjectRef, pub sys_module: PyObjectRef, - pub stdlib_inits: HashMap, + pub stdlib_inits: RefCell>, pub ctx: PyContext, pub frames: RefCell>, pub wasm_id: Option, @@ -60,7 +60,7 @@ impl VirtualMachine { let builtins = builtins::make_module(&ctx); let sysmod = sysmodule::make_module(&ctx, builtins.clone()); - let stdlib_inits = stdlib::get_module_inits(); + let stdlib_inits = RefCell::new(stdlib::get_module_inits()); VirtualMachine { builtins, sys_module: sysmod, @@ -71,19 +71,19 @@ impl VirtualMachine { } } - pub fn run_code_obj(&mut self, code: PyObjectRef, scope: Scope) -> PyResult { + pub fn run_code_obj(&self, code: PyObjectRef, scope: Scope) -> PyResult { let frame = self.ctx.new_frame(code, scope); self.run_frame_full(frame) } - pub fn run_frame_full(&mut self, frame: PyObjectRef) -> PyResult { + pub fn run_frame_full(&self, frame: PyObjectRef) -> PyResult { match self.run_frame(frame)? { ExecutionResult::Return(value) => Ok(value), _ => panic!("Got unexpected result from function"), } } - pub fn run_frame(&mut self, frame: PyObjectRef) -> PyResult { + pub fn run_frame(&self, frame: PyObjectRef) -> PyResult { self.frames.borrow_mut().push(frame.clone()); let frame = objframe::get_value(&frame); let result = frame.run(self); @@ -104,7 +104,7 @@ impl VirtualMachine { Ref::map(frame, |f| &f.scope) } - pub fn class(&mut self, module: &str, class: &str) -> PyObjectRef { + pub fn class(&self, module: &str, class: &str) -> PyObjectRef { let module = self .import(module) .unwrap_or_else(|_| panic!("unable to import {}", module)); @@ -131,13 +131,13 @@ impl VirtualMachine { self.ctx.new_dict() } - pub fn new_empty_exception(&mut self, exc_type: PyObjectRef) -> PyResult { + pub fn new_empty_exception(&self, exc_type: PyObjectRef) -> PyResult { info!("New exception created: no msg"); let args = PyFuncArgs::default(); self.invoke(exc_type, args) } - pub fn new_exception(&mut self, exc_type: PyObjectRef, msg: String) -> PyObjectRef { + pub fn new_exception(&self, exc_type: PyObjectRef, msg: String) -> PyObjectRef { // TODO: exc_type may be user-defined exception, so we should return PyResult // TODO: maybe there is a clearer way to create an instance: info!("New exception created: {}", msg); @@ -148,18 +148,18 @@ impl VirtualMachine { self.invoke(exc_type, args).unwrap() } - pub fn new_attribute_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_attribute_error(&self, msg: String) -> PyObjectRef { let attribute_error = self.ctx.exceptions.attribute_error.clone(); self.new_exception(attribute_error, msg) } - pub fn new_type_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_type_error(&self, msg: String) -> PyObjectRef { let type_error = self.ctx.exceptions.type_error.clone(); self.new_exception(type_error, msg) } pub fn new_unsupported_operand_error( - &mut self, + &self, a: PyObjectRef, b: PyObjectRef, op: &str, @@ -172,39 +172,39 @@ impl VirtualMachine { )) } - pub fn new_os_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_os_error(&self, msg: String) -> PyObjectRef { let os_error = self.ctx.exceptions.os_error.clone(); self.new_exception(os_error, msg) } /// Create a new python ValueError object. Useful for raising errors from /// python functions implemented in rust. - pub fn new_value_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_value_error(&self, msg: String) -> PyObjectRef { let value_error = self.ctx.exceptions.value_error.clone(); self.new_exception(value_error, msg) } - pub fn new_key_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_key_error(&self, msg: String) -> PyObjectRef { let key_error = self.ctx.exceptions.key_error.clone(); self.new_exception(key_error, msg) } - pub fn new_index_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_index_error(&self, msg: String) -> PyObjectRef { let index_error = self.ctx.exceptions.index_error.clone(); self.new_exception(index_error, msg) } - pub fn new_not_implemented_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_not_implemented_error(&self, msg: String) -> PyObjectRef { let not_implemented_error = self.ctx.exceptions.not_implemented_error.clone(); self.new_exception(not_implemented_error, msg) } - pub fn new_zero_division_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_zero_division_error(&self, msg: String) -> PyObjectRef { let zero_division_error = self.ctx.exceptions.zero_division_error.clone(); self.new_exception(zero_division_error, msg) } - pub fn new_overflow_error(&mut self, msg: String) -> PyObjectRef { + pub fn new_overflow_error(&self, msg: String) -> PyObjectRef { let overflow_error = self.ctx.exceptions.overflow_error.clone(); self.new_exception(overflow_error, msg) } @@ -230,22 +230,22 @@ impl VirtualMachine { } // Container of the virtual machine state: - pub fn to_str(&mut self, obj: &PyObjectRef) -> PyResult { + pub fn to_str(&self, obj: &PyObjectRef) -> PyResult { let str = self.call_method(&obj, "__str__", vec![])?; TryFromObject::try_from_object(self, str) } - pub fn to_pystr(&mut self, obj: &PyObjectRef) -> Result { + pub fn to_pystr(&self, obj: &PyObjectRef) -> Result { let py_str_obj = self.to_str(obj)?; Ok(py_str_obj.value.clone()) } - pub fn to_repr(&mut self, obj: &PyObjectRef) -> PyResult { + pub fn to_repr(&self, obj: &PyObjectRef) -> PyResult { let repr = self.call_method(obj, "__repr__", vec![])?; TryFromObject::try_from_object(self, repr) } - pub fn import(&mut self, module: &str) -> PyResult { + pub fn import(&self, module: &str) -> PyResult { let builtins_import = self.builtins.get_item("__import__"); match builtins_import { Some(func) => self.invoke(func, vec![self.ctx.new_str(module.to_string())]), @@ -258,7 +258,7 @@ impl VirtualMachine { /// Determines if `obj` is an instance of `cls`, either directly, indirectly or virtually via /// the __instancecheck__ magic method. - pub fn isinstance(&mut self, obj: &PyObjectRef, cls: &PyObjectRef) -> PyResult { + pub fn isinstance(&self, obj: &PyObjectRef, cls: &PyObjectRef) -> PyResult { // cpython first does an exact check on the type, although documentation doesn't state that // https://github.com/python/cpython/blob/a24107b04c1277e3c1105f98aff5bfa3a98b33a0/Objects/abstract.c#L2408 if Rc::ptr_eq(&obj.typ(), cls) { @@ -271,12 +271,12 @@ impl VirtualMachine { /// Determines if `subclass` is a subclass of `cls`, either directly, indirectly or virtually /// via the __subclasscheck__ magic method. - pub fn issubclass(&mut self, subclass: &PyObjectRef, cls: &PyObjectRef) -> PyResult { + pub fn issubclass(&self, subclass: &PyObjectRef, cls: &PyObjectRef) -> PyResult { let ret = self.call_method(cls, "__subclasscheck__", vec![subclass.clone()])?; objbool::boolval(self, ret) } - pub fn call_get_descriptor(&mut self, attr: PyObjectRef, obj: PyObjectRef) -> PyResult { + pub fn call_get_descriptor(&self, attr: PyObjectRef, obj: PyObjectRef) -> PyResult { let attr_class = attr.typ(); if let Some(descriptor) = attr_class.get_attr("__get__") { let cls = obj.typ(); @@ -286,7 +286,7 @@ impl VirtualMachine { } } - pub fn call_method(&mut self, obj: &PyObjectRef, method_name: &str, args: T) -> PyResult + pub fn call_method(&self, obj: &PyObjectRef, method_name: &str, args: T) -> PyResult where T: Into, { @@ -308,7 +308,7 @@ impl VirtualMachine { } } - pub fn invoke(&mut self, func_ref: PyObjectRef, args: T) -> PyResult + pub fn invoke(&self, func_ref: PyObjectRef, args: T) -> PyResult where T: Into, { @@ -339,7 +339,7 @@ impl VirtualMachine { } fn invoke_python_function( - &mut self, + &self, code: &PyObjectRef, scope: &Scope, defaults: &PyObjectRef, @@ -361,7 +361,7 @@ impl VirtualMachine { } pub fn invoke_with_locals( - &mut self, + &self, function: PyObjectRef, cells: PyObjectRef, locals: PyObjectRef, @@ -385,7 +385,7 @@ impl VirtualMachine { } fn fill_locals_from_args( - &mut self, + &self, code_object: &bytecode::CodeObject, locals: &PyObjectRef, args: PyFuncArgs, @@ -536,7 +536,7 @@ impl VirtualMachine { Ok(()) } - pub fn extract_elements(&mut self, value: &PyObjectRef) -> PyResult> { + pub fn extract_elements(&self, value: &PyObjectRef) -> PyResult> { // Extract elements from item, if possible: let elements = if objtype::isinstance(value, &self.ctx.tuple_type()) || objtype::isinstance(value, &self.ctx.list_type()) @@ -550,7 +550,7 @@ impl VirtualMachine { } // get_attribute should be used for full attribute access (usually from user code). - pub fn get_attribute(&mut self, obj: PyObjectRef, attr_name: T) -> PyResult + pub fn get_attribute(&self, obj: PyObjectRef, attr_name: T) -> PyResult where T: TryIntoRef, { @@ -560,7 +560,7 @@ impl VirtualMachine { } pub fn set_attr( - &mut self, + &self, obj: &PyObjectRef, attr_name: PyObjectRef, attr_value: PyObjectRef, @@ -568,13 +568,13 @@ impl VirtualMachine { self.call_method(&obj, "__setattr__", vec![attr_name, attr_value]) } - pub fn del_attr(&mut self, obj: &PyObjectRef, attr_name: PyObjectRef) -> PyResult { + pub fn del_attr(&self, obj: &PyObjectRef, attr_name: PyObjectRef) -> PyResult { self.call_method(&obj, "__delattr__", vec![attr_name]) } // get_method should be used for internal access to magic methods (by-passing // the full getattribute look-up. - pub fn get_method(&mut self, obj: PyObjectRef, method_name: &str) -> PyResult { + pub fn get_method(&self, obj: PyObjectRef, method_name: &str) -> PyResult { let cls = obj.typ(); match cls.get_attr(method_name) { Some(method) => self.call_get_descriptor(method, obj.clone()), @@ -587,14 +587,14 @@ impl VirtualMachine { /// Otherwise, or if the result is the special `NotImplemented` built-in constant, /// calls `unsupported` to determine fallback value. pub fn call_or_unsupported( - &mut self, + &self, obj: PyObjectRef, arg: PyObjectRef, method: &str, unsupported: F, ) -> PyResult where - F: Fn(&mut VirtualMachine, PyObjectRef, PyObjectRef) -> PyResult, + F: Fn(&VirtualMachine, PyObjectRef, PyObjectRef) -> PyResult, { if let Ok(method) = self.get_method(obj.clone(), method) { let result = self.invoke(method, vec![arg.clone()])?; @@ -617,12 +617,12 @@ impl VirtualMachine { /// 2. If above is not implemented, calls `__rand__` with `rhs` and `lhs`. /// 3. If above is not implemented, invokes `unsupported` for the result. pub fn call_or_reflection( - &mut self, + &self, lhs: PyObjectRef, rhs: PyObjectRef, default: &str, reflection: &str, - unsupported: fn(&mut VirtualMachine, PyObjectRef, PyObjectRef) -> PyResult, + unsupported: fn(&VirtualMachine, PyObjectRef, PyObjectRef) -> PyResult, ) -> PyResult { // Try to call the default method self.call_or_unsupported(lhs, rhs, default, move |vm, lhs, rhs| { @@ -631,21 +631,21 @@ impl VirtualMachine { }) } - pub fn serialize(&mut self, obj: &PyObjectRef) -> PyResult { + pub fn serialize(&self, obj: &PyObjectRef) -> PyResult { crate::stdlib::json::ser_pyobject(self, obj) } - pub fn deserialize(&mut self, s: &str) -> PyResult { + pub fn deserialize(&self, s: &str) -> PyResult { crate::stdlib::json::de_pyobject(self, s) } - pub fn _sub(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _sub(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__sub__", "__rsub__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "-")) }) } - pub fn _isub(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _isub(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__isub__", |vm, a, b| { vm.call_or_reflection(a, b, "__sub__", "__rsub__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "-=")) @@ -653,13 +653,13 @@ impl VirtualMachine { }) } - pub fn _add(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _add(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__add__", "__radd__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "+")) }) } - pub fn _iadd(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _iadd(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__iadd__", |vm, a, b| { vm.call_or_reflection(a, b, "__add__", "__radd__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "+=")) @@ -667,13 +667,13 @@ impl VirtualMachine { }) } - pub fn _mul(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _mul(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__mul__", "__rmul__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "*")) }) } - pub fn _imul(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _imul(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__imul__", |vm, a, b| { vm.call_or_reflection(a, b, "__mul__", "__rmul__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "*=")) @@ -681,13 +681,13 @@ impl VirtualMachine { }) } - pub fn _matmul(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _matmul(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__matmul__", "__rmatmul__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "@")) }) } - pub fn _imatmul(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _imatmul(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__imatmul__", |vm, a, b| { vm.call_or_reflection(a, b, "__matmul__", "__rmatmul__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "@=")) @@ -695,13 +695,13 @@ impl VirtualMachine { }) } - pub fn _truediv(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _truediv(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__truediv__", "__rtruediv__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "/")) }) } - pub fn _itruediv(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _itruediv(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__itruediv__", |vm, a, b| { vm.call_or_reflection(a, b, "__truediv__", "__rtruediv__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "/=")) @@ -709,13 +709,13 @@ impl VirtualMachine { }) } - pub fn _floordiv(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _floordiv(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__floordiv__", "__rfloordiv__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "//")) }) } - pub fn _ifloordiv(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _ifloordiv(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__ifloordiv__", |vm, a, b| { vm.call_or_reflection(a, b, "__floordiv__", "__rfloordiv__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "//=")) @@ -723,13 +723,13 @@ impl VirtualMachine { }) } - pub fn _pow(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _pow(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__pow__", "__rpow__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "**")) }) } - pub fn _ipow(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _ipow(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__ipow__", |vm, a, b| { vm.call_or_reflection(a, b, "__pow__", "__rpow__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "**=")) @@ -737,13 +737,13 @@ impl VirtualMachine { }) } - pub fn _mod(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _mod(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__mod__", "__rmod__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "%")) }) } - pub fn _imod(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _imod(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__imod__", |vm, a, b| { vm.call_or_reflection(a, b, "__mod__", "__rmod__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "%=")) @@ -751,13 +751,13 @@ impl VirtualMachine { }) } - pub fn _lshift(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _lshift(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__lshift__", "__rlshift__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "<<")) }) } - pub fn _ilshift(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _ilshift(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__ilshift__", |vm, a, b| { vm.call_or_reflection(a, b, "__lshift__", "__rlshift__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "<<=")) @@ -765,13 +765,13 @@ impl VirtualMachine { }) } - pub fn _rshift(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _rshift(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__rshift__", "__rrshift__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, ">>")) }) } - pub fn _irshift(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _irshift(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__irshift__", |vm, a, b| { vm.call_or_reflection(a, b, "__rshift__", "__rrshift__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, ">>=")) @@ -779,13 +779,13 @@ impl VirtualMachine { }) } - pub fn _xor(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _xor(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__xor__", "__rxor__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "^")) }) } - pub fn _ixor(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _ixor(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__ixor__", |vm, a, b| { vm.call_or_reflection(a, b, "__xor__", "__rxor__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "^=")) @@ -793,13 +793,13 @@ impl VirtualMachine { }) } - pub fn _or(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _or(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__or__", "__ror__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "|")) }) } - pub fn _ior(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _ior(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__ior__", |vm, a, b| { vm.call_or_reflection(a, b, "__or__", "__ror__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "|=")) @@ -807,13 +807,13 @@ impl VirtualMachine { }) } - pub fn _and(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _and(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__and__", "__rand__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "&")) }) } - pub fn _iand(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _iand(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_unsupported(a, b, "__iand__", |vm, a, b| { vm.call_or_reflection(a, b, "__and__", "__rand__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "&=")) @@ -821,38 +821,38 @@ impl VirtualMachine { }) } - pub fn _eq(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _eq(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__eq__", "__eq__", |vm, a, b| { Ok(vm.new_bool(a.is(&b))) }) } - pub fn _ne(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _ne(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__ne__", "__ne__", |vm, a, b| { let eq = vm._eq(a, b)?; objbool::not(vm, &eq) }) } - pub fn _lt(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _lt(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__lt__", "__gt__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "<")) }) } - pub fn _le(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _le(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__le__", "__ge__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, "<=")) }) } - pub fn _gt(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _gt(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__gt__", "__lt__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, ">")) }) } - pub fn _ge(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult { + pub fn _ge(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult { self.call_or_reflection(a, b, "__ge__", "__le__", |vm, a, b| { Err(vm.new_unsupported_operand_error(a, b, ">=")) }) diff --git a/wasm/lib/src/browser_module.rs b/wasm/lib/src/browser_module.rs index e30f653917b..7fc2a2476e5 100644 --- a/wasm/lib/src/browser_module.rs +++ b/wasm/lib/src/browser_module.rs @@ -24,7 +24,7 @@ enum FetchResponseFormat { } impl FetchResponseFormat { - fn from_str(vm: &mut VirtualMachine, s: &str) -> Result { + fn from_str(vm: &VirtualMachine, s: &str) -> Result { match s { "json" => Ok(FetchResponseFormat::Json), "text" => Ok(FetchResponseFormat::Text), @@ -41,7 +41,7 @@ impl FetchResponseFormat { } } -fn browser_fetch(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn browser_fetch(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(url, Some(vm.ctx.str_type()))]); let promise_type = import_promise_type(vm)?; @@ -104,7 +104,7 @@ fn browser_fetch(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(PyPromise::new_obj(promise_type, future_to_promise(future))) } -fn browser_request_animation_frame(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn browser_request_animation_frame(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(func, Some(vm.ctx.function_type()))]); use std::{cell::RefCell, rc::Rc}; @@ -117,12 +117,13 @@ fn browser_request_animation_frame(vm: &mut VirtualMachine, args: PyFuncArgs) -> let func = func.clone(); - let acc_vm = AccessibleVM::from_vm(vm); + let acc_vm = AccessibleVM::from(vm); *g.borrow_mut() = Some(Closure::wrap(Box::new(move |time: f64| { - let vm = &mut acc_vm + let stored_vm = acc_vm .upgrade() .expect("that the vm is valid from inside of request_animation_frame"); + let vm = &stored_vm.vm; let func = func.clone(); let args = vec![vm.ctx.new_float(time)]; let _ = vm.invoke(func, args); @@ -140,7 +141,7 @@ fn browser_request_animation_frame(vm: &mut VirtualMachine, args: PyFuncArgs) -> Ok(vm.ctx.new_int(id)) } -fn browser_cancel_animation_frame(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn browser_cancel_animation_frame(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(id, Some(vm.ctx.int_type()))]); let id = objint::get_value(id).to_i32().ok_or_else(|| { @@ -163,7 +164,7 @@ pub struct PyPromise { } impl PyValue for PyPromise { - fn class(vm: &mut VirtualMachine) -> PyObjectRef { + fn class(vm: &VirtualMachine) -> PyObjectRef { vm.class(BROWSER_NAME, "Promise") } } @@ -181,14 +182,14 @@ pub fn get_promise_value(obj: &PyObjectRef) -> Promise { panic!("Inner error getting promise") } -pub fn import_promise_type(vm: &mut VirtualMachine) -> PyResult { +pub fn import_promise_type(vm: &VirtualMachine) -> PyResult { match import_module(vm, PathBuf::default(), BROWSER_NAME)?.get_attr("Promise") { Some(promise) => Ok(promise), None => Err(vm.new_not_implemented_error("No Promise".to_string())), } } -fn promise_then(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn promise_then(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let promise_type = import_promise_type(vm)?; arg_check!( vm, @@ -203,14 +204,15 @@ fn promise_then(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { let on_fulfill = on_fulfill.clone(); let on_reject = on_reject.cloned(); - let acc_vm = AccessibleVM::from_vm(vm); + let acc_vm = AccessibleVM::from(vm); let promise = get_promise_value(zelf); let ret_future = JsFuture::from(promise).then(move |res| { - let vm = &mut acc_vm + let stored_vm = &acc_vm .upgrade() .expect("that the vm is valid when the promise resolves"); + let vm = &stored_vm.vm; let ret = match res { Ok(val) => { let val = convert::js_to_py(vm, val); @@ -233,7 +235,7 @@ fn promise_then(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(PyPromise::new_obj(promise_type, ret_promise)) } -fn promise_catch(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn promise_catch(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let promise_type = import_promise_type(vm)?; arg_check!( vm, @@ -246,16 +248,17 @@ fn promise_catch(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { let on_reject = on_reject.clone(); - let acc_vm = AccessibleVM::from_vm(vm); + let acc_vm = AccessibleVM::from(vm); let promise = get_promise_value(zelf); let ret_future = JsFuture::from(promise).then(move |res| match res { Ok(val) => Ok(val), Err(err) => { - let vm = &mut acc_vm + let stored_vm = acc_vm .upgrade() .expect("that the vm is valid when the promise resolves"); + let vm = &stored_vm.vm; let err = convert::js_to_py(vm, err); let res = vm.invoke(on_reject, PyFuncArgs::new(vec![err], vec![])); convert::pyresult_to_jsresult(vm, res) @@ -267,7 +270,7 @@ fn promise_catch(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(PyPromise::new_obj(promise_type, ret_promise)) } -fn browser_alert(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn browser_alert(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(message, Some(vm.ctx.str_type()))]); window() @@ -277,7 +280,7 @@ fn browser_alert(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } -fn browser_confirm(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn browser_confirm(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(message, Some(vm.ctx.str_type()))]); let result = window() @@ -287,7 +290,7 @@ fn browser_confirm(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_bool(result)) } -fn browser_prompt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { +fn browser_prompt(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, @@ -331,7 +334,8 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef { }) } -pub fn setup_browser_module(vm: &mut VirtualMachine) { +pub fn setup_browser_module(vm: &VirtualMachine) { vm.stdlib_inits + .borrow_mut() .insert(BROWSER_NAME.to_string(), Box::new(make_module)); } diff --git a/wasm/lib/src/convert.rs b/wasm/lib/src/convert.rs index 1113ace8783..122ff1763e6 100644 --- a/wasm/lib/src/convert.rs +++ b/wasm/lib/src/convert.rs @@ -10,7 +10,7 @@ use rustpython_vm::VirtualMachine; use crate::browser_module; use crate::vm_class::{AccessibleVM, WASMVirtualMachine}; -pub fn py_err_to_js_err(vm: &mut VirtualMachine, py_err: &PyObjectRef) -> JsValue { +pub fn py_err_to_js_err(vm: &VirtualMachine, py_err: &PyObjectRef) -> JsValue { macro_rules! map_exceptions { ($py_exc:ident, $msg:expr, { $($py_exc_ty:expr => $js_err_new:expr),*$(,)? }) => { $(if objtype::isinstance($py_exc, $py_exc_ty) { @@ -57,12 +57,12 @@ pub fn py_err_to_js_err(vm: &mut VirtualMachine, py_err: &PyObjectRef) -> JsValu js_err } -pub fn js_py_typeerror(vm: &mut VirtualMachine, js_err: JsValue) -> PyObjectRef { +pub fn js_py_typeerror(vm: &VirtualMachine, js_err: JsValue) -> PyObjectRef { let msg = js_err.unchecked_into::().to_string(); vm.new_type_error(msg.into()) } -pub fn py_to_js(vm: &mut VirtualMachine, py_obj: PyObjectRef) -> JsValue { +pub fn py_to_js(vm: &VirtualMachine, py_obj: PyObjectRef) -> JsValue { if let Some(ref wasm_id) = vm.wasm_id { if objtype::isinstance(&py_obj, &vm.ctx.function_type()) { let wasm_vm = WASMVirtualMachine { @@ -81,9 +81,10 @@ pub fn py_to_js(vm: &mut VirtualMachine, py_obj: PyObjectRef) -> JsValue { } }; let acc_vm = AccessibleVM::from(wasm_vm.clone()); - let vm = &mut acc_vm + let stored_vm = acc_vm .upgrade() .expect("acc. VM to be invalid when WASM vm is valid"); + let vm = &stored_vm.vm; let mut py_func_args = PyFuncArgs::default(); if let Some(ref args) = args { for arg in args.values() { @@ -147,13 +148,13 @@ pub fn object_entries(obj: &Object) -> impl Iterator Result { +pub fn pyresult_to_jsresult(vm: &VirtualMachine, result: PyResult) -> Result { result .map(|value| py_to_js(vm, value)) .map_err(|err| py_err_to_js_err(vm, &err)) } -pub fn js_to_py(vm: &mut VirtualMachine, js_val: JsValue) -> PyObjectRef { +pub fn js_to_py(vm: &VirtualMachine, js_val: JsValue) -> PyObjectRef { if js_val.is_object() { if let Some(promise) = js_val.dyn_ref::() { // the browser module might not be injected @@ -193,8 +194,8 @@ pub fn js_to_py(vm: &mut VirtualMachine, js_val: JsValue) -> PyObjectRef { } } else if js_val.is_function() { let func = js_sys::Function::from(js_val); - vm.ctx.new_rustfunc( - move |vm: &mut VirtualMachine, args: PyFuncArgs| -> PyResult { + vm.ctx + .new_rustfunc(move |vm: &VirtualMachine, args: PyFuncArgs| -> PyResult { let func = func.clone(); let this = Object::new(); for (k, v) in args.kwargs { @@ -208,8 +209,7 @@ pub fn js_to_py(vm: &mut VirtualMachine, js_val: JsValue) -> PyObjectRef { func.apply(&this, &js_args) .map(|val| js_to_py(vm, val)) .map_err(|err| js_to_py(vm, err)) - }, - ) + }) } else if let Some(err) = js_val.dyn_ref::() { let exc_type = match String::from(err.name()).as_str() { "TypeError" => &vm.ctx.exceptions.type_error, diff --git a/wasm/lib/src/vm_class.rs b/wasm/lib/src/vm_class.rs index 408e2b3cc0c..9d80854f73d 100644 --- a/wasm/lib/src/vm_class.rs +++ b/wasm/lib/src/vm_class.rs @@ -21,10 +21,10 @@ impl HeldRcInner for T {} pub(crate) struct StoredVirtualMachine { pub vm: VirtualMachine, - pub scope: Scope, + pub scope: RefCell, /// you can put a Rc in here, keep it as a Weak, and it'll be held only for /// as long as the StoredVM is alive - held_rcs: Vec>, + held_rcs: RefCell>>, } impl StoredVirtualMachine { @@ -32,13 +32,13 @@ impl StoredVirtualMachine { let mut vm = VirtualMachine::new(); let scope = vm.ctx.new_scope(); if inject_browser_module { - setup_browser_module(&mut vm); + setup_browser_module(&vm); } vm.wasm_id = Some(id); StoredVirtualMachine { vm, - scope, - held_rcs: vec![], + scope: RefCell::new(scope), + held_rcs: RefCell::new(Vec::new()), } } } @@ -47,9 +47,9 @@ impl StoredVirtualMachine { // probably gets compiled down to a normal-ish static varible, like Atomic* types do: // https://rustwasm.github.io/2018/10/24/multithreading-rust-and-wasm.html#atomic-instructions thread_local! { - static STORED_VMS: RefCell>>> = + static STORED_VMS: RefCell>> = RefCell::default(); - static ACTIVE_VMS: RefCell> = RefCell::default(); + static ACTIVE_VMS: RefCell> = RefCell::default(); } #[wasm_bindgen(js_name = vmStore)] @@ -63,7 +63,7 @@ impl VMStore { if !vms.contains_key(&id) { let stored_vm = StoredVirtualMachine::new(id.clone(), inject_browser_module.unwrap_or(true)); - vms.insert(id.clone(), Rc::new(RefCell::new(stored_vm))); + vms.insert(id.clone(), Rc::new(stored_vm)); } }); WASMVirtualMachine { id } @@ -110,8 +110,8 @@ impl VMStore { } #[derive(Clone)] -pub struct AccessibleVM { - weak: Weak>, +pub(crate) struct AccessibleVM { + weak: Weak, id: String, } @@ -122,35 +122,8 @@ impl AccessibleVM { AccessibleVM { weak, id } } - pub fn from_vm(vm: &VirtualMachine) -> AccessibleVM { - AccessibleVM::from_id( - vm.wasm_id - .clone() - .expect("VM passed to from_vm to have wasm_id be Some()"), - ) - } - - pub fn upgrade(&self) -> Option { - let vm_cell = self.weak.upgrade()?; - let top_level = match vm_cell.try_borrow_mut() { - Ok(mut vm) => { - ACTIVE_VMS.with(|cell| { - cell.borrow_mut().insert(self.id.clone(), &mut vm.vm); - }); - true - } - Err(_) => false, - }; - Some(ACTIVE_VMS.with(|cell| { - let vms = cell.borrow(); - let ptr = vms.get(&self.id).expect("id to be in ACTIVE_VMS"); - let vm = unsafe { &mut **ptr }; - AccessibleVMPtr { - id: self.id.clone(), - top_level, - inner: vm, - } - })) + pub fn upgrade(&self) -> Option> { + self.weak.upgrade() } } @@ -164,31 +137,13 @@ impl From<&WASMVirtualMachine> for AccessibleVM { AccessibleVM::from_id(vm.id.clone()) } } - -pub struct AccessibleVMPtr<'a> { - id: String, - top_level: bool, - inner: &'a mut VirtualMachine, -} - -impl std::ops::Deref for AccessibleVMPtr<'_> { - type Target = VirtualMachine; - fn deref(&self) -> &VirtualMachine { - &self.inner - } -} -impl std::ops::DerefMut for AccessibleVMPtr<'_> { - fn deref_mut(&mut self) -> &mut VirtualMachine { - &mut self.inner - } -} - -impl Drop for AccessibleVMPtr<'_> { - fn drop(&mut self) { - if self.top_level { - // remove the (now invalid) pointer from the map - ACTIVE_VMS.with(|cell| cell.borrow_mut().remove(&self.id)); - } +impl From<&VirtualMachine> for AccessibleVM { + fn from(vm: &VirtualMachine) -> AccessibleVM { + AccessibleVM::from_id( + vm.wasm_id + .clone() + .expect("VM passed to from::() to have wasm_id be Some()"), + ) } } @@ -202,19 +157,18 @@ pub struct WASMVirtualMachine { impl WASMVirtualMachine { pub(crate) fn with_unchecked(&self, f: F) -> R where - F: FnOnce(&mut StoredVirtualMachine) -> R, + F: FnOnce(&StoredVirtualMachine) -> R, { let stored_vm = STORED_VMS.with(|cell| { let mut vms = cell.borrow_mut(); vms.get_mut(&self.id).unwrap().clone() }); - let mut stored_vm = stored_vm.borrow_mut(); - f(&mut stored_vm) + f(&stored_vm) } pub(crate) fn with(&self, f: F) -> Result where - F: FnOnce(&mut StoredVirtualMachine) -> R, + F: FnOnce(&StoredVirtualMachine) -> R, { self.assert_valid()?; Ok(self.with_unchecked(f)) @@ -230,7 +184,7 @@ impl WASMVirtualMachine { ) -> Result, JsValue> { self.with(|stored_vm| { let weak = Rc::downgrade(&rc); - stored_vm.held_rcs.push(rc); + stored_vm.held_rcs.borrow_mut().push(rc); weak }) } @@ -256,23 +210,21 @@ impl WASMVirtualMachine { pub fn add_to_scope(&self, name: String, value: JsValue) -> Result<(), JsValue> { self.with( move |StoredVirtualMachine { - ref mut vm, - ref mut scope, - .. + ref vm, ref scope, .. }| { let value = convert::js_to_py(vm, value); - scope.store_name(&vm, &name, value); + scope.borrow_mut().store_name(&vm, &name, value); }, ) } #[wasm_bindgen(js_name = setStdout)] pub fn set_stdout(&self, stdout: JsValue) -> Result<(), JsValue> { - self.with(move |StoredVirtualMachine { ref mut vm, .. }| { + self.with(move |StoredVirtualMachine { ref vm, .. }| { fn error() -> JsValue { TypeError::new("Unknown stdout option, please pass a function or 'console'").into() } - let print_fn: Box PyResult> = + let print_fn: Box PyResult> = if let Some(s) = stdout.as_string() { match s.as_str() { "console" => Box::new(wasm_builtins::builtin_print_console), @@ -280,18 +232,16 @@ impl WASMVirtualMachine { } } else if stdout.is_function() { let func = js_sys::Function::from(stdout); - Box::new( - move |vm: &mut VirtualMachine, args: PyFuncArgs| -> PyResult { - func.call1( - &JsValue::UNDEFINED, - &wasm_builtins::format_print_args(vm, args)?.into(), - ) - .map_err(|err| convert::js_to_py(vm, err))?; - Ok(vm.get_none()) - }, - ) + Box::new(move |vm: &VirtualMachine, args: PyFuncArgs| -> PyResult { + func.call1( + &JsValue::UNDEFINED, + &wasm_builtins::format_print_args(vm, args)?.into(), + ) + .map_err(|err| convert::js_to_py(vm, err))?; + Ok(vm.get_none()) + }) } else if stdout.is_undefined() || stdout.is_null() { - fn noop(vm: &mut VirtualMachine, _args: PyFuncArgs) -> PyResult { + fn noop(vm: &VirtualMachine, _args: PyFuncArgs) -> PyResult { Ok(vm.get_none()) } Box::new(noop) @@ -306,7 +256,7 @@ impl WASMVirtualMachine { #[wasm_bindgen(js_name = injectModule)] pub fn inject_module(&self, name: String, module: Object) -> Result<(), JsValue> { - self.with(|StoredVirtualMachine { ref mut vm, .. }| { + self.with(|StoredVirtualMachine { ref vm, .. }| { let mut module_items: HashMap = HashMap::new(); for entry in convert::object_entries(&module) { let (key, value) = entry?; @@ -324,7 +274,9 @@ impl WASMVirtualMachine { py_mod }; - vm.stdlib_inits.insert(mod_name, Box::new(stdlib_init_fn)); + vm.stdlib_inits + .borrow_mut() + .insert(mod_name, Box::new(stdlib_init_fn)); Ok(()) })? @@ -334,9 +286,7 @@ impl WASMVirtualMachine { self.assert_valid()?; self.with_unchecked( |StoredVirtualMachine { - ref mut vm, - ref mut scope, - .. + ref vm, ref scope, .. }| { source.push('\n'); let code = @@ -378,7 +328,7 @@ impl WASMVirtualMachine { } js_err })?; - let result = vm.run_code_obj(code, scope.clone()); + let result = vm.run_code_obj(code, scope.borrow().clone()); convert::pyresult_to_jsresult(vm, result) }, ) diff --git a/wasm/lib/src/wasm_builtins.rs b/wasm/lib/src/wasm_builtins.rs index cc3435bbaa0..d5bc830dfe4 100644 --- a/wasm/lib/src/wasm_builtins.rs +++ b/wasm/lib/src/wasm_builtins.rs @@ -16,7 +16,7 @@ pub(crate) fn window() -> web_sys::Window { web_sys::window().expect("Window to be available") } -pub fn format_print_args(vm: &mut VirtualMachine, args: PyFuncArgs) -> Result { +pub fn format_print_args(vm: &VirtualMachine, args: PyFuncArgs) -> Result { // Handle 'sep' kwarg: let sep_arg = args .get_optional_kwarg("sep") @@ -68,7 +68,7 @@ pub fn format_print_args(vm: &mut VirtualMachine, args: PyFuncArgs) -> Result PyResult { +pub fn builtin_print_console(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let arr = Array::new(); for arg in args.args { arr.push(&vm.to_pystr(&arg)?.into());