From c3f46c773ec1b21fbe16079ed2e290159dee4d8e Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Sat, 25 Sep 2021 16:07:43 +0900 Subject: [PATCH 1/2] Expose exception types under vm::builtins --- derive/src/pyclass.rs | 2 +- src/shell.rs | 3 +- vm/src/builtins/asyncgenerator.rs | 2 +- vm/src/builtins/dict.rs | 2 +- vm/src/builtins/function/jitfunc.rs | 2 +- vm/src/builtins/mod.rs | 2 + vm/src/builtins/singletons.rs | 5 +- vm/src/codecs.rs | 2 +- vm/src/coroutine.rs | 3 +- vm/src/exceptions.rs | 1106 ++++++++++++++------------- vm/src/format.rs | 4 +- vm/src/frame.rs | 3 +- vm/src/function.rs | 2 +- vm/src/import.rs | 2 +- vm/src/iterator.rs | 2 +- vm/src/py_io.rs | 2 +- vm/src/pyobject.rs | 3 +- vm/src/stdlib/codecs.rs | 3 +- vm/src/stdlib/io.rs | 10 +- vm/src/stdlib/json.rs | 2 +- vm/src/stdlib/os.rs | 3 +- vm/src/stdlib/pystruct.rs | 5 +- vm/src/stdlib/socket.rs | 4 +- vm/src/stdlib/ssl.rs | 7 +- vm/src/stdlib/termios.rs | 2 +- vm/src/stdlib/zlib.rs | 3 +- vm/src/vm.rs | 3 +- wasm/lib/src/convert.rs | 25 +- wasm/lib/src/js_module.rs | 2 +- 29 files changed, 617 insertions(+), 599 deletions(-) diff --git a/derive/src/pyclass.rs b/derive/src/pyclass.rs index d019e59d8..fc55d7d21 100644 --- a/derive/src/pyclass.rs +++ b/derive/src/pyclass.rs @@ -346,7 +346,7 @@ pub(crate) fn impl_define_exception( #[pymethod(magic)] pub(crate) fn init( - zelf: ::rustpython_vm::PyRef<::rustpython_vm::exceptions::PyBaseException>, + zelf: ::rustpython_vm::PyRef<::rustpython_vm::builtins::PyBaseException>, args: ::rustpython_vm::function::FuncArgs, vm: &::rustpython_vm::VirtualMachine, ) -> ::rustpython_vm::PyResult<()> { diff --git a/src/shell.rs b/src/shell.rs index 0b98e1755..4fb91b499 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -3,8 +3,9 @@ mod helper; use rustpython_parser::error::{LexicalErrorType, ParseErrorType}; use rustpython_vm::readline::{Readline, ReadlineResult}; use rustpython_vm::{ + builtins::PyBaseExceptionRef, compile::{self, CompileError, CompileErrorType}, - exceptions::{print_exception, PyBaseExceptionRef}, + exceptions::print_exception, scope::Scope, PyResult, TypeProtocol, VirtualMachine, }; diff --git a/vm/src/builtins/asyncgenerator.rs b/vm/src/builtins/asyncgenerator.rs index b43969328..d8365178f 100644 --- a/vm/src/builtins/asyncgenerator.rs +++ b/vm/src/builtins/asyncgenerator.rs @@ -1,7 +1,7 @@ use super::{PyCode, PyStrRef, PyTypeRef}; use crate::{ + builtins::PyBaseExceptionRef, coroutine::{Coro, Variant}, - exceptions::PyBaseExceptionRef, frame::FrameRef, function::OptionalArg, slots::{IteratorIterable, PyIter}, diff --git a/vm/src/builtins/dict.rs b/vm/src/builtins/dict.rs index b3541dbe2..aeaa17039 100644 --- a/vm/src/builtins/dict.rs +++ b/vm/src/builtins/dict.rs @@ -1,8 +1,8 @@ use super::{IterStatus, PySet, PyStrRef, PyTypeRef}; use crate::{ + builtins::PyBaseExceptionRef, common::ascii, dictdatatype::{self, DictKey}, - exceptions::PyBaseExceptionRef, function::{ArgIterable, FuncArgs, KwArgs, OptionalArg}, iterator, slots::{Comparable, Hashable, Iterable, IteratorIterable, PyComparisonOp, PyIter, Unhashable}, diff --git a/vm/src/builtins/function/jitfunc.rs b/vm/src/builtins/function/jitfunc.rs index c7dfeb18c..9c3623742 100644 --- a/vm/src/builtins/function/jitfunc.rs +++ b/vm/src/builtins/function/jitfunc.rs @@ -1,8 +1,8 @@ use crate::builtins::dict::PyDictRef; use crate::builtins::function::{PyFunction, PyFunctionRef}; +use crate::builtins::PyBaseExceptionRef; use crate::builtins::{float, int, pybool, PyStrRef}; use crate::bytecode::CodeFlags; -use crate::exceptions::PyBaseExceptionRef; use crate::function::FuncArgs; use crate::VirtualMachine; use crate::{ diff --git a/vm/src/builtins/mod.rs b/vm/src/builtins/mod.rs index 8f6f9f11f..29d96cd0e 100644 --- a/vm/src/builtins/mod.rs +++ b/vm/src/builtins/mod.rs @@ -86,3 +86,5 @@ pub use int::try_to_float as try_bigint_to_f64; mod make_module; pub use make_module::{ascii, make_module, print}; + +pub use crate::exceptions::types::*; diff --git a/vm/src/builtins/singletons.rs b/vm/src/builtins/singletons.rs index 6b79793fd..4e9afbf99 100644 --- a/vm/src/builtins/singletons.rs +++ b/vm/src/builtins/singletons.rs @@ -1,13 +1,12 @@ use super::PyTypeRef; use crate::{ - slots::SlotConstructor, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, - PyValue, TypeProtocol, VirtualMachine, + slots::SlotConstructor, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyResult, PyValue, + TypeProtocol, VirtualMachine, }; #[pyclass(module = false, name = "NoneType")] #[derive(Debug)] pub struct PyNone; -pub type PyNoneRef = PyRef; impl PyValue for PyNone { fn class(vm: &VirtualMachine) -> &PyTypeRef { diff --git a/vm/src/codecs.rs b/vm/src/codecs.rs index 28d8db810..b5a7dc795 100644 --- a/vm/src/codecs.rs +++ b/vm/src/codecs.rs @@ -2,9 +2,9 @@ use std::borrow::Cow; use std::collections::HashMap; use std::ops::Range; +use crate::builtins::PyBaseExceptionRef; use crate::builtins::{PyBytesRef, PyStr, PyStrRef, PyTuple, PyTupleRef}; use crate::common::{ascii, lock::PyRwLock}; -use crate::exceptions::PyBaseExceptionRef; use crate::VirtualMachine; use crate::{IntoPyObject, PyContext, PyObjectRef, PyResult, PyValue, TryFromObject, TypeProtocol}; diff --git a/vm/src/coroutine.rs b/vm/src/coroutine.rs index 94d5da742..3db3d190c 100644 --- a/vm/src/coroutine.rs +++ b/vm/src/coroutine.rs @@ -1,5 +1,6 @@ +use crate::builtins::PyBaseExceptionRef; use crate::builtins::{PyStrRef, PyTypeRef}; -use crate::exceptions::{self, PyBaseExceptionRef}; +use crate::exceptions; use crate::frame::{ExecutionResult, FrameRef}; use crate::VirtualMachine; use crate::{PyObjectRef, PyResult, TypeProtocol}; diff --git a/vm/src/exceptions.rs b/vm/src/exceptions.rs index fa78bb293..7e9dc2183 100644 --- a/vm/src/exceptions.rs +++ b/vm/src/exceptions.rs @@ -1,17 +1,14 @@ -use crate::builtins::pystr::{PyStr, PyStrRef}; -use crate::builtins::pytype::{PyType, PyTypeRef}; -use crate::builtins::singletons::{PyNone, PyNoneRef}; -use crate::builtins::traceback::PyTracebackRef; -use crate::builtins::tuple::{PyTuple, PyTupleRef}; +use self::types::{PyBaseException, PyBaseExceptionRef}; use crate::common::lock::PyRwLock; -use crate::function::{ArgIterable, FuncArgs}; -use crate::py_io::{self, Write}; -use crate::sysmodule; use crate::{ - IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, - StaticType, TryFromObject, TypeProtocol, VirtualMachine, + builtins::{ + traceback::PyTracebackRef, PyNone, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, + }, + function::{ArgIterable, FuncArgs}, + py_io::{self, Write}, + sysmodule, IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, + PyValue, StaticType, TryFromObject, TypeProtocol, VirtualMachine, }; - use crossbeam_utils::atomic::AtomicCell; use itertools::Itertools; use std::collections::HashSet; @@ -19,13 +16,8 @@ use std::fmt; use std::fs::File; use std::io::{self, BufRead, BufReader}; -#[pyclass(module = false, name = "BaseException")] -pub struct PyBaseException { - traceback: PyRwLock>, - cause: PyRwLock>, - context: PyRwLock>, - suppress_context: AtomicCell, - args: PyRwLock, +pub trait IntoPyException { + fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef; } impl fmt::Debug for PyBaseException { @@ -35,127 +27,12 @@ impl fmt::Debug for PyBaseException { } } -pub type PyBaseExceptionRef = PyRef; - -pub trait IntoPyException { - fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef; -} - impl PyValue for PyBaseException { fn class(vm: &VirtualMachine) -> &PyTypeRef { &vm.ctx.exceptions.base_exception_type } } -#[pyimpl(flags(BASETYPE, HAS_DICT))] -impl PyBaseException { - pub(crate) fn new(args: Vec, vm: &VirtualMachine) -> PyBaseException { - PyBaseException { - traceback: PyRwLock::new(None), - cause: PyRwLock::new(None), - context: PyRwLock::new(None), - suppress_context: AtomicCell::new(false), - args: PyRwLock::new(PyTupleRef::with_elements(args, &vm.ctx)), - } - } - - #[pyslot] - pub(crate) fn tp_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - PyBaseException::new(args.args, vm).into_pyresult_with_type(vm, cls) - } - - #[pymethod(magic)] - pub(crate) fn init(zelf: PyRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - *zelf.args.write() = PyTupleRef::with_elements(args.args, &vm.ctx); - Ok(()) - } - - pub fn get_arg(&self, idx: usize) -> Option { - self.args.read().as_slice().get(idx).cloned() - } - - #[pyproperty] - pub fn args(&self) -> PyTupleRef { - self.args.read().clone() - } - - #[pyproperty(setter)] - fn set_args(&self, args: ArgIterable, vm: &VirtualMachine) -> PyResult<()> { - let args = args.iter(vm)?.collect::>>()?; - *self.args.write() = PyTupleRef::with_elements(args, &vm.ctx); - Ok(()) - } - - #[pyproperty(magic)] - pub fn traceback(&self) -> Option { - self.traceback.read().clone() - } - - #[pyproperty(name = "__traceback__", setter)] - pub fn set_traceback(&self, traceback: Option) { - *self.traceback.write() = traceback; - } - - #[pyproperty(magic)] - pub fn cause(&self) -> Option { - self.cause.read().clone() - } - - #[pyproperty(name = "__cause__", setter)] - pub fn set_cause(&self, cause: Option) { - let mut c = self.cause.write(); - self.set_suppress_context(true); - *c = cause; - } - - #[pyproperty(magic)] - pub fn context(&self) -> Option { - self.context.read().clone() - } - - #[pyproperty(name = "__context__", setter)] - pub fn set_context(&self, context: Option) { - *self.context.write() = context; - } - - #[pyproperty(name = "__suppress_context__")] - fn get_suppress_context(&self) -> bool { - self.suppress_context.load() - } - - #[pyproperty(name = "__suppress_context__", setter)] - fn set_suppress_context(&self, suppress_context: bool) { - self.suppress_context.store(suppress_context); - } - - #[pymethod] - fn with_traceback(zelf: PyRef, tb: Option) -> PyResult { - *zelf.traceback.write() = tb; - Ok(zelf.as_object().clone()) - } - - #[pymethod(magic)] - fn str(&self, vm: &VirtualMachine) -> PyStrRef { - let str_args = exception_args_as_string(vm, self.args(), true); - match str_args.into_iter().exactly_one() { - Err(i) if i.len() == 0 => PyStr::from("").into_ref(vm), - Ok(s) => s, - Err(i) => PyStr::from(format!("({})", i.format(", "))).into_ref(vm), - } - } - - #[pymethod(magic)] - fn repr(zelf: PyRef, vm: &VirtualMachine) -> String { - let repr_args = exception_args_as_string(vm, zelf.args(), false); - let cls = zelf.class(); - format!("{}({})", cls.name(), repr_args.iter().format(", ")) - } -} - -fn base_exception_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - PyBaseException::tp_new(cls, args, vm) -} - pub fn chain(e1: PyResult<()>, e2: PyResult) -> PyResult { match (e1, e2) { (Err(e1), Err(e)) => { @@ -532,418 +409,115 @@ macro_rules! extend_exception { }; } -// Sorted By Hierarchy then alphabetized. +#[pyimpl(flags(BASETYPE, HAS_DICT))] +impl PyBaseException { + pub(crate) fn new(args: Vec, vm: &VirtualMachine) -> PyBaseException { + PyBaseException { + traceback: PyRwLock::new(None), + cause: PyRwLock::new(None), + context: PyRwLock::new(None), + suppress_context: AtomicCell::new(false), + args: PyRwLock::new(PyTupleRef::with_elements(args, &vm.ctx)), + } + } -define_exception! { - PySystemExit, - PyBaseException, - system_exit, - "Request to exit from the interpreter." -} -define_exception! { - PyGeneratorExit, - PyBaseException, - generator_exit, - "Request that a generator exit." -} -define_exception! { - PyKeyboardInterrupt, - PyBaseException, - keyboard_interrupt, - "Program interrupted by user." -} + #[pyslot] + pub(crate) fn tp_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + PyBaseException::new(args.args, vm).into_pyresult_with_type(vm, cls) + } -// Base `Exception` type -define_exception! { - PyException, - PyBaseException, - exception_type, - "Common base class for all non-exit exceptions." -} + #[pymethod(magic)] + pub(crate) fn init(zelf: PyRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { + *zelf.args.write() = PyTupleRef::with_elements(args.args, &vm.ctx); + Ok(()) + } -define_exception! { - PyStopIteration, - PyException, - stop_iteration, - "Signal the end from iterator.__next__()." -} -define_exception! { - PyStopAsyncIteration, - PyException, - stop_async_iteration, - "Signal the end from iterator.__anext__()." -} + pub fn get_arg(&self, idx: usize) -> Option { + self.args.read().as_slice().get(idx).cloned() + } -define_exception! { - PyArithmeticError, - PyException, - arithmetic_error, - "Base class for arithmetic errors." -} -define_exception! { - PyFloatingPointError, - PyArithmeticError, - floating_point_error, - "Floating point operation failed." -} -define_exception! { - PyOverflowError, - PyArithmeticError, - overflow_error, - "Result too large to be represented." -} -define_exception! { - PyZeroDivisionError, - PyArithmeticError, - zero_division_error, - "Second argument to a division or modulo operation was zero." -} + #[pyproperty] + pub fn args(&self) -> PyTupleRef { + self.args.read().clone() + } -define_exception! { - PyAssertionError, - PyException, - assertion_error, - "Assertion failed." -} -define_exception! { - PyAttributeError, - PyException, - attribute_error, - "Attribute not found." -} -define_exception! { - PyBufferError, - PyException, - buffer_error, - "Buffer error." -} -define_exception! { - PyEOFError, - PyException, - eof_error, - "Read beyond end of file." -} + #[pyproperty(setter)] + fn set_args(&self, args: ArgIterable, vm: &VirtualMachine) -> PyResult<()> { + let args = args.iter(vm)?.collect::>>()?; + *self.args.write() = PyTupleRef::with_elements(args, &vm.ctx); + Ok(()) + } -define_exception! { - PyImportError, - PyException, - import_error, - "Import can't find module, or can't find name in module.", - base_exception_new, - import_error_init, -} -define_exception! { - PyModuleNotFoundError, - PyImportError, - module_not_found_error, - "Module not found." -} + #[pyproperty(magic)] + pub fn traceback(&self) -> Option { + self.traceback.read().clone() + } -define_exception! { - PyLookupError, - PyException, - lookup_error, - "Base class for lookup errors." -} -define_exception! { - PyIndexError, - PyLookupError, - index_error, - "Sequence index out of range." -} -define_exception! { - PyKeyError, - PyLookupError, - key_error, - "Mapping key not found." -} + #[pyproperty(name = "__traceback__", setter)] + pub fn set_traceback(&self, traceback: Option) { + *self.traceback.write() = traceback; + } -define_exception! { - PyMemoryError, - PyException, - memory_error, - "Out of memory." -} + #[pyproperty(magic)] + pub fn cause(&self) -> Option> { + self.cause.read().clone() + } -define_exception! { - PyNameError, - PyException, - name_error, - "Name not found globally." -} -define_exception! { - PyUnboundLocalError, - PyNameError, - unbound_local_error, - "Local name referenced but not bound to a value." -} + #[pyproperty(name = "__cause__", setter)] + pub fn set_cause(&self, cause: Option>) { + let mut c = self.cause.write(); + self.set_suppress_context(true); + *c = cause; + } -// OS Errors: -define_exception! { - PyOSError, - PyException, - os_error, - "Base class for I/O related errors." -} -define_exception! { - PyBlockingIOError, - PyOSError, - blocking_io_error, - "I/O operation would block." -} -define_exception! { - PyChildProcessError, - PyOSError, - child_process_error, - "Child process error." -} -define_exception! { - PyConnectionError, - PyOSError, - connection_error, - "Connection error." -} -define_exception! { - PyBrokenPipeError, - PyConnectionError, - broken_pipe_error, - "Broken pipe." -} -define_exception! { - PyConnectionAbortedError, - PyConnectionError, - connection_aborted_error, - "Connection aborted." -} -define_exception! { - PyConnectionRefusedError, - PyConnectionError, - connection_refused_error, - "Connection refused." -} -define_exception! { - PyConnectionResetError, - PyConnectionError, - connection_reset_error, - "Connection reset." -} -define_exception! { - PyFileExistsError, - PyOSError, - file_exists_error, - "File already exists." -} -define_exception! { - PyFileNotFoundError, - PyOSError, - file_not_found_error, - "File not found." -} -define_exception! { - PyInterruptedError, - PyOSError, - interrupted_error, - "Interrupted by signal." -} -define_exception! { - PyIsADirectoryError, - PyOSError, - is_a_directory_error, - "Operation doesn't work on directories." -} -define_exception! { - PyNotADirectoryError, - PyOSError, - not_a_directory_error, - "Operation only works on directories." -} -define_exception! { - PyPermissionError, - PyOSError, - permission_error, - "Not enough permissions." -} -define_exception! { - PyProcessLookupError, - PyOSError, - process_lookup_error, - "Process not found." -} -define_exception! { - PyTimeoutError, - PyOSError, - timeout_error, - "Timeout expired." -} + #[pyproperty(magic)] + pub fn context(&self) -> Option> { + self.context.read().clone() + } -define_exception! { - PyReferenceError, - PyException, - reference_error, - "Weak ref proxy used after referent went away." -} + #[pyproperty(name = "__context__", setter)] + pub fn set_context(&self, context: Option>) { + *self.context.write() = context; + } -define_exception! { - PyRuntimeError, - PyException, - runtime_error, - "Unspecified run-time error." -} -define_exception! { - PyNotImplementedError, - PyRuntimeError, - not_implemented_error, - "Method or function hasn't been implemented yet." -} -define_exception! { - PyRecursionError, - PyRuntimeError, - recursion_error, - "Recursion limit exceeded." -} + #[pyproperty(name = "__suppress_context__")] + pub(super) fn get_suppress_context(&self) -> bool { + self.suppress_context.load() + } -define_exception! { - PySyntaxError, - PyException, - syntax_error, - "Invalid syntax." -} -define_exception! { - PyIndentationError, - PySyntaxError, - indentation_error, - "Improper indentation." -} -define_exception! { - PyTabError, - PyIndentationError, - tab_error, - "Improper mixture of spaces and tabs." -} + #[pyproperty(name = "__suppress_context__", setter)] + fn set_suppress_context(&self, suppress_context: bool) { + self.suppress_context.store(suppress_context); + } -define_exception! { - PySystemError, - PyException, - system_error, - "Internal error in the Python interpreter.\n\nPlease report this to the Python maintainer, along with the traceback,\nthe Python version, and the hardware/OS platform and version." -} + #[pymethod] + fn with_traceback(zelf: PyRef, tb: Option) -> PyResult { + *zelf.traceback.write() = tb; + Ok(zelf.as_object().clone()) + } -define_exception! { - PyTypeError, - PyException, - type_error, - "Inappropriate argument type." -} + #[pymethod(magic)] + pub(super) fn str(&self, vm: &VirtualMachine) -> PyStrRef { + let str_args = exception_args_as_string(vm, self.args(), true); + match str_args.into_iter().exactly_one() { + Err(i) if i.len() == 0 => PyStr::from("").into_ref(vm), + Ok(s) => s, + Err(i) => PyStr::from(format!("({})", i.format(", "))).into_ref(vm), + } + } -define_exception! { - PyValueError, - PyException, - value_error, - "Inappropriate argument value (of correct type)." -} -define_exception! { - PyUnicodeError, - PyValueError, - unicode_error, - "Unicode related error." -} -define_exception! { - PyUnicodeDecodeError, - PyUnicodeError, - unicode_decode_error, - "Unicode decoding error." -} -define_exception! { - PyUnicodeEncodeError, - PyUnicodeError, - unicode_encode_error, - "Unicode encoding error." -} -define_exception! { - PyUnicodeTranslateError, - PyUnicodeError, - unicode_translate_error, - "Unicode translation error." -} - -#[cfg(feature = "jit")] -define_exception! { - PyJitError, - PyException, - jit_error, - "JIT error." -} - -// Warnings -define_exception! { - PyWarning, - PyException, - warning, - "Base class for warning categories." -} -define_exception! { - PyDeprecationWarning, - PyWarning, - deprecation_warning, - "Base class for warnings about deprecated features." -} -define_exception! { - PyPendingDeprecationWarning, - PyWarning, - pending_deprecation_warning, - "Base class for warnings about features which will be deprecated\nin the future." -} -define_exception! { - PyRuntimeWarning, - PyWarning, - runtime_warning, - "Base class for warnings about dubious runtime behavior." -} -define_exception! { - PySyntaxWarning, - PyWarning, - syntax_warning, - "Base class for warnings about dubious syntax." -} -define_exception! { - PyUserWarning, - PyWarning, - user_warning, - "Base class for warnings generated by user code." -} -define_exception! { - PyFutureWarning, - PyWarning, - future_warning, - "Base class for warnings about constructs that will change semantically\nin the future." -} -define_exception! { - PyImportWarning, - PyWarning, - import_warning, - "Base class for warnings about probable mistakes in module imports." -} -define_exception! { - PyUnicodeWarning, - PyWarning, - unicode_warning, - "Base class for warnings about Unicode related problems, mostly\nrelated to conversion problems." -} -define_exception! { - PyBytesWarning, - PyWarning, - bytes_warning, - "Base class for warnings about bytes and buffer related problems, mostly\nrelated to conversion from str or comparing to str." -} -define_exception! { - PyResourceWarning, - PyWarning, - resource_warning, - "Base class for warnings about resource usage." + #[pymethod(magic)] + fn repr(zelf: PyRef, vm: &VirtualMachine) -> String { + let repr_args = exception_args_as_string(vm, zelf.args(), false); + let cls = zelf.class(); + format!("{}({})", cls.name(), repr_args.iter().format(", ")) + } } impl ExceptionZoo { pub(crate) fn init() -> Self { + use self::types::*; + let base_exception_type = PyBaseException::init_bare_type().clone(); // Sorted By Hierarchy then alphabetized. @@ -1104,6 +678,8 @@ impl ExceptionZoo { // TODO: remove it after fixing `errno` / `winerror` problem #[allow(clippy::redundant_clone)] pub fn extend(ctx: &PyContext) { + use self::types::*; + let excs = &ctx.exceptions; PyBaseException::extend_class(ctx, &excs.base_exception_type); @@ -1257,26 +833,7 @@ impl ExceptionZoo { } } -fn import_error_init( - zelf: PyRef, - args: FuncArgs, - vm: &VirtualMachine, -) -> PyResult<()> { - let exc_self = zelf.into_object(); - vm.set_attr( - &exc_self, - "name", - vm.unwrap_or_none(args.kwargs.get("name").cloned()), - )?; - vm.set_attr( - &exc_self, - "path", - vm.unwrap_or_none(args.kwargs.get("path").cloned()), - )?; - Ok(()) -} - -fn none_getter(_obj: PyObjectRef, vm: &VirtualMachine) -> PyNoneRef { +fn none_getter(_obj: PyObjectRef, vm: &VirtualMachine) -> PyRef { vm.ctx.none.clone() } @@ -1392,3 +949,462 @@ impl IntoPyException for widestring::NulError { cstring_error(vm) } } + +pub(super) mod types { + use crate::common::lock::PyRwLock; + use crate::{ + builtins::{traceback::PyTracebackRef, PyTupleRef, PyTypeRef}, + function::FuncArgs, + PyRef, PyResult, VirtualMachine, + }; + use crossbeam_utils::atomic::AtomicCell; + + // This module is designed to be used as `use builtins::*;`. + // Do not add any pub symbols not included in builtins module. + // `PyBaseExceptionRef` is the only exception. + + pub type PyBaseExceptionRef = PyRef; + + // Sorted By Hierarchy then alphabetized. + + #[pyclass(module = false, name = "BaseException")] + pub struct PyBaseException { + pub(super) traceback: PyRwLock>, + pub(super) cause: PyRwLock>>, + pub(super) context: PyRwLock>>, + pub(super) suppress_context: AtomicCell, + pub(super) args: PyRwLock, + } + + define_exception! { + PySystemExit, + PyBaseException, + system_exit, + "Request to exit from the interpreter." + } + define_exception! { + PyGeneratorExit, + PyBaseException, + generator_exit, + "Request that a generator exit." + } + define_exception! { + PyKeyboardInterrupt, + PyBaseException, + keyboard_interrupt, + "Program interrupted by user." + } + + // Base `Exception` type + define_exception! { + PyException, + PyBaseException, + exception_type, + "Common base class for all non-exit exceptions." + } + + define_exception! { + PyStopIteration, + PyException, + stop_iteration, + "Signal the end from iterator.__next__()." + } + define_exception! { + PyStopAsyncIteration, + PyException, + stop_async_iteration, + "Signal the end from iterator.__anext__()." + } + + define_exception! { + PyArithmeticError, + PyException, + arithmetic_error, + "Base class for arithmetic errors." + } + define_exception! { + PyFloatingPointError, + PyArithmeticError, + floating_point_error, + "Floating point operation failed." + } + define_exception! { + PyOverflowError, + PyArithmeticError, + overflow_error, + "Result too large to be represented." + } + define_exception! { + PyZeroDivisionError, + PyArithmeticError, + zero_division_error, + "Second argument to a division or modulo operation was zero." + } + + define_exception! { + PyAssertionError, + PyException, + assertion_error, + "Assertion failed." + } + define_exception! { + PyAttributeError, + PyException, + attribute_error, + "Attribute not found." + } + define_exception! { + PyBufferError, + PyException, + buffer_error, + "Buffer error." + } + define_exception! { + PyEOFError, + PyException, + eof_error, + "Read beyond end of file." + } + + define_exception! { + PyImportError, + PyException, + import_error, + "Import can't find module, or can't find name in module.", + base_exception_new, + import_error_init, + } + + fn base_exception_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + PyBaseException::tp_new(cls, args, vm) + } + + fn import_error_init( + zelf: PyRef, + args: FuncArgs, + vm: &VirtualMachine, + ) -> PyResult<()> { + let exc_self = zelf.into_object(); + vm.set_attr( + &exc_self, + "name", + vm.unwrap_or_none(args.kwargs.get("name").cloned()), + )?; + vm.set_attr( + &exc_self, + "path", + vm.unwrap_or_none(args.kwargs.get("path").cloned()), + )?; + Ok(()) + } + + define_exception! { + PyModuleNotFoundError, + PyImportError, + module_not_found_error, + "Module not found." + } + + define_exception! { + PyLookupError, + PyException, + lookup_error, + "Base class for lookup errors." + } + define_exception! { + PyIndexError, + PyLookupError, + index_error, + "Sequence index out of range." + } + define_exception! { + PyKeyError, + PyLookupError, + key_error, + "Mapping key not found." + } + + define_exception! { + PyMemoryError, + PyException, + memory_error, + "Out of memory." + } + + define_exception! { + PyNameError, + PyException, + name_error, + "Name not found globally." + } + define_exception! { + PyUnboundLocalError, + PyNameError, + unbound_local_error, + "Local name referenced but not bound to a value." + } + + // OS Errors: + define_exception! { + PyOSError, + PyException, + os_error, + "Base class for I/O related errors." + } + define_exception! { + PyBlockingIOError, + PyOSError, + blocking_io_error, + "I/O operation would block." + } + define_exception! { + PyChildProcessError, + PyOSError, + child_process_error, + "Child process error." + } + define_exception! { + PyConnectionError, + PyOSError, + connection_error, + "Connection error." + } + define_exception! { + PyBrokenPipeError, + PyConnectionError, + broken_pipe_error, + "Broken pipe." + } + define_exception! { + PyConnectionAbortedError, + PyConnectionError, + connection_aborted_error, + "Connection aborted." + } + define_exception! { + PyConnectionRefusedError, + PyConnectionError, + connection_refused_error, + "Connection refused." + } + define_exception! { + PyConnectionResetError, + PyConnectionError, + connection_reset_error, + "Connection reset." + } + define_exception! { + PyFileExistsError, + PyOSError, + file_exists_error, + "File already exists." + } + define_exception! { + PyFileNotFoundError, + PyOSError, + file_not_found_error, + "File not found." + } + define_exception! { + PyInterruptedError, + PyOSError, + interrupted_error, + "Interrupted by signal." + } + define_exception! { + PyIsADirectoryError, + PyOSError, + is_a_directory_error, + "Operation doesn't work on directories." + } + define_exception! { + PyNotADirectoryError, + PyOSError, + not_a_directory_error, + "Operation only works on directories." + } + define_exception! { + PyPermissionError, + PyOSError, + permission_error, + "Not enough permissions." + } + define_exception! { + PyProcessLookupError, + PyOSError, + process_lookup_error, + "Process not found." + } + define_exception! { + PyTimeoutError, + PyOSError, + timeout_error, + "Timeout expired." + } + + define_exception! { + PyReferenceError, + PyException, + reference_error, + "Weak ref proxy used after referent went away." + } + + define_exception! { + PyRuntimeError, + PyException, + runtime_error, + "Unspecified run-time error." + } + define_exception! { + PyNotImplementedError, + PyRuntimeError, + not_implemented_error, + "Method or function hasn't been implemented yet." + } + define_exception! { + PyRecursionError, + PyRuntimeError, + recursion_error, + "Recursion limit exceeded." + } + + define_exception! { + PySyntaxError, + PyException, + syntax_error, + "Invalid syntax." + } + define_exception! { + PyIndentationError, + PySyntaxError, + indentation_error, + "Improper indentation." + } + define_exception! { + PyTabError, + PyIndentationError, + tab_error, + "Improper mixture of spaces and tabs." + } + + define_exception! { + PySystemError, + PyException, + system_error, + "Internal error in the Python interpreter.\n\nPlease report this to the Python maintainer, along with the traceback,\nthe Python version, and the hardware/OS platform and version." + } + + define_exception! { + PyTypeError, + PyException, + type_error, + "Inappropriate argument type." + } + + define_exception! { + PyValueError, + PyException, + value_error, + "Inappropriate argument value (of correct type)." + } + define_exception! { + PyUnicodeError, + PyValueError, + unicode_error, + "Unicode related error." + } + define_exception! { + PyUnicodeDecodeError, + PyUnicodeError, + unicode_decode_error, + "Unicode decoding error." + } + define_exception! { + PyUnicodeEncodeError, + PyUnicodeError, + unicode_encode_error, + "Unicode encoding error." + } + define_exception! { + PyUnicodeTranslateError, + PyUnicodeError, + unicode_translate_error, + "Unicode translation error." + } + + #[cfg(feature = "jit")] + define_exception! { + PyJitError, + PyException, + jit_error, + "JIT error." + } + + // Warnings + define_exception! { + PyWarning, + PyException, + warning, + "Base class for warning categories." + } + define_exception! { + PyDeprecationWarning, + PyWarning, + deprecation_warning, + "Base class for warnings about deprecated features." + } + define_exception! { + PyPendingDeprecationWarning, + PyWarning, + pending_deprecation_warning, + "Base class for warnings about features which will be deprecated\nin the future." + } + define_exception! { + PyRuntimeWarning, + PyWarning, + runtime_warning, + "Base class for warnings about dubious runtime behavior." + } + define_exception! { + PySyntaxWarning, + PyWarning, + syntax_warning, + "Base class for warnings about dubious syntax." + } + define_exception! { + PyUserWarning, + PyWarning, + user_warning, + "Base class for warnings generated by user code." + } + define_exception! { + PyFutureWarning, + PyWarning, + future_warning, + "Base class for warnings about constructs that will change semantically\nin the future." + } + define_exception! { + PyImportWarning, + PyWarning, + import_warning, + "Base class for warnings about probable mistakes in module imports." + } + define_exception! { + PyUnicodeWarning, + PyWarning, + unicode_warning, + "Base class for warnings about Unicode related problems, mostly\nrelated to conversion problems." + } + define_exception! { + PyBytesWarning, + PyWarning, + bytes_warning, + "Base class for warnings about bytes and buffer related problems, mostly\nrelated to conversion from str or comparing to str." + } + define_exception! { + PyResourceWarning, + PyWarning, + resource_warning, + "Base class for warnings about resource usage." + } +} diff --git a/vm/src/format.rs b/vm/src/format.rs index 57ac71c6d..8cf1c5a1d 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -1,6 +1,6 @@ -use crate::builtins::{self, PyStrRef}; +use crate::builtins::{self, PyBaseExceptionRef, PyStrRef}; use crate::common::float_ops; -use crate::exceptions::{IntoPyException, PyBaseExceptionRef}; +use crate::exceptions::IntoPyException; use crate::function::FuncArgs; use crate::vm::VirtualMachine; use crate::{ItemProtocol, PyObjectRef, PyResult, TypeProtocol}; diff --git a/vm/src/frame.rs b/vm/src/frame.rs index 411f32912..dc3ac2a01 100644 --- a/vm/src/frame.rs +++ b/vm/src/frame.rs @@ -1,5 +1,6 @@ use crate::common::{boxvec::BoxVec, lock::PyMutex}; use crate::{ + builtins::PyBaseExceptionRef, builtins::{ self, asyncgenerator::PyAsyncGenWrappedValue, @@ -13,7 +14,7 @@ use crate::{ }, bytecode, coroutine::Coro, - exceptions::{self, ExceptionCtor, PyBaseExceptionRef}, + exceptions::{self, ExceptionCtor}, function::FuncArgs, iterator, scope::Scope, diff --git a/vm/src/function.rs b/vm/src/function.rs index 6daf5f369..c1365ee6d 100644 --- a/vm/src/function.rs +++ b/vm/src/function.rs @@ -4,7 +4,7 @@ mod byteslike; use self::OptionalArg::*; use crate::builtins::pytype::PyTypeRef; use crate::builtins::tuple::PyTupleRef; -use crate::exceptions::PyBaseExceptionRef; +use crate::builtins::PyBaseExceptionRef; use crate::vm::VirtualMachine; use crate::{ IntoPyObject, IntoPyResult, PyObjectRef, PyRef, PyResult, PyThreadingConstraint, PyValue, diff --git a/vm/src/import.rs b/vm/src/import.rs index 4e42daf2e..de64d6cd5 100644 --- a/vm/src/import.rs +++ b/vm/src/import.rs @@ -5,10 +5,10 @@ use rand::Rng; use crate::builtins::code::CodeObject; use crate::builtins::traceback::{PyTraceback, PyTracebackRef}; +use crate::builtins::PyBaseExceptionRef; use crate::builtins::{code, list}; #[cfg(feature = "rustpython-compiler")] use crate::compile; -use crate::exceptions::PyBaseExceptionRef; use crate::scope::Scope; use crate::version::get_git_revision; use crate::vm::{InitParameter, VirtualMachine}; diff --git a/vm/src/iterator.rs b/vm/src/iterator.rs index ddd514a1f..2d8406356 100644 --- a/vm/src/iterator.rs +++ b/vm/src/iterator.rs @@ -4,7 +4,7 @@ use crate::builtins::int::{self, PyInt}; use crate::builtins::iter::PySequenceIterator; -use crate::exceptions::PyBaseExceptionRef; +use crate::builtins::PyBaseExceptionRef; use crate::vm::VirtualMachine; use crate::{IdProtocol, PyObjectRef, PyResult, PyValue, TypeProtocol}; use num_traits::Signed; diff --git a/vm/src/py_io.rs b/vm/src/py_io.rs index 571d7e8c8..520f2631e 100644 --- a/vm/src/py_io.rs +++ b/vm/src/py_io.rs @@ -1,7 +1,7 @@ use crate::builtins::bytes::PyBytes; use crate::builtins::pystr::PyStr; +use crate::builtins::PyBaseExceptionRef; use crate::common::ascii; -use crate::exceptions::PyBaseExceptionRef; use crate::VirtualMachine; use crate::{PyObjectRef, PyResult}; use std::{fmt, io, ops}; diff --git a/vm/src/pyobject.rs b/vm/src/pyobject.rs index a6d6f6ab7..47d55fb14 100644 --- a/vm/src/pyobject.rs +++ b/vm/src/pyobject.rs @@ -5,6 +5,7 @@ use crate::common::{ }; pub use crate::pyobjectrc::{PyObject, PyObjectRef, PyObjectWeak, PyRef, PyWeakRef}; use crate::{ + builtins::PyBaseExceptionRef, builtins::{ builtinfunc::PyNativeFuncDef, bytearray, bytes, @@ -17,7 +18,7 @@ use crate::{ PyNone, PyNotImplemented, PyStaticMethod, PyTuple, PyTupleRef, PyType, PyTypeRef, }, dictdatatype::Dict, - exceptions::{self, PyBaseExceptionRef}, + exceptions, function::{IntoFuncArgs, IntoPyNativeFunc}, slots::{PyTpFlags, PyTypeSlots}, types::{create_type_with_slots, TypeZoo}, diff --git a/vm/src/stdlib/codecs.rs b/vm/src/stdlib/codecs.rs index 1f9e16f3e..822859687 100644 --- a/vm/src/stdlib/codecs.rs +++ b/vm/src/stdlib/codecs.rs @@ -4,9 +4,8 @@ pub(crate) use _codecs::make_module; mod _codecs { use crate::common::encodings; use crate::{ - builtins::{PyBytes, PyBytesRef, PyStr, PyStrRef, PyTuple}, + builtins::{PyBaseExceptionRef, PyBytes, PyBytesRef, PyStr, PyStrRef, PyTuple}, codecs, - exceptions::PyBaseExceptionRef, function::{ArgBytesLike, FuncArgs}, IdProtocol, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, }; diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index ef7531b2e..29fe956a4 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -78,11 +78,13 @@ mod _io { }; use crate::{ builtins::{ - PyByteArray, PyBytes, PyBytesRef, PyMemoryView, PyStr, PyStrRef, PyType, PyTypeRef, + PyBaseExceptionRef, PyByteArray, PyBytes, PyBytesRef, PyMemoryView, PyStr, PyStrRef, + PyType, PyTypeRef, + }, + exceptions, + function::{ + ArgBytesLike, ArgIterable, ArgMemoryBuffer, FuncArgs, OptionalArg, OptionalOption, }, - exceptions::{self, PyBaseExceptionRef}, - function::{ArgBytesLike, ArgMemoryBuffer}, - function::{ArgIterable, FuncArgs, OptionalArg, OptionalOption}, protocol::{BufferInternal, BufferOptions, PyBuffer, ResizeGuard}, slots::{Iterable, PyIter, SlotConstructor}, utils::Either, diff --git a/vm/src/stdlib/json.rs b/vm/src/stdlib/json.rs index 29f908abc..daaf7e8b9 100644 --- a/vm/src/stdlib/json.rs +++ b/vm/src/stdlib/json.rs @@ -5,8 +5,8 @@ mod machinery; mod _json { use super::machinery; use crate::{ + builtins::PyBaseExceptionRef, builtins::{PyStrRef, PyTypeRef}, - exceptions::PyBaseExceptionRef, function::{FuncArgs, OptionalArg}, iterator, slots::{Callable, SlotConstructor}, diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index b17149fc4..b03940817 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -1,8 +1,9 @@ use super::errno::errors; use crate::crt_fd::Fd; use crate::{ + builtins::PyBaseExceptionRef, builtins::{PyBytes, PyBytesRef, PyInt, PySet, PyStr, PyStrRef}, - exceptions::{IntoPyException, PyBaseExceptionRef}, + exceptions::IntoPyException, function::{ArgumentError, FromArgs, FuncArgs}, protocol::PyBuffer, IntoPyObject, PyObjectRef, PyResult, PyValue, TryFromBorrowedObject, TryFromObject, diff --git a/vm/src/stdlib/pystruct.rs b/vm/src/stdlib/pystruct.rs index 661e75eb5..501391ea3 100644 --- a/vm/src/stdlib/pystruct.rs +++ b/vm/src/stdlib/pystruct.rs @@ -13,11 +13,10 @@ pub(crate) mod _struct { use crate::{ builtins::{ - bytes::PyBytesRef, float, pybool::IntoPyBool, pystr::PyStr, pystr::PyStrRef, - pytype::PyTypeRef, tuple::PyTupleRef, + float, IntoPyBool, PyBaseExceptionRef, PyBytesRef, PyStr, PyStrRef, PyTupleRef, + PyTypeRef, }, common::str::wchar_t, - exceptions::PyBaseExceptionRef, function::{ArgBytesLike, ArgMemoryBuffer, PosArgs}, slots::{IteratorIterable, PyIter, SlotConstructor}, utils::Either, diff --git a/vm/src/stdlib/socket.rs b/vm/src/stdlib/socket.rs index 347511652..199ab9344 100644 --- a/vm/src/stdlib/socket.rs +++ b/vm/src/stdlib/socket.rs @@ -1,7 +1,7 @@ use crate::common::lock::{PyMappedRwLockReadGuard, PyRwLock, PyRwLockReadGuard}; use crate::{ - builtins::{PyStrRef, PyTupleRef, PyTypeRef}, - exceptions::{IntoPyException, PyBaseExceptionRef}, + builtins::{PyBaseExceptionRef, PyStrRef, PyTupleRef, PyTypeRef}, + exceptions::IntoPyException, function::{ArgBytesLike, ArgMemoryBuffer, FuncArgs, OptionalArg, OptionalOption}, utils::{Either, ToCString}, IntoPyObject, PyClassImpl, PyObjectRef, PyResult, PyValue, TryFromBorrowedObject, diff --git a/vm/src/stdlib/ssl.rs b/vm/src/stdlib/ssl.rs index 51a73be27..2e1eadce5 100644 --- a/vm/src/stdlib/ssl.rs +++ b/vm/src/stdlib/ssl.rs @@ -4,10 +4,9 @@ use crate::common::{ lock::{PyRwLock, PyRwLockWriteGuard}, }; use crate::{ - builtins::{PyStrRef, PyType, PyTypeRef, PyWeak}, - exceptions::{self, IntoPyException, PyBaseException, PyBaseExceptionRef}, - function::{ArgBytesLike, ArgMemoryBuffer, ArgStrOrBytesLike}, - function::{ArgCallable, OptionalArg}, + builtins::{PyBaseException, PyBaseExceptionRef, PyStrRef, PyType, PyTypeRef, PyWeak}, + exceptions::{self, IntoPyException}, + function::{ArgBytesLike, ArgCallable, ArgMemoryBuffer, ArgStrOrBytesLike, OptionalArg}, slots::SlotConstructor, stdlib::os::PyPathLike, types::create_simple_type, diff --git a/vm/src/stdlib/termios.rs b/vm/src/stdlib/termios.rs index 2e2892245..acc9b76b5 100644 --- a/vm/src/stdlib/termios.rs +++ b/vm/src/stdlib/termios.rs @@ -3,8 +3,8 @@ pub(crate) use self::termios::make_module; #[pymodule] mod termios { use crate::{ + builtins::PyBaseExceptionRef, builtins::{PyBytes, PyInt, PyListRef, PyTypeRef}, - exceptions::PyBaseExceptionRef, IntoPyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, }; use std::convert::TryFrom; diff --git a/vm/src/stdlib/zlib.rs b/vm/src/stdlib/zlib.rs index c8da644ce..77ff59965 100644 --- a/vm/src/stdlib/zlib.rs +++ b/vm/src/stdlib/zlib.rs @@ -4,8 +4,7 @@ pub(crate) use decl::make_module; mod decl { use crate::common::lock::PyMutex; use crate::{ - builtins::{PyBytes, PyBytesRef, PyIntRef, PyTypeRef}, - exceptions::PyBaseExceptionRef, + builtins::{PyBaseExceptionRef, PyBytes, PyBytesRef, PyIntRef, PyTypeRef}, function::{ArgBytesLike, OptionalArg}, types::create_simple_type, IntoPyRef, PyResult, PyValue, VirtualMachine, diff --git a/vm/src/vm.rs b/vm/src/vm.rs index a8ff07e5e..9c14976e8 100644 --- a/vm/src/vm.rs +++ b/vm/src/vm.rs @@ -14,10 +14,11 @@ use crate::{ tuple::{PyTuple, PyTupleRef, PyTupleTyped}, PyDictRef, PyInt, PyIntRef, PyList, PyModule, PyStr, PyStrRef, PyTypeRef, }, + builtins::{PyBaseException, PyBaseExceptionRef}, bytecode, codecs::CodecsRegistry, common::{ascii, hash::HashSecret, lock::PyMutex, rc::PyRc}, - exceptions::{self, PyBaseException, PyBaseExceptionRef}, + exceptions, frame::{ExecutionResult, Frame, FrameRef}, frozen, function::{FuncArgs, IntoFuncArgs}, diff --git a/wasm/lib/src/convert.rs b/wasm/lib/src/convert.rs index 3744ef9ed..75521b57f 100644 --- a/wasm/lib/src/convert.rs +++ b/wasm/lib/src/convert.rs @@ -1,19 +1,16 @@ -use js_sys::{Array, ArrayBuffer, Object, Promise, Reflect, SyntaxError, Uint8Array}; -use wasm_bindgen::{closure::Closure, prelude::*, JsCast}; - -use rustpython_parser::error::ParseErrorType; -use rustpython_vm::compile::{CompileError, CompileErrorType}; -use rustpython_vm::exceptions::PyBaseExceptionRef; -use rustpython_vm::function::ArgBytesLike; -use rustpython_vm::function::FuncArgs; -use rustpython_vm::VirtualMachine; -use rustpython_vm::{exceptions, py_serde}; -use rustpython_vm::{ - ItemProtocol, PyObjectRef, PyResult, PyValue, TryFromBorrowedObject, TypeProtocol, -}; - use crate::js_module; use crate::vm_class::{stored_vm_from_wasm, WASMVirtualMachine}; +use js_sys::{Array, ArrayBuffer, Object, Promise, Reflect, SyntaxError, Uint8Array}; +use rustpython_parser::error::ParseErrorType; +use rustpython_vm::{ + builtins::PyBaseExceptionRef, + compile::{CompileError, CompileErrorType}, + exceptions, + function::{ArgBytesLike, FuncArgs}, + py_serde, ItemProtocol, PyObjectRef, PyResult, PyValue, TryFromBorrowedObject, TypeProtocol, + VirtualMachine, +}; +use wasm_bindgen::{closure::Closure, prelude::*, JsCast}; #[wasm_bindgen(inline_js = r" export class PyError extends Error { diff --git a/wasm/lib/src/js_module.rs b/wasm/lib/src/js_module.rs index 8e0ca7c21..a99efdd63 100644 --- a/wasm/lib/src/js_module.rs +++ b/wasm/lib/src/js_module.rs @@ -6,8 +6,8 @@ use std::{cell, fmt, future}; use wasm_bindgen::{closure::Closure, prelude::*, JsCast}; use wasm_bindgen_futures::{future_to_promise, JsFuture}; +use rustpython_vm::builtins::PyBaseExceptionRef; use rustpython_vm::builtins::{PyFloatRef, PyStrRef, PyTypeRef}; -use rustpython_vm::exceptions::PyBaseExceptionRef; use rustpython_vm::function::{OptionalArg, OptionalOption, PosArgs}; use rustpython_vm::slots::{IteratorIterable, PyIter}; use rustpython_vm::types::create_simple_type; From d2692554e49b25ead74052720ff49fc35aabf9f6 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Thu, 30 Sep 2021 01:22:27 +0900 Subject: [PATCH 2/2] clean up imports --- vm/src/builtins/function/jitfunc.rs | 15 ++++++--------- vm/src/codecs.rs | 12 ++++++------ vm/src/coroutine.rs | 15 +++++++-------- vm/src/format.rs | 13 +++++++------ vm/src/function.rs | 7 ++----- vm/src/import.rs | 22 ++++++++++------------ vm/src/py_io.rs | 11 +++++------ 7 files changed, 43 insertions(+), 52 deletions(-) diff --git a/vm/src/builtins/function/jitfunc.rs b/vm/src/builtins/function/jitfunc.rs index 9c3623742..5bd7159a7 100644 --- a/vm/src/builtins/function/jitfunc.rs +++ b/vm/src/builtins/function/jitfunc.rs @@ -1,12 +1,9 @@ -use crate::builtins::dict::PyDictRef; -use crate::builtins::function::{PyFunction, PyFunctionRef}; -use crate::builtins::PyBaseExceptionRef; -use crate::builtins::{float, int, pybool, PyStrRef}; -use crate::bytecode::CodeFlags; -use crate::function::FuncArgs; -use crate::VirtualMachine; use crate::{ - IdProtocol, IntoPyObject, ItemProtocol, PyObjectRef, PyResult, TryFromObject, TypeProtocol, + builtins::{float, int, pybool, PyBaseExceptionRef, PyDictRef, PyFunction, PyStrRef}, + bytecode::CodeFlags, + function::FuncArgs, + IdProtocol, IntoPyObject, ItemProtocol, PyObjectRef, PyRef, PyResult, TryFromObject, + TypeProtocol, VirtualMachine, }; use num_traits::ToPrimitive; use rustpython_jit::{AbiValue, Args, CompiledCode, JitArgumentError, JitType}; @@ -66,7 +63,7 @@ fn get_jit_arg_type(dict: &PyDictRef, name: &str, vm: &VirtualMachine) -> PyResu } } -pub fn get_jit_arg_types(func: &PyFunctionRef, vm: &VirtualMachine) -> PyResult> { +pub fn get_jit_arg_types(func: &PyRef, vm: &VirtualMachine) -> PyResult> { let arg_names = func.code.arg_names(); if func diff --git a/vm/src/codecs.rs b/vm/src/codecs.rs index b5a7dc795..be7e16465 100644 --- a/vm/src/codecs.rs +++ b/vm/src/codecs.rs @@ -1,13 +1,13 @@ +use crate::{ + builtins::{PyBaseExceptionRef, PyBytesRef, PyStr, PyStrRef, PyTuple, PyTupleRef}, + common::{ascii, lock::PyRwLock}, + IntoPyObject, PyContext, PyObjectRef, PyResult, PyValue, TryFromObject, TypeProtocol, + VirtualMachine, +}; use std::borrow::Cow; use std::collections::HashMap; use std::ops::Range; -use crate::builtins::PyBaseExceptionRef; -use crate::builtins::{PyBytesRef, PyStr, PyStrRef, PyTuple, PyTupleRef}; -use crate::common::{ascii, lock::PyRwLock}; -use crate::VirtualMachine; -use crate::{IntoPyObject, PyContext, PyObjectRef, PyResult, PyValue, TryFromObject, TypeProtocol}; - pub struct CodecsRegistry { inner: PyRwLock, } diff --git a/vm/src/coroutine.rs b/vm/src/coroutine.rs index 3db3d190c..5716e0ad7 100644 --- a/vm/src/coroutine.rs +++ b/vm/src/coroutine.rs @@ -1,11 +1,10 @@ -use crate::builtins::PyBaseExceptionRef; -use crate::builtins::{PyStrRef, PyTypeRef}; -use crate::exceptions; -use crate::frame::{ExecutionResult, FrameRef}; -use crate::VirtualMachine; -use crate::{PyObjectRef, PyResult, TypeProtocol}; - -use crate::common::lock::PyMutex; +use crate::{ + builtins::{PyBaseExceptionRef, PyStrRef, PyTypeRef}, + common::lock::PyMutex, + exceptions, + frame::{ExecutionResult, FrameRef}, + PyObjectRef, PyResult, TypeProtocol, VirtualMachine, +}; use crossbeam_utils::atomic::AtomicCell; #[derive(Debug, PartialEq, Clone, Copy)] diff --git a/vm/src/format.rs b/vm/src/format.rs index 8cf1c5a1d..ddbda3ee9 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -1,9 +1,10 @@ -use crate::builtins::{self, PyBaseExceptionRef, PyStrRef}; -use crate::common::float_ops; -use crate::exceptions::IntoPyException; -use crate::function::FuncArgs; -use crate::vm::VirtualMachine; -use crate::{ItemProtocol, PyObjectRef, PyResult, TypeProtocol}; +use crate::{ + builtins::{self, PyBaseExceptionRef, PyStrRef}, + common::float_ops, + exceptions::IntoPyException, + function::FuncArgs, + ItemProtocol, PyObjectRef, PyResult, TypeProtocol, VirtualMachine, +}; use itertools::{Itertools, PeekingNext}; use num_bigint::{BigInt, Sign}; use num_traits::cast::ToPrimitive; diff --git a/vm/src/function.rs b/vm/src/function.rs index c1365ee6d..af461ff3a 100644 --- a/vm/src/function.rs +++ b/vm/src/function.rs @@ -2,13 +2,10 @@ mod argument; mod byteslike; use self::OptionalArg::*; -use crate::builtins::pytype::PyTypeRef; -use crate::builtins::tuple::PyTupleRef; -use crate::builtins::PyBaseExceptionRef; -use crate::vm::VirtualMachine; use crate::{ + builtins::{PyBaseExceptionRef, PyTupleRef, PyTypeRef}, IntoPyObject, IntoPyResult, PyObjectRef, PyRef, PyResult, PyThreadingConstraint, PyValue, - TryFromObject, TypeProtocol, + TryFromObject, TypeProtocol, VirtualMachine, }; use indexmap::IndexMap; use itertools::Itertools; diff --git a/vm/src/import.rs b/vm/src/import.rs index de64d6cd5..4af056e98 100644 --- a/vm/src/import.rs +++ b/vm/src/import.rs @@ -1,18 +1,16 @@ /* * Import mechanics */ -use rand::Rng; - -use crate::builtins::code::CodeObject; -use crate::builtins::traceback::{PyTraceback, PyTracebackRef}; -use crate::builtins::PyBaseExceptionRef; -use crate::builtins::{code, list}; #[cfg(feature = "rustpython-compiler")] use crate::compile; -use crate::scope::Scope; -use crate::version::get_git_revision; -use crate::vm::{InitParameter, VirtualMachine}; -use crate::{ItemProtocol, PyResult, PyValue, TryFromObject, TypeProtocol}; +use crate::{ + builtins::{code, code::CodeObject, list, traceback::PyTraceback, PyBaseExceptionRef}, + scope::Scope, + version::get_git_revision, + vm::{InitParameter, VirtualMachine}, + ItemProtocol, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, +}; +use rand::Rng; pub(crate) fn init_importlib( vm: &mut VirtualMachine, @@ -146,9 +144,9 @@ pub fn import_codeobj( fn remove_importlib_frames_inner( vm: &VirtualMachine, - tb: Option, + tb: Option>, always_trim: bool, -) -> (Option, bool) { +) -> (Option>, bool) { let traceback = if let Some(tb) = tb { tb } else { diff --git a/vm/src/py_io.rs b/vm/src/py_io.rs index 520f2631e..dd267539f 100644 --- a/vm/src/py_io.rs +++ b/vm/src/py_io.rs @@ -1,9 +1,8 @@ -use crate::builtins::bytes::PyBytes; -use crate::builtins::pystr::PyStr; -use crate::builtins::PyBaseExceptionRef; -use crate::common::ascii; -use crate::VirtualMachine; -use crate::{PyObjectRef, PyResult}; +use crate::{ + builtins::{PyBaseExceptionRef, PyBytes, PyStr}, + common::ascii, + PyObjectRef, PyResult, VirtualMachine, +}; use std::{fmt, io, ops}; pub trait Write {