forked from Rust-related/RustPython
Merge pull request #3717 from youknowone/exception-ref
ExceptionZoo holds static ref
This commit is contained in:
@@ -387,11 +387,11 @@ class ClassDefVisitor(EmitVisitor):
|
||||
self.emit("#[pyimpl(flags(HAS_DICT, BASETYPE))]", depth)
|
||||
self.emit(f"impl {structname} {{", depth)
|
||||
self.emit(f"#[extend_class]", depth + 1)
|
||||
self.emit("fn extend_class_with_fields(ctx: &Context, class: &PyTypeRef) {", depth + 1)
|
||||
self.emit("fn extend_class_with_fields(ctx: &Context, class: &'static Py<PyType>) {", depth + 1)
|
||||
fields = ",".join(f"ctx.new_str(ascii!({json.dumps(f.name)})).into()" for f in fields)
|
||||
self.emit(f'class.set_attr(interned!(ctx, _fields), ctx.new_list(vec![{fields}]).into());', depth + 2)
|
||||
self.emit(f'class.set_attr(identifier!(ctx, _fields), ctx.new_list(vec![{fields}]).into());', depth + 2)
|
||||
attrs = ",".join(f"ctx.new_str(ascii!({json.dumps(attr.name)})).into()" for attr in attrs)
|
||||
self.emit(f'class.set_attr(interned!(ctx, _attributes), ctx.new_list(vec![{attrs}]).into());', depth + 2)
|
||||
self.emit(f'class.set_attr(identifier!(ctx, _attributes), ctx.new_list(vec![{attrs}]).into());', depth + 2)
|
||||
self.emit("}", depth + 1)
|
||||
self.emit("}", depth)
|
||||
|
||||
@@ -481,7 +481,7 @@ class TraitImplVisitor(EmitVisitor):
|
||||
|
||||
def make_node(self, variant, fields, depth):
|
||||
lines = []
|
||||
self.emit(f"let _node = AstNode.into_ref_with_type(_vm, Node{variant}::static_type().clone()).unwrap();", depth)
|
||||
self.emit(f"let _node = AstNode.into_ref_with_type(_vm, Node{variant}::static_type().to_owned()).unwrap();", depth)
|
||||
if fields:
|
||||
self.emit("let _dict = _node.as_object().dict().unwrap();", depth)
|
||||
for f in fields:
|
||||
|
||||
@@ -3,7 +3,7 @@ use criterion::{
|
||||
Criterion, Throughput,
|
||||
};
|
||||
use rustpython_compiler::Mode;
|
||||
use rustpython_vm::{common::ascii, Interpreter, PyResult, Settings};
|
||||
use rustpython_vm::{common::ascii, AsObject, Interpreter, PyResult, Settings};
|
||||
use std::{
|
||||
ffi, fs, io,
|
||||
path::{Path, PathBuf},
|
||||
|
||||
@@ -117,7 +117,7 @@ pub(crate) fn impl_pyimpl(attr: AttributeArgs, item: Item) -> Result<TokenStream
|
||||
|
||||
fn impl_extend_class(
|
||||
ctx: &::rustpython_vm::Context,
|
||||
class: &::rustpython_vm::builtins::PyTypeRef,
|
||||
class: &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType>,
|
||||
) {
|
||||
#getset_impl
|
||||
#extend_impl
|
||||
@@ -150,7 +150,7 @@ pub(crate) fn impl_pyimpl(attr: AttributeArgs, item: Item) -> Result<TokenStream
|
||||
parse_quote! {
|
||||
fn __extend_py_class(
|
||||
ctx: &::rustpython_vm::Context,
|
||||
class: &::rustpython_vm::builtins::PyTypeRef,
|
||||
class: &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType>,
|
||||
) {
|
||||
#getset_impl
|
||||
#extend_impl
|
||||
@@ -238,7 +238,7 @@ fn generate_class_def(
|
||||
}
|
||||
.map(|typ| {
|
||||
quote! {
|
||||
fn static_baseclass() -> &'static ::rustpython_vm::builtins::PyTypeRef {
|
||||
fn static_baseclass() -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
|
||||
use rustpython_vm::class::StaticType;
|
||||
#typ::static_type()
|
||||
}
|
||||
@@ -248,7 +248,7 @@ fn generate_class_def(
|
||||
let meta_class = metaclass.map(|typ| {
|
||||
let typ = Ident::new(&typ, ident.span());
|
||||
quote! {
|
||||
fn static_metaclass() -> &'static ::rustpython_vm::builtins::PyTypeRef {
|
||||
fn static_metaclass() -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
|
||||
use rustpython_vm::class::StaticType;
|
||||
#typ::static_type()
|
||||
}
|
||||
@@ -368,8 +368,8 @@ pub(crate) fn impl_define_exception(exc_def: PyExceptionDef) -> Result<TokenStre
|
||||
|
||||
// We need this to make extend mechanism work:
|
||||
impl ::rustpython_vm::PyPayload for #class_name {
|
||||
fn class(vm: &::rustpython_vm::VirtualMachine) -> &::rustpython_vm::builtins::PyTypeRef {
|
||||
&vm.ctx.exceptions.#ctx_name
|
||||
fn class(vm: &::rustpython_vm::VirtualMachine) -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
|
||||
vm.ctx.exceptions.#ctx_name
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,9 +491,9 @@ where
|
||||
quote!(.with_doc(#doc.to_owned(), ctx))
|
||||
});
|
||||
let build_func = match self.inner.attr_name {
|
||||
AttrName::Method => quote!(.build_method(ctx, class.clone())),
|
||||
AttrName::ClassMethod => quote!(.build_classmethod(ctx, class.clone())),
|
||||
AttrName::StaticMethod => quote!(.build_staticmethod(ctx, class.clone())),
|
||||
AttrName::Method => quote!(.build_method(ctx, class)),
|
||||
AttrName::ClassMethod => quote!(.build_classmethod(ctx, class)),
|
||||
AttrName::StaticMethod => quote!(.build_staticmethod(ctx, class)),
|
||||
other => unreachable!(
|
||||
"Only 'method', 'classmethod' and 'staticmethod' are supported, got {:?}",
|
||||
other
|
||||
@@ -735,10 +735,10 @@ impl ToTokens for GetSetNursery {
|
||||
class.set_str_attr(
|
||||
#name,
|
||||
::rustpython_vm::PyRef::new_ref(
|
||||
::rustpython_vm::builtins::PyGetSet::new(#name.into(), class.clone())
|
||||
::rustpython_vm::builtins::PyGetSet::new(#name.into(), class)
|
||||
.with_get(&Self::#getter)
|
||||
#setter #deleter,
|
||||
ctx.types.getset_type.clone(), None),
|
||||
ctx.types.getset_type.to_owned(), None),
|
||||
ctx
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ pub(crate) fn impl_pypayload(input: DeriveInput) -> Result<TokenStream> {
|
||||
|
||||
let ret = quote! {
|
||||
impl ::rustpython_vm::PyPayload for #ty {
|
||||
fn class(_vm: &::rustpython_vm::VirtualMachine) -> &rustpython_vm::builtins::PyTypeRef {
|
||||
fn class(_vm: &::rustpython_vm::VirtualMachine) -> &'static rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
|
||||
<Self as ::rustpython_vm::class::StaticType>::static_type()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -517,7 +517,7 @@ __import__("io").TextIOWrapper(
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
fn install_pip(_: Scope, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_exception_msg(
|
||||
vm.ctx.exceptions.system_error.clone(),
|
||||
vm.ctx.exceptions.system_error.to_owned(),
|
||||
"install-pip requires rustpython be build with the 'ssl' feature enabled.".to_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> {
|
||||
continuing = false;
|
||||
full_input.clear();
|
||||
let keyboard_interrupt =
|
||||
vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.clone());
|
||||
vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned());
|
||||
Err(keyboard_interrupt)
|
||||
}
|
||||
ReadlineResult::Eof => {
|
||||
@@ -127,7 +127,7 @@ pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> {
|
||||
};
|
||||
|
||||
if let Err(exc) = result {
|
||||
if exc.fast_isinstance(&vm.ctx.exceptions.system_exit) {
|
||||
if exc.fast_isinstance(vm.ctx.exceptions.system_exit) {
|
||||
repl.save_history(&repl_history_path).unwrap();
|
||||
return Err(exc);
|
||||
}
|
||||
|
||||
@@ -843,7 +843,7 @@ mod array {
|
||||
|
||||
if not_enough_bytes {
|
||||
Err(vm.new_exception_msg(
|
||||
vm.ctx.exceptions.eof_error.clone(),
|
||||
vm.ctx.exceptions.eof_error.to_owned(),
|
||||
"read() didn't return enough bytes".to_owned(),
|
||||
))
|
||||
} else {
|
||||
|
||||
@@ -16,7 +16,7 @@ mod decl {
|
||||
vm.ctx.new_exception_type(
|
||||
"binascii",
|
||||
"Error",
|
||||
Some(vec![vm.ctx.exceptions.value_error.clone()]),
|
||||
Some(vec![vm.ctx.exceptions.value_error.to_owned()]),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ mod _csv {
|
||||
vm.ctx.new_exception_type(
|
||||
"_csv",
|
||||
"Error",
|
||||
Some(vec![vm.ctx.exceptions.exception_type.clone()]),
|
||||
Some(vec![vm.ctx.exceptions.exception_type.to_owned()]),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -36,14 +36,14 @@ mod _json {
|
||||
let object_hook = vm.option_if_none(ctx.get_attr("object_hook", vm)?);
|
||||
let object_pairs_hook = vm.option_if_none(ctx.get_attr("object_pairs_hook", vm)?);
|
||||
let parse_float = ctx.get_attr("parse_float", vm)?;
|
||||
let parse_float =
|
||||
if vm.is_none(&parse_float) || parse_float.is(&vm.ctx.types.float_type) {
|
||||
None
|
||||
} else {
|
||||
Some(parse_float)
|
||||
};
|
||||
let parse_float = if vm.is_none(&parse_float) || parse_float.is(vm.ctx.types.float_type)
|
||||
{
|
||||
None
|
||||
} else {
|
||||
Some(parse_float)
|
||||
};
|
||||
let parse_int = ctx.get_attr("parse_int", vm)?;
|
||||
let parse_int = if vm.is_none(&parse_int) || parse_int.is(&vm.ctx.types.int_type) {
|
||||
let parse_int = if vm.is_none(&parse_int) || parse_int.is(vm.ctx.types.int_type) {
|
||||
None
|
||||
} else {
|
||||
Some(parse_int)
|
||||
|
||||
@@ -32,10 +32,10 @@ macro_rules! create_property {
|
||||
#[pymodule(name = "pyexpat")]
|
||||
mod _pyexpat {
|
||||
use crate::vm::{
|
||||
builtins::{PyStr, PyStrRef, PyTypeRef},
|
||||
builtins::{PyStr, PyStrRef, PyType},
|
||||
function::ArgBytesLike,
|
||||
function::{IntoFuncArgs, OptionalArg},
|
||||
Context, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
};
|
||||
use rustpython_common::lock::PyRwLock;
|
||||
use std::io::Cursor;
|
||||
@@ -76,38 +76,20 @@ mod _pyexpat {
|
||||
}
|
||||
|
||||
#[extend_class]
|
||||
fn extend_class_with_fields(ctx: &Context, class: &PyTypeRef) {
|
||||
fn extend_class_with_fields(ctx: &Context, class: &'static Py<PyType>) {
|
||||
let mut attributes = class.attributes.write();
|
||||
|
||||
create_property!(
|
||||
ctx,
|
||||
attributes,
|
||||
"StartElementHandler",
|
||||
class.clone(),
|
||||
start_element
|
||||
);
|
||||
create_property!(
|
||||
ctx,
|
||||
attributes,
|
||||
"EndElementHandler",
|
||||
class.clone(),
|
||||
end_element
|
||||
);
|
||||
create_property!(ctx, attributes, "StartElementHandler", class, start_element);
|
||||
create_property!(ctx, attributes, "EndElementHandler", class, end_element);
|
||||
create_property!(
|
||||
ctx,
|
||||
attributes,
|
||||
"CharacterDataHandler",
|
||||
class.clone(),
|
||||
class,
|
||||
character_data
|
||||
);
|
||||
create_property!(
|
||||
ctx,
|
||||
attributes,
|
||||
"EntityDeclHandler",
|
||||
class.clone(),
|
||||
entity_decl
|
||||
);
|
||||
create_property!(ctx, attributes, "buffer_text", class.clone(), buffer_text);
|
||||
create_property!(ctx, attributes, "EntityDeclHandler", class, entity_decl);
|
||||
create_property!(ctx, attributes, "buffer_text", class, buffer_text);
|
||||
}
|
||||
|
||||
fn create_config(&self) -> xml::ParserConfig {
|
||||
|
||||
@@ -165,7 +165,7 @@ mod decl {
|
||||
|
||||
#[pyattr]
|
||||
fn error(vm: &VirtualMachine) -> PyTypeRef {
|
||||
vm.ctx.exceptions.os_error.clone()
|
||||
vm.ctx.exceptions.os_error.to_owned()
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -80,7 +80,7 @@ mod _socket {
|
||||
|
||||
#[pyattr]
|
||||
fn error(vm: &VirtualMachine) -> PyTypeRef {
|
||||
vm.ctx.exceptions.os_error.clone()
|
||||
vm.ctx.exceptions.os_error.to_owned()
|
||||
}
|
||||
|
||||
#[pyattr(once)]
|
||||
@@ -88,7 +88,7 @@ mod _socket {
|
||||
vm.ctx.new_exception_type(
|
||||
"socket",
|
||||
"timeout",
|
||||
Some(vec![vm.ctx.exceptions.os_error.clone()]),
|
||||
Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
|
||||
)
|
||||
}
|
||||
#[pyattr(once)]
|
||||
@@ -96,7 +96,7 @@ mod _socket {
|
||||
vm.ctx.new_exception_type(
|
||||
"socket",
|
||||
"herror",
|
||||
Some(vec![vm.ctx.exceptions.os_error.clone()]),
|
||||
Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
|
||||
)
|
||||
}
|
||||
#[pyattr(once)]
|
||||
@@ -104,7 +104,7 @@ mod _socket {
|
||||
vm.ctx.new_exception_type(
|
||||
"socket",
|
||||
"gaierror",
|
||||
Some(vec![vm.ctx.exceptions.os_error.clone()]),
|
||||
Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -153,7 +153,7 @@ mod _socket {
|
||||
type CastFrom = libc::c_longlong;
|
||||
|
||||
// should really just be to_index() but test_socket tests the error messages explicitly
|
||||
if obj.fast_isinstance(&vm.ctx.types.float_type) {
|
||||
if obj.fast_isinstance(vm.ctx.types.float_type) {
|
||||
return Err(vm.new_type_error("integer argument expected, got float".to_owned()));
|
||||
}
|
||||
let int = vm
|
||||
|
||||
@@ -180,7 +180,7 @@ mod _ssl {
|
||||
vm.ctx.new_exception_type(
|
||||
"ssl",
|
||||
"SSLError",
|
||||
Some(vec![vm.ctx.exceptions.os_error.clone()]),
|
||||
Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -190,7 +190,10 @@ mod _ssl {
|
||||
vm.ctx.new_exception_type(
|
||||
"ssl",
|
||||
"SSLCertVerificationError",
|
||||
Some(vec![ssl_error(vm), vm.ctx.exceptions.value_error.clone()]),
|
||||
Some(vec![
|
||||
ssl_error(vm),
|
||||
vm.ctx.exceptions.value_error.to_owned(),
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -271,7 +271,7 @@ mod termios {
|
||||
vm.ctx.new_exception_type(
|
||||
"termios",
|
||||
"error",
|
||||
Some(vec![vm.ctx.exceptions.os_error.clone()]),
|
||||
Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ mod zlib {
|
||||
vm.ctx.new_exception_type(
|
||||
"zlib",
|
||||
"error",
|
||||
Some(vec![vm.ctx.exceptions.exception_type.clone()]),
|
||||
Some(vec![vm.ctx.exceptions.exception_type.to_owned()]),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{PyCode, PyGenericAlias, PyStrRef, PyTypeRef};
|
||||
use super::{PyCode, PyGenericAlias, PyStrRef, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
builtins::PyBaseExceptionRef,
|
||||
class::PyClassImpl,
|
||||
@@ -7,7 +7,7 @@ use crate::{
|
||||
function::OptionalArg,
|
||||
protocol::PyIterReturn,
|
||||
types::{Constructor, IterNext, IterNextIterable, Unconstructible},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
@@ -21,8 +21,8 @@ pub struct PyAsyncGen {
|
||||
type PyAsyncGenRef = PyRef<PyAsyncGen>;
|
||||
|
||||
impl PyPayload for PyAsyncGen {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.async_generator
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.async_generator
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ impl PyAsyncGen {
|
||||
aclose: true,
|
||||
state: AtomicCell::new(AwaitableState::Init),
|
||||
value: (
|
||||
vm.ctx.exceptions.generator_exit.clone().into(),
|
||||
vm.ctx.exceptions.generator_exit.to_owned().into(),
|
||||
vm.ctx.none(),
|
||||
vm.ctx.none(),
|
||||
),
|
||||
@@ -135,8 +135,8 @@ impl Unconstructible for PyAsyncGen {}
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PyAsyncGenWrappedValue(pub PyObjectRef);
|
||||
impl PyPayload for PyAsyncGenWrappedValue {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.async_generator_wrapped_value
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.async_generator_wrapped_value
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ impl PyAsyncGenWrappedValue {
|
||||
fn unbox(ag: &PyAsyncGen, val: PyResult<PyIterReturn>, vm: &VirtualMachine) -> PyResult {
|
||||
let (closed, async_done) = match &val {
|
||||
Ok(PyIterReturn::StopIteration(_)) => (true, true),
|
||||
Err(e) if e.fast_isinstance(&vm.ctx.exceptions.generator_exit) => (true, true),
|
||||
Err(e) if e.fast_isinstance(vm.ctx.exceptions.generator_exit) => (true, true),
|
||||
Err(_) => (false, true),
|
||||
_ => (false, false),
|
||||
};
|
||||
@@ -184,8 +184,8 @@ pub(crate) struct PyAsyncGenASend {
|
||||
}
|
||||
|
||||
impl PyPayload for PyAsyncGenASend {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.async_generator_asend
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.async_generator_asend
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,8 +279,8 @@ pub(crate) struct PyAsyncGenAThrow {
|
||||
}
|
||||
|
||||
impl PyPayload for PyAsyncGenAThrow {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.async_generator_athrow
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.async_generator_athrow
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,8 +398,8 @@ impl PyAsyncGenAThrow {
|
||||
self.ag.running_async.store(false);
|
||||
self.state.store(AwaitableState::Closed);
|
||||
if self.aclose
|
||||
&& (exc.fast_isinstance(&vm.ctx.exceptions.stop_async_iteration)
|
||||
|| exc.fast_isinstance(&vm.ctx.exceptions.generator_exit))
|
||||
&& (exc.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
|
||||
|| exc.fast_isinstance(vm.ctx.exceptions.generator_exit))
|
||||
{
|
||||
vm.new_stop_iteration(None)
|
||||
} else {
|
||||
@@ -416,7 +416,7 @@ impl IterNext for PyAsyncGenAThrow {
|
||||
}
|
||||
|
||||
pub fn init(ctx: &Context) {
|
||||
PyAsyncGen::extend_class(ctx, &ctx.types.async_generator);
|
||||
PyAsyncGenASend::extend_class(ctx, &ctx.types.async_generator_asend);
|
||||
PyAsyncGenAThrow::extend_class(ctx, &ctx.types.async_generator_athrow);
|
||||
PyAsyncGen::extend_class(ctx, ctx.types.async_generator);
|
||||
PyAsyncGenASend::extend_class(ctx, ctx.types.async_generator_asend);
|
||||
PyAsyncGenAThrow::extend_class(ctx, ctx.types.async_generator_athrow);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{PyInt, PyStrRef, PyTypeRef};
|
||||
use super::{PyInt, PyStrRef, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
class::PyClassImpl, convert::ToPyObject, function::OptionalArg, identifier, types::Constructor,
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject,
|
||||
VirtualMachine,
|
||||
};
|
||||
use num_bigint::Sign;
|
||||
@@ -16,7 +16,7 @@ impl ToPyObject for bool {
|
||||
|
||||
impl TryFromBorrowedObject for bool {
|
||||
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &PyObject) -> PyResult<bool> {
|
||||
if obj.fast_isinstance(&vm.ctx.types.int_type) {
|
||||
if obj.fast_isinstance(vm.ctx.types.int_type) {
|
||||
Ok(get_value(obj))
|
||||
} else {
|
||||
Err(vm.new_type_error(format!("Expected type bool, not {}", obj.class().name())))
|
||||
@@ -38,7 +38,7 @@ impl PyObjectRef {
|
||||
// If descriptor returns Error, propagate it further
|
||||
let method = method_or_err?;
|
||||
let bool_obj = vm.invoke(&method, ())?;
|
||||
if !bool_obj.fast_isinstance(&vm.ctx.types.bool_type) {
|
||||
if !bool_obj.fast_isinstance(vm.ctx.types.bool_type) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"__bool__ should return bool, returned type {}",
|
||||
bool_obj.class().name()
|
||||
@@ -80,8 +80,8 @@ impl PyObjectRef {
|
||||
pub struct PyBool;
|
||||
|
||||
impl PyPayload for PyBool {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.bool_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.bool_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ impl Constructor for PyBool {
|
||||
type Args = OptionalArg<PyObjectRef>;
|
||||
|
||||
fn py_new(zelf: PyTypeRef, x: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
if !zelf.fast_isinstance(&vm.ctx.types.type_type) {
|
||||
if !zelf.fast_isinstance(vm.ctx.types.type_type) {
|
||||
let actual_class = zelf.class();
|
||||
let actual_type = &actual_class.name();
|
||||
return Err(vm.new_type_error(format!(
|
||||
@@ -132,8 +132,8 @@ impl PyBool {
|
||||
#[pymethod(name = "__ror__")]
|
||||
#[pymethod(magic)]
|
||||
fn or(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
|
||||
if lhs.fast_isinstance(&vm.ctx.types.bool_type)
|
||||
&& rhs.fast_isinstance(&vm.ctx.types.bool_type)
|
||||
if lhs.fast_isinstance(vm.ctx.types.bool_type)
|
||||
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
|
||||
{
|
||||
let lhs = get_value(&lhs);
|
||||
let rhs = get_value(&rhs);
|
||||
@@ -146,8 +146,8 @@ impl PyBool {
|
||||
#[pymethod(name = "__rand__")]
|
||||
#[pymethod(magic)]
|
||||
fn and(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
|
||||
if lhs.fast_isinstance(&vm.ctx.types.bool_type)
|
||||
&& rhs.fast_isinstance(&vm.ctx.types.bool_type)
|
||||
if lhs.fast_isinstance(vm.ctx.types.bool_type)
|
||||
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
|
||||
{
|
||||
let lhs = get_value(&lhs);
|
||||
let rhs = get_value(&rhs);
|
||||
@@ -160,8 +160,8 @@ impl PyBool {
|
||||
#[pymethod(name = "__rxor__")]
|
||||
#[pymethod(magic)]
|
||||
fn xor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
|
||||
if lhs.fast_isinstance(&vm.ctx.types.bool_type)
|
||||
&& rhs.fast_isinstance(&vm.ctx.types.bool_type)
|
||||
if lhs.fast_isinstance(vm.ctx.types.bool_type)
|
||||
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
|
||||
{
|
||||
let lhs = get_value(&lhs);
|
||||
let rhs = get_value(&rhs);
|
||||
@@ -173,11 +173,11 @@ impl PyBool {
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyBool::extend_class(context, &context.types.bool_type);
|
||||
PyBool::extend_class(context, context.types.bool_type);
|
||||
}
|
||||
|
||||
// pub fn not(vm: &VirtualMachine, obj: &PyObject) -> PyResult<bool> {
|
||||
// if obj.fast_isinstance(&vm.ctx.types.bool_type) {
|
||||
// if obj.fast_isinstance(vm.ctx.types.bool_type) {
|
||||
// let value = get_value(obj);
|
||||
// Ok(!value)
|
||||
// } else {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::{type_, PyClassMethod, PyStaticMethod, PyStr, PyStrRef, PyTypeRef};
|
||||
use super::{type_, PyClassMethod, PyStaticMethod, PyStr, PyStrRef, PyType};
|
||||
use crate::{
|
||||
builtins::PyBoundMethod,
|
||||
class::PyClassImpl,
|
||||
function::{FuncArgs, IntoPyNativeFunc, PyNativeFunc},
|
||||
types::{Callable, Constructor, GetDescriptor, Unconstructible},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
use std::fmt;
|
||||
|
||||
@@ -34,23 +34,31 @@ impl PyNativeFuncDef {
|
||||
pub fn build_function(self, ctx: &Context) -> PyRef<PyBuiltinFunction> {
|
||||
self.into_function().into_ref(ctx)
|
||||
}
|
||||
pub fn build_method(self, ctx: &Context, class: PyTypeRef) -> PyRef<PyBuiltinMethod> {
|
||||
pub fn build_method(self, ctx: &Context, class: &'static Py<PyType>) -> PyRef<PyBuiltinMethod> {
|
||||
PyRef::new_ref(
|
||||
PyBuiltinMethod { value: self, class },
|
||||
ctx.types.method_descriptor_type.clone(),
|
||||
ctx.types.method_descriptor_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
pub fn build_classmethod(self, ctx: &Context, class: PyTypeRef) -> PyRef<PyClassMethod> {
|
||||
pub fn build_classmethod(
|
||||
self,
|
||||
ctx: &Context,
|
||||
class: &'static Py<PyType>,
|
||||
) -> PyRef<PyClassMethod> {
|
||||
// TODO: classmethod_descriptor
|
||||
let callable = self.build_method(ctx, class).into();
|
||||
PyClassMethod::new_ref(callable, ctx)
|
||||
}
|
||||
pub fn build_staticmethod(self, ctx: &Context, class: PyTypeRef) -> PyRef<PyStaticMethod> {
|
||||
pub fn build_staticmethod(
|
||||
self,
|
||||
ctx: &Context,
|
||||
class: &'static Py<PyType>,
|
||||
) -> PyRef<PyStaticMethod> {
|
||||
let callable = self.build_method(ctx, class).into();
|
||||
PyRef::new_ref(
|
||||
PyStaticMethod { callable },
|
||||
ctx.types.staticmethod_type.clone(),
|
||||
ctx.types.staticmethod_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -63,8 +71,8 @@ pub struct PyBuiltinFunction {
|
||||
}
|
||||
|
||||
impl PyPayload for PyBuiltinFunction {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.builtin_function_or_method_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.builtin_function_or_method_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +100,7 @@ impl PyBuiltinFunction {
|
||||
pub fn into_ref(self, ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(
|
||||
self,
|
||||
ctx.types.builtin_function_or_method_type.clone(),
|
||||
ctx.types.builtin_function_or_method_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -164,12 +172,12 @@ impl Unconstructible for PyBuiltinFunction {}
|
||||
#[pyclass(module = false, name = "method_descriptor")]
|
||||
pub struct PyBuiltinMethod {
|
||||
value: PyNativeFuncDef,
|
||||
class: PyTypeRef,
|
||||
class: &'static Py<PyType>,
|
||||
}
|
||||
|
||||
impl PyPayload for PyBuiltinMethod {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.method_descriptor_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.method_descriptor_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +218,7 @@ impl Callable for PyBuiltinMethod {
|
||||
impl PyBuiltinMethod {
|
||||
pub fn new_ref<F, FKind>(
|
||||
name: impl Into<PyStr>,
|
||||
class: PyTypeRef,
|
||||
class: &'static Py<PyType>,
|
||||
f: F,
|
||||
ctx: &Context,
|
||||
) -> PyRef<Self>
|
||||
@@ -254,6 +262,6 @@ impl PyBuiltinMethod {
|
||||
impl Unconstructible for PyBuiltinMethod {}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyBuiltinFunction::extend_class(context, &context.types.builtin_function_or_method_type);
|
||||
PyBuiltinMethod::extend_class(context, &context.types.method_descriptor_type);
|
||||
PyBuiltinFunction::extend_class(context, context.types.builtin_function_or_method_type);
|
||||
PyBuiltinMethod::extend_class(context, context.types.method_descriptor_type);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Implementation of the python bytearray object.
|
||||
use super::{
|
||||
PositionIterInternal, PyBytes, PyBytesRef, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef,
|
||||
PyTypeRef,
|
||||
PyType, PyTypeRef,
|
||||
};
|
||||
use crate::{
|
||||
anystr::{self, AnyStr},
|
||||
builtins::PyType,
|
||||
bytesinner::{
|
||||
bytes_decode, bytes_from_object, value_from_object, ByteInnerFindOptions,
|
||||
ByteInnerNewOptions, ByteInnerPaddingOptions, ByteInnerSplitOptions,
|
||||
@@ -50,7 +49,7 @@ pub type PyByteArrayRef = PyRef<PyByteArray>;
|
||||
|
||||
impl PyByteArray {
|
||||
pub fn new_ref(data: Vec<u8>, ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(Self::from(data), ctx.types.bytearray_type.clone(), None)
|
||||
PyRef::new_ref(Self::from(data), ctx.types.bytearray_type.to_owned(), None)
|
||||
}
|
||||
|
||||
fn from_inner(inner: PyBytesInner) -> Self {
|
||||
@@ -82,15 +81,15 @@ impl From<Vec<u8>> for PyByteArray {
|
||||
}
|
||||
|
||||
impl PyPayload for PyByteArray {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.bytearray_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.bytearray_type
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill bytearray class methods dictionary.
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyByteArray::extend_class(context, &context.types.bytearray_type);
|
||||
PyByteArrayIterator::extend_class(context, &context.types.bytearray_iterator_type);
|
||||
PyByteArray::extend_class(context, context.types.bytearray_type);
|
||||
PyByteArrayIterator::extend_class(context, context.types.bytearray_iterator_type);
|
||||
}
|
||||
|
||||
#[pyimpl(
|
||||
@@ -862,8 +861,8 @@ pub struct PyByteArrayIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyByteArrayIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.bytearray_iterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.bytearray_iterator_type
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::{PositionIterInternal, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyTypeRef};
|
||||
use super::{
|
||||
PositionIterInternal, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef,
|
||||
};
|
||||
use crate::{
|
||||
anystr::{self, AnyStr},
|
||||
builtins::PyType,
|
||||
bytesinner::{
|
||||
bytes_decode, ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions,
|
||||
ByteInnerSplitOptions, ByteInnerTranslateOptions, DecodeArgs, PyBytesInner,
|
||||
@@ -74,14 +75,14 @@ impl AsRef<[u8]> for PyBytesRef {
|
||||
}
|
||||
|
||||
impl PyPayload for PyBytes {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.bytes_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.bytes_type
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyBytes::extend_class(context, &context.types.bytes_type);
|
||||
PyBytesIterator::extend_class(context, &context.types.bytes_iterator_type);
|
||||
PyBytes::extend_class(context, context.types.bytes_type);
|
||||
PyBytesIterator::extend_class(context, context.types.bytes_iterator_type);
|
||||
}
|
||||
|
||||
impl Constructor for PyBytes {
|
||||
@@ -94,7 +95,7 @@ impl Constructor for PyBytes {
|
||||
|
||||
impl PyBytes {
|
||||
pub fn new_ref(data: Vec<u8>, ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(Self::from(data), ctx.types.bytes_type.clone(), None)
|
||||
PyRef::new_ref(Self::from(data), ctx.types.bytes_type.to_owned(), None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +135,7 @@ impl PyBytes {
|
||||
|
||||
#[pymethod(magic)]
|
||||
fn bytes(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRef<Self> {
|
||||
if zelf.is(&vm.ctx.types.bytes_type) {
|
||||
if zelf.is(vm.ctx.types.bytes_type) {
|
||||
zelf
|
||||
} else {
|
||||
PyBytes::from(zelf.inner.clone()).into_ref(vm)
|
||||
@@ -480,7 +481,7 @@ impl PyBytes {
|
||||
#[pymethod(name = "__rmul__")]
|
||||
#[pymethod(magic)]
|
||||
fn mul(zelf: PyRef<Self>, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
|
||||
if value == 1 && zelf.class().is(&vm.ctx.types.bytes_type) {
|
||||
if value == 1 && zelf.class().is(vm.ctx.types.bytes_type) {
|
||||
// Special case: when some `bytes` is multiplied by `1`,
|
||||
// nothing really happens, we need to return an object itself
|
||||
// with the same `id()` to be compatible with CPython.
|
||||
@@ -633,7 +634,7 @@ impl Comparable for PyBytes {
|
||||
) -> PyResult<PyComparisonValue> {
|
||||
Ok(if let Some(res) = op.identical_optimization(zelf, other) {
|
||||
res.into()
|
||||
} else if other.fast_isinstance(&vm.ctx.types.memoryview_type)
|
||||
} else if other.fast_isinstance(vm.ctx.types.memoryview_type)
|
||||
&& op != PyComparisonOp::Eq
|
||||
&& op != PyComparisonOp::Ne
|
||||
{
|
||||
@@ -665,8 +666,8 @@ pub struct PyBytesIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyBytesIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.bytes_iterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.bytes_iterator_type
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use super::PyTypeRef;
|
||||
use super::{PyBoundMethod, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
builtins::PyBoundMethod,
|
||||
class::PyClassImpl,
|
||||
types::{Constructor, GetDescriptor},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
/// classmethod(function) -> method
|
||||
@@ -39,8 +38,8 @@ impl From<PyObjectRef> for PyClassMethod {
|
||||
}
|
||||
|
||||
impl PyPayload for PyClassMethod {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.classmethod_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.classmethod_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +68,11 @@ impl Constructor for PyClassMethod {
|
||||
|
||||
impl PyClassMethod {
|
||||
pub fn new_ref(callable: PyObjectRef, ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(Self { callable }, ctx.types.classmethod_type.clone(), None)
|
||||
PyRef::new_ref(
|
||||
Self { callable },
|
||||
ctx.types.classmethod_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,5 +99,5 @@ impl PyClassMethod {
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyClassMethod::extend_class(context, &context.types.classmethod_type);
|
||||
PyClassMethod::extend_class(context, context.types.classmethod_type);
|
||||
}
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
|
||||
*/
|
||||
|
||||
use super::{PyStrRef, PyTupleRef, PyTypeRef};
|
||||
use super::{PyStrRef, PyTupleRef, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
builtins::PyStrInterned,
|
||||
bytecode::{self, BorrowedConstant, Constant, ConstantBag},
|
||||
class::{PyClassImpl, StaticType},
|
||||
convert::ToPyObject,
|
||||
function::FuncArgs,
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
use num_traits::Zero;
|
||||
use std::{borrow::Borrow, fmt, ops::Deref};
|
||||
@@ -152,8 +152,8 @@ impl fmt::Debug for PyCode {
|
||||
}
|
||||
|
||||
impl PyPayload for PyCode {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.code_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.code_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,5 +246,5 @@ impl ToPyObject for bytecode::CodeObject {
|
||||
}
|
||||
|
||||
pub fn init(ctx: &Context) {
|
||||
PyRef::<PyCode>::extend_class(ctx, &ctx.types.code_type);
|
||||
PyRef::<PyCode>::extend_class(ctx, ctx.types.code_type);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{float, PyStr, PyTypeRef};
|
||||
use super::{float, PyStr, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
convert::ToPyObject,
|
||||
@@ -9,7 +9,7 @@ use crate::{
|
||||
},
|
||||
identifier,
|
||||
types::{Comparable, Constructor, Hashable, PyComparisonOp},
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
use num_complex::Complex64;
|
||||
use num_traits::Zero;
|
||||
@@ -25,8 +25,8 @@ pub struct PyComplex {
|
||||
}
|
||||
|
||||
impl PyPayload for PyComplex {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.complex_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.complex_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ impl PyObjectRef {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyComplex::extend_class(context, &context.types.complex_type);
|
||||
PyComplex::extend_class(context, context.types.complex_type);
|
||||
}
|
||||
|
||||
fn to_op_complex(value: &PyObject, vm: &VirtualMachine) -> PyResult<Option<Complex64>> {
|
||||
@@ -121,7 +121,7 @@ impl Constructor for PyComplex {
|
||||
let (real, real_was_complex) = match args.real {
|
||||
OptionalArg::Missing => (Complex64::new(0.0, 0.0), false),
|
||||
OptionalArg::Present(val) => {
|
||||
let val = if cls.is(&vm.ctx.types.complex_type) && imag_missing {
|
||||
let val = if cls.is(vm.ctx.types.complex_type) && imag_missing {
|
||||
match val.downcast_exact::<PyComplex>(vm) {
|
||||
Ok(c) => {
|
||||
return Ok(c.into());
|
||||
@@ -162,7 +162,7 @@ impl Constructor for PyComplex {
|
||||
OptionalArg::Present(obj) => {
|
||||
if let Some(c) = obj.try_complex(vm)? {
|
||||
c
|
||||
} else if obj.class().fast_issubclass(&vm.ctx.types.str_type) {
|
||||
} else if obj.class().fast_issubclass(vm.ctx.types.str_type) {
|
||||
return Err(
|
||||
vm.new_type_error("complex() second arg can't be a string".to_owned())
|
||||
);
|
||||
@@ -195,7 +195,7 @@ impl Constructor for PyComplex {
|
||||
|
||||
impl PyComplex {
|
||||
pub fn new_ref(value: Complex64, ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(Self::from(value), ctx.types.complex_type.clone(), None)
|
||||
PyRef::new_ref(Self::from(value), ctx.types.complex_type.to_owned(), None)
|
||||
}
|
||||
|
||||
pub fn to_complex(&self) -> Complex64 {
|
||||
@@ -207,7 +207,7 @@ impl PyComplex {
|
||||
impl PyComplex {
|
||||
#[pymethod(magic)]
|
||||
fn complex(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRef<PyComplex> {
|
||||
if zelf.is(&vm.ctx.types.complex_type) {
|
||||
if zelf.is(vm.ctx.types.complex_type) {
|
||||
zelf
|
||||
} else {
|
||||
PyComplex::from(zelf.value).into_ref(vm)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{PyCode, PyStrRef, PyTypeRef};
|
||||
use super::{PyCode, PyStrRef, PyType};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
coroutine::Coro,
|
||||
@@ -6,7 +6,7 @@ use crate::{
|
||||
function::OptionalArg,
|
||||
protocol::PyIterReturn,
|
||||
types::{Constructor, IterNext, IterNextIterable, Unconstructible},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
#[pyclass(module = false, name = "coroutine")]
|
||||
@@ -17,8 +17,8 @@ pub struct PyCoroutine {
|
||||
}
|
||||
|
||||
impl PyPayload for PyCoroutine {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.coroutine_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.coroutine_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,8 +121,8 @@ pub struct PyCoroutineWrapper {
|
||||
}
|
||||
|
||||
impl PyPayload for PyCoroutineWrapper {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.coroutine_wrapper_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.coroutine_wrapper_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +153,6 @@ impl IterNext for PyCoroutineWrapper {
|
||||
}
|
||||
|
||||
pub fn init(ctx: &Context) {
|
||||
PyCoroutine::extend_class(ctx, &ctx.types.coroutine_type);
|
||||
PyCoroutineWrapper::extend_class(ctx, &ctx.types.coroutine_wrapper_type);
|
||||
PyCoroutine::extend_class(ctx, ctx.types.coroutine_type);
|
||||
PyCoroutineWrapper::extend_class(ctx, ctx.types.coroutine_wrapper_type);
|
||||
}
|
||||
|
||||
@@ -53,14 +53,14 @@ impl fmt::Debug for PyDict {
|
||||
}
|
||||
|
||||
impl PyPayload for PyDict {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.dict_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.dict_type
|
||||
}
|
||||
}
|
||||
|
||||
impl PyDict {
|
||||
pub fn new_ref(ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(Self::default(), ctx.types.dict_type.clone(), None)
|
||||
PyRef::new_ref(Self::default(), ctx.types.dict_type.to_owned(), None)
|
||||
}
|
||||
|
||||
/// escape hatch to access the underlying data structure directly. prefer adding a method on
|
||||
@@ -519,7 +519,7 @@ impl Iterable for PyDict {
|
||||
impl Py<PyDict> {
|
||||
#[inline]
|
||||
fn exact_dict(&self, vm: &VirtualMachine) -> bool {
|
||||
self.class().is(&vm.ctx.types.dict_type)
|
||||
self.class().is(vm.ctx.types.dict_type)
|
||||
}
|
||||
|
||||
fn missing_opt<K: DictKey + ?Sized>(
|
||||
@@ -569,7 +569,7 @@ impl Py<PyDict> {
|
||||
} else {
|
||||
match self.as_object().get_item(key, vm) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(e) if e.fast_isinstance(&vm.ctx.exceptions.key_error) => {
|
||||
Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {
|
||||
self.missing_opt(key, vm)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
@@ -749,8 +749,8 @@ macro_rules! dict_view {
|
||||
}
|
||||
|
||||
impl PyPayload for $name {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.$class
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.$class
|
||||
}
|
||||
}
|
||||
|
||||
@@ -762,8 +762,8 @@ macro_rules! dict_view {
|
||||
}
|
||||
|
||||
impl PyPayload for $iter_name {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.$iter_class
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.$iter_class
|
||||
}
|
||||
}
|
||||
|
||||
@@ -835,8 +835,8 @@ macro_rules! dict_view {
|
||||
}
|
||||
|
||||
impl PyPayload for $reverse_iter_name {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.$reverse_iter_class
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.$reverse_iter_class
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1012,7 +1012,7 @@ trait ViewSetOps: DictView {
|
||||
zelf.dict(),
|
||||
dictview.dict(),
|
||||
op,
|
||||
!zelf.class().is(&vm.ctx.types.dict_keys_type),
|
||||
!zelf.class().is(vm.ctx.types.dict_keys_type),
|
||||
vm,
|
||||
)
|
||||
}
|
||||
@@ -1146,17 +1146,14 @@ impl PyDictValues {
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyDict::extend_class(context, &context.types.dict_type);
|
||||
PyDictKeys::extend_class(context, &context.types.dict_keys_type);
|
||||
PyDictKeyIterator::extend_class(context, &context.types.dict_keyiterator_type);
|
||||
PyDictReverseKeyIterator::extend_class(context, &context.types.dict_reversekeyiterator_type);
|
||||
PyDictValues::extend_class(context, &context.types.dict_values_type);
|
||||
PyDictValueIterator::extend_class(context, &context.types.dict_valueiterator_type);
|
||||
PyDictReverseValueIterator::extend_class(
|
||||
context,
|
||||
&context.types.dict_reversevalueiterator_type,
|
||||
);
|
||||
PyDictItems::extend_class(context, &context.types.dict_items_type);
|
||||
PyDictItemIterator::extend_class(context, &context.types.dict_itemiterator_type);
|
||||
PyDictReverseItemIterator::extend_class(context, &context.types.dict_reverseitemiterator_type);
|
||||
PyDict::extend_class(context, context.types.dict_type);
|
||||
PyDictKeys::extend_class(context, context.types.dict_keys_type);
|
||||
PyDictKeyIterator::extend_class(context, context.types.dict_keyiterator_type);
|
||||
PyDictReverseKeyIterator::extend_class(context, context.types.dict_reversekeyiterator_type);
|
||||
PyDictValues::extend_class(context, context.types.dict_values_type);
|
||||
PyDictValueIterator::extend_class(context, context.types.dict_valueiterator_type);
|
||||
PyDictReverseValueIterator::extend_class(context, context.types.dict_reversevalueiterator_type);
|
||||
PyDictItems::extend_class(context, context.types.dict_items_type);
|
||||
PyDictItemIterator::extend_class(context, context.types.dict_itemiterator_type);
|
||||
PyDictReverseItemIterator::extend_class(context, context.types.dict_reverseitemiterator_type);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::{IterStatus, PositionIterInternal, PyGenericAlias, PyIntRef, PyTupleRef, PyTypeRef};
|
||||
use super::{
|
||||
IterStatus, PositionIterInternal, PyGenericAlias, PyIntRef, PyTupleRef, PyType, PyTypeRef,
|
||||
};
|
||||
use crate::common::lock::{PyMutex, PyRwLock};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
@@ -6,7 +8,7 @@ use crate::{
|
||||
function::OptionalArg,
|
||||
protocol::{PyIter, PyIterReturn},
|
||||
types::{Constructor, IterNext, IterNextIterable},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
use num_bigint::BigInt;
|
||||
use num_traits::Zero;
|
||||
@@ -19,8 +21,8 @@ pub struct PyEnumerate {
|
||||
}
|
||||
|
||||
impl PyPayload for PyEnumerate {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.enumerate_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.enumerate_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,8 +87,8 @@ pub struct PyReverseSequenceIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyReverseSequenceIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.reverse_iter_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.reverse_iter_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +135,6 @@ impl IterNext for PyReverseSequenceIterator {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyEnumerate::extend_class(context, &context.types.enumerate_type);
|
||||
PyReverseSequenceIterator::extend_class(context, &context.types.reverse_iter_type);
|
||||
PyEnumerate::extend_class(context, context.types.enumerate_type);
|
||||
PyReverseSequenceIterator::extend_class(context, context.types.reverse_iter_type);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::PyTypeRef;
|
||||
use super::{PyType, PyTypeRef};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
protocol::{PyIter, PyIterReturn},
|
||||
types::{Constructor, IterNext, IterNextIterable},
|
||||
Context, PyObjectRef, PyPayload, PyResult, VirtualMachine,
|
||||
Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
/// filter(function or None, iterable) --> filter object
|
||||
@@ -18,8 +18,8 @@ pub struct PyFilter {
|
||||
}
|
||||
|
||||
impl PyPayload for PyFilter {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.filter_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.filter_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ impl PyFilter {
|
||||
#[pymethod(magic)]
|
||||
fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, (PyObjectRef, PyIter)) {
|
||||
(
|
||||
vm.ctx.types.filter_type.clone(),
|
||||
vm.ctx.types.filter_type.to_owned(),
|
||||
(self.predicate.clone(), self.iterator.clone()),
|
||||
)
|
||||
}
|
||||
@@ -74,5 +74,5 @@ impl IterNext for PyFilter {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyFilter::extend_class(context, &context.types.filter_type);
|
||||
PyFilter::extend_class(context, context.types.filter_type);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::{try_bigint_to_f64, PyByteArray, PyBytes, PyInt, PyIntRef, PyStr, PyStrRef, PyTypeRef};
|
||||
use super::{
|
||||
try_bigint_to_f64, PyByteArray, PyBytes, PyInt, PyIntRef, PyStr, PyStrRef, PyType, PyTypeRef,
|
||||
};
|
||||
use crate::common::{float_ops, hash};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
@@ -11,8 +13,8 @@ use crate::{
|
||||
},
|
||||
identifier,
|
||||
types::{Comparable, Constructor, Hashable, PyComparisonOp},
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject,
|
||||
TryFromObject, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
|
||||
TryFromBorrowedObject, TryFromObject, VirtualMachine,
|
||||
};
|
||||
use num_bigint::{BigInt, ToBigInt};
|
||||
use num_complex::Complex64;
|
||||
@@ -33,8 +35,8 @@ impl PyFloat {
|
||||
}
|
||||
|
||||
impl PyPayload for PyFloat {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.float_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.float_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,7 +170,7 @@ impl Constructor for PyFloat {
|
||||
let float_val = match arg {
|
||||
OptionalArg::Missing => 0.0,
|
||||
OptionalArg::Present(val) => {
|
||||
let val = if cls.is(&vm.ctx.types.float_type) {
|
||||
let val = if cls.is(vm.ctx.types.float_type) {
|
||||
match val.downcast_exact::<PyFloat>(vm) {
|
||||
Ok(f) => return Ok(f.into()),
|
||||
Err(val) => val,
|
||||
@@ -567,5 +569,5 @@ pub(crate) fn get_value(obj: &PyObject) -> f64 {
|
||||
|
||||
#[rustfmt::skip] // to avoid line splitting
|
||||
pub fn init(context: &Context) {
|
||||
PyFloat::extend_class(context, &context.types.float_type);
|
||||
PyFloat::extend_class(context, context.types.float_type);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::{
|
||||
};
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
FrameRef::extend_class(context, &context.types.frame_type);
|
||||
FrameRef::extend_class(context, context.types.frame_type);
|
||||
}
|
||||
|
||||
#[pyimpl(with(Constructor, PyRef))]
|
||||
|
||||
@@ -3,7 +3,7 @@ mod jitfunc;
|
||||
|
||||
use super::{
|
||||
tuple::PyTupleTyped, PyAsyncGen, PyCode, PyCoroutine, PyDictRef, PyGenerator, PyStr, PyStrRef,
|
||||
PyTupleRef, PyTypeRef,
|
||||
PyTupleRef, PyType, PyTypeRef,
|
||||
};
|
||||
use crate::common::lock::PyMutex;
|
||||
use crate::function::ArgMapping;
|
||||
@@ -322,8 +322,8 @@ impl PyFunction {
|
||||
}
|
||||
|
||||
impl PyPayload for PyFunction {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.function_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.function_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,7 +499,7 @@ impl PyBoundMethod {
|
||||
pub fn new_ref(object: PyObjectRef, function: PyObjectRef, ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(
|
||||
Self::new(object, function),
|
||||
ctx.types.bound_method_type.clone(),
|
||||
ctx.types.bound_method_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -548,7 +548,7 @@ impl PyBoundMethod {
|
||||
fn qualname(&self, vm: &VirtualMachine) -> PyResult {
|
||||
if self
|
||||
.function
|
||||
.fast_isinstance(&vm.ctx.types.builtin_function_or_method_type)
|
||||
.fast_isinstance(vm.ctx.types.builtin_function_or_method_type)
|
||||
{
|
||||
// Special case: we work with `__new__`, which is not really a method.
|
||||
// It is a function, so its `__qualname__` is just `__new__`.
|
||||
@@ -568,8 +568,8 @@ impl PyBoundMethod {
|
||||
}
|
||||
|
||||
impl PyPayload for PyBoundMethod {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.bound_method_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.bound_method_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -581,8 +581,8 @@ pub(crate) struct PyCell {
|
||||
pub(crate) type PyCellRef = PyRef<PyCell>;
|
||||
|
||||
impl PyPayload for PyCell {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.cell_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.cell_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -627,7 +627,7 @@ impl PyCell {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyFunction::extend_class(context, &context.types.function_type);
|
||||
PyBoundMethod::extend_class(context, &context.types.bound_method_type);
|
||||
PyCell::extend_class(context, &context.types.cell_type);
|
||||
PyFunction::extend_class(context, context.types.function_type);
|
||||
PyBoundMethod::extend_class(context, context.types.bound_method_type);
|
||||
PyCell::extend_class(context, context.types.cell_type);
|
||||
}
|
||||
|
||||
@@ -38,17 +38,17 @@ impl ToPyObject for AbiValue {
|
||||
}
|
||||
|
||||
pub fn new_jit_error(msg: String, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
let jit_error = vm.ctx.exceptions.jit_error.clone();
|
||||
let jit_error = vm.ctx.exceptions.jit_error.to_owned();
|
||||
vm.new_exception_msg(jit_error, msg)
|
||||
}
|
||||
|
||||
fn get_jit_arg_type(dict: &PyDictRef, name: &str, vm: &VirtualMachine) -> PyResult<JitType> {
|
||||
if let Some(value) = dict.get_item_opt(name, vm)? {
|
||||
if value.is(&vm.ctx.types.int_type) {
|
||||
if value.is(vm.ctx.types.int_type) {
|
||||
Ok(JitType::Int)
|
||||
} else if value.is(&vm.ctx.types.float_type) {
|
||||
} else if value.is(vm.ctx.types.float_type) {
|
||||
Ok(JitType::Float)
|
||||
} else if value.is(&vm.ctx.types.bool_type) {
|
||||
} else if value.is(vm.ctx.types.bool_type) {
|
||||
Ok(JitType::Bool)
|
||||
} else {
|
||||
Err(new_jit_error(
|
||||
@@ -112,14 +112,14 @@ pub fn get_jit_arg_types(
|
||||
fn get_jit_value(vm: &VirtualMachine, obj: &PyObject) -> Result<AbiValue, ArgsError> {
|
||||
// This does exact type checks as subclasses of int/float can't be passed to jitted functions
|
||||
let cls = obj.class();
|
||||
if cls.is(&vm.ctx.types.int_type) {
|
||||
if cls.is(vm.ctx.types.int_type) {
|
||||
int::get_value(obj)
|
||||
.to_i64()
|
||||
.map(AbiValue::Int)
|
||||
.ok_or(ArgsError::IntOverflow)
|
||||
} else if cls.is(&vm.ctx.types.float_type) {
|
||||
} else if cls.is(vm.ctx.types.float_type) {
|
||||
Ok(AbiValue::Float(float::get_value(obj)))
|
||||
} else if cls.is(&vm.ctx.types.bool_type) {
|
||||
} else if cls.is(vm.ctx.types.bool_type) {
|
||||
Ok(AbiValue::Bool(bool_::get_value(obj)))
|
||||
} else {
|
||||
Err(ArgsError::NonJitType)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* The mythical generator.
|
||||
*/
|
||||
|
||||
use super::{PyCode, PyStrRef, PyTypeRef};
|
||||
use super::{PyCode, PyStrRef, PyType};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
coroutine::Coro,
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
function::OptionalArg,
|
||||
protocol::PyIterReturn,
|
||||
types::{Constructor, IterNext, IterNextIterable, Unconstructible},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
#[pyclass(module = false, name = "generator")]
|
||||
@@ -20,8 +20,8 @@ pub struct PyGenerator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyGenerator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.generator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.generator_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,5 +106,5 @@ impl IterNext for PyGenerator {
|
||||
}
|
||||
|
||||
pub fn init(ctx: &Context) {
|
||||
PyGenerator::extend_class(ctx, &ctx.types.generator_type);
|
||||
PyGenerator::extend_class(ctx, ctx.types.generator_type);
|
||||
}
|
||||
|
||||
@@ -36,8 +36,8 @@ impl fmt::Debug for PyGenericAlias {
|
||||
}
|
||||
|
||||
impl PyPayload for PyGenericAlias {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.generic_alias_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.generic_alias_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ impl PyGenericAlias {
|
||||
#[pymethod(magic)]
|
||||
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> (PyTypeRef, (PyTypeRef, PyTupleRef)) {
|
||||
(
|
||||
vm.ctx.types.generic_alias_type.clone(),
|
||||
vm.ctx.types.generic_alias_type.to_owned(),
|
||||
(zelf.origin.clone(), zelf.args.clone()),
|
||||
)
|
||||
}
|
||||
@@ -327,8 +327,8 @@ impl Callable for PyGenericAlias {
|
||||
fn call(zelf: &crate::Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
PyType::call(&zelf.origin, args, vm).map(|obj| {
|
||||
if let Err(exc) = obj.set_attr(identifier!(vm, __orig_class__), zelf.to_owned(), vm) {
|
||||
if !exc.fast_isinstance(&vm.ctx.exceptions.attribute_error)
|
||||
&& !exc.fast_isinstance(&vm.ctx.exceptions.type_error)
|
||||
if !exc.fast_isinstance(vm.ctx.exceptions.attribute_error)
|
||||
&& !exc.fast_isinstance(vm.ctx.exceptions.type_error)
|
||||
{
|
||||
return Err(exc);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/*! Python `attribute` descriptor class. (PyGetSet)
|
||||
|
||||
*/
|
||||
use super::PyTypeRef;
|
||||
use super::PyType;
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
convert::ToPyResult,
|
||||
function::{OwnedParam, RefParam},
|
||||
object::PyThreadingConstraint,
|
||||
types::{Constructor, GetDescriptor, Unconstructible},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
};
|
||||
|
||||
pub type PyGetterFunc = Box<py_dyn_fn!(dyn Fn(&VirtualMachine, PyObjectRef) -> PyResult)>;
|
||||
@@ -210,7 +210,7 @@ where
|
||||
#[pyclass(module = false, name = "getset_descriptor")]
|
||||
pub struct PyGetSet {
|
||||
name: String,
|
||||
class: PyTypeRef,
|
||||
class: &'static Py<PyType>,
|
||||
getter: Option<PyGetterFunc>,
|
||||
setter: Option<PySetterFunc>,
|
||||
deleter: Option<PyDeleterFunc>,
|
||||
@@ -238,8 +238,8 @@ impl std::fmt::Debug for PyGetSet {
|
||||
}
|
||||
|
||||
impl PyPayload for PyGetSet {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.getset_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.getset_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,7 +267,7 @@ impl GetDescriptor for PyGetSet {
|
||||
}
|
||||
|
||||
impl PyGetSet {
|
||||
pub fn new(name: String, class: PyTypeRef) -> Self {
|
||||
pub fn new(name: String, class: &'static Py<PyType>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
class,
|
||||
@@ -366,5 +366,5 @@ impl PyGetSet {
|
||||
impl Unconstructible for PyGetSet {}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyGetSet::extend_class(context, &context.types.getset_type);
|
||||
PyGetSet::extend_class(context, context.types.getset_type);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{float, PyByteArray, PyBytes, PyStr, PyStrRef, PyTypeRef};
|
||||
use super::{float, PyByteArray, PyBytes, PyStr, PyStrRef, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
bytesinner::PyBytesInner,
|
||||
class::PyClassImpl,
|
||||
@@ -10,8 +10,8 @@ use crate::{
|
||||
PyComparisonValue,
|
||||
},
|
||||
types::{Comparable, Constructor, Hashable, PyComparisonOp},
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject,
|
||||
VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
|
||||
TryFromBorrowedObject, VirtualMachine,
|
||||
};
|
||||
use bstr::ByteSlice;
|
||||
use num_bigint::{BigInt, BigUint, Sign};
|
||||
@@ -57,8 +57,8 @@ where
|
||||
}
|
||||
|
||||
impl PyPayload for PyInt {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.int_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.int_type
|
||||
}
|
||||
|
||||
fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
|
||||
@@ -252,7 +252,7 @@ impl Constructor for PyInt {
|
||||
})?;
|
||||
try_int_radix(&val, base, vm)
|
||||
} else {
|
||||
let val = if cls.is(&vm.ctx.types.int_type) {
|
||||
let val = if cls.is(vm.ctx.types.int_type) {
|
||||
match val.downcast_exact::<PyInt>(vm) {
|
||||
Ok(i) => {
|
||||
return Ok(i.to_pyobject(vm));
|
||||
@@ -280,9 +280,9 @@ impl PyInt {
|
||||
where
|
||||
T: Into<BigInt> + ToPrimitive,
|
||||
{
|
||||
if cls.is(&vm.ctx.types.int_type) {
|
||||
if cls.is(vm.ctx.types.int_type) {
|
||||
Ok(vm.ctx.new_int(value))
|
||||
} else if cls.is(&vm.ctx.types.bool_type) {
|
||||
} else if cls.is(vm.ctx.types.bool_type) {
|
||||
Ok(vm.ctx.new_bool(!value.into().eq(&BigInt::zero())))
|
||||
} else {
|
||||
PyInt::from(value).into_ref_with_type(vm, cls)
|
||||
@@ -690,7 +690,7 @@ impl PyInt {
|
||||
|
||||
#[inline]
|
||||
fn clone_if_subclass(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRef<Self> {
|
||||
if zelf.class().is(&vm.ctx.types.int_type) {
|
||||
if zelf.class().is(vm.ctx.types.int_type) {
|
||||
return zelf;
|
||||
}
|
||||
|
||||
@@ -986,7 +986,7 @@ pub(crate) fn try_int(obj: &PyObject, vm: &VirtualMachine) -> PyResult<BigInt> {
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyInt::extend_class(context, &context.types.int_type);
|
||||
PyInt::extend_class(context, context.types.int_type);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,20 +2,19 @@
|
||||
* iterator types
|
||||
*/
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::{PyInt, PyTupleRef, PyTypeRef};
|
||||
use super::{PyInt, PyTupleRef, PyType};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
function::ArgCallable,
|
||||
protocol::{PyIterReturn, PySequence, PySequenceMethods},
|
||||
types::{IterNext, IterNextIterable},
|
||||
Context, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
|
||||
Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
|
||||
};
|
||||
use rustpython_common::{
|
||||
lock::{PyMutex, PyRwLock, PyRwLockUpgradableReadGuard},
|
||||
static_cell,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// Marks status of iterator.
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -169,8 +168,8 @@ pub struct PySequenceIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PySequenceIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.iter_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.iter_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,8 +226,8 @@ pub struct PyCallableIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyCallableIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.callable_iterator
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.callable_iterator
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,6 +261,6 @@ impl IterNext for PyCallableIterator {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PySequenceIterator::extend_class(context, &context.types.iter_type);
|
||||
PyCallableIterator::extend_class(context, &context.types.callable_iterator);
|
||||
PySequenceIterator::extend_class(context, context.types.iter_type);
|
||||
PyCallableIterator::extend_class(context, context.types.callable_iterator);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{PositionIterInternal, PyGenericAlias, PyTupleRef, PyTypeRef};
|
||||
use super::{PositionIterInternal, PyGenericAlias, PyTupleRef, PyType, PyTypeRef};
|
||||
use crate::common::lock::{
|
||||
PyMappedRwLockReadGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard,
|
||||
};
|
||||
@@ -53,8 +53,8 @@ impl FromIterator<PyObjectRef> for PyList {
|
||||
}
|
||||
|
||||
impl PyPayload for PyList {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.list_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.list_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ impl ToPyObject for Vec<PyObjectRef> {
|
||||
|
||||
impl PyList {
|
||||
pub fn new_ref(elements: Vec<PyObjectRef>, ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(Self::from(elements), ctx.types.list_type.clone(), None)
|
||||
PyRef::new_ref(Self::from(elements), ctx.types.list_type.to_owned(), None)
|
||||
}
|
||||
|
||||
pub fn borrow_vec(&self) -> PyMappedRwLockReadGuard<'_, [PyObjectRef]> {
|
||||
@@ -521,8 +521,8 @@ pub struct PyListIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyListIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.list_iterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.list_iterator_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,8 +566,8 @@ pub struct PyListReverseIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyListReverseIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.list_reverseiterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.list_reverseiterator_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -608,6 +608,6 @@ pub fn init(context: &Context) {
|
||||
let list_type = &context.types.list_type;
|
||||
PyList::extend_class(context, list_type);
|
||||
|
||||
PyListIterator::extend_class(context, &context.types.list_iterator_type);
|
||||
PyListReverseIterator::extend_class(context, &context.types.list_reverseiterator_type);
|
||||
PyListIterator::extend_class(context, context.types.list_iterator_type);
|
||||
PyListReverseIterator::extend_class(context, context.types.list_reverseiterator_type);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use super::PyTypeRef;
|
||||
use super::{PyType, PyTypeRef};
|
||||
use crate::{
|
||||
builtins::PyTupleRef,
|
||||
class::PyClassImpl,
|
||||
function::PosArgs,
|
||||
protocol::{PyIter, PyIterReturn},
|
||||
types::{Constructor, IterNext, IterNextIterable},
|
||||
Context, PyObjectRef, PyPayload, PyResult, VirtualMachine,
|
||||
Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
/// map(func, *iterables) --> map object
|
||||
@@ -20,8 +20,8 @@ pub struct PyMap {
|
||||
}
|
||||
|
||||
impl PyPayload for PyMap {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.map_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.map_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ impl PyMap {
|
||||
fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) {
|
||||
let mut vec = vec![self.mapper.clone()];
|
||||
vec.extend(self.iterators.iter().map(|o| o.clone().into()));
|
||||
(vm.ctx.types.map_type.clone(), vm.new_tuple(vec))
|
||||
(vm.ctx.types.map_type.to_owned(), vm.new_tuple(vec))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,5 +73,5 @@ impl IterNext for PyMap {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyMap::extend_class(context, &context.types.map_type);
|
||||
PyMap::extend_class(context, context.types.map_type);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::{PyDict, PyGenericAlias, PyList, PyTuple, PyTypeRef};
|
||||
use super::{PyDict, PyGenericAlias, PyList, PyTuple, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
convert::ToPyObject,
|
||||
function::OptionalArg,
|
||||
protocol::{PyMapping, PyMappingMethods, PySequence, PySequenceMethods},
|
||||
types::{AsMapping, AsSequence, Constructor, Iterable},
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[pyclass(module = false, name = "mappingproxy")]
|
||||
#[derive(Debug)]
|
||||
@@ -23,8 +22,8 @@ enum MappingProxyInner {
|
||||
}
|
||||
|
||||
impl PyPayload for PyMappingProxy {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.mappingproxy_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.mappingproxy_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,5 +204,5 @@ impl Iterable for PyMappingProxy {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyMappingProxy::extend_class(context, &context.types.mappingproxy_type)
|
||||
PyMappingProxy::extend_class(context, context.types.mappingproxy_type)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::{
|
||||
PyBytes, PyBytesRef, PyInt, PyListRef, PySlice, PyStr, PyStrRef, PyTuple, PyTupleRef, PyTypeRef,
|
||||
PyBytes, PyBytesRef, PyInt, PyListRef, PySlice, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType,
|
||||
PyTypeRef,
|
||||
};
|
||||
use crate::{
|
||||
buffer::FormatSpec,
|
||||
@@ -1041,13 +1042,13 @@ impl Hashable for PyMemoryView {
|
||||
}
|
||||
|
||||
impl PyPayload for PyMemoryView {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.memoryview_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.memoryview_type
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn init(ctx: &Context) {
|
||||
PyMemoryView::extend_class(ctx, &ctx.types.memoryview_type)
|
||||
PyMemoryView::extend_class(ctx, ctx.types.memoryview_type)
|
||||
}
|
||||
|
||||
fn format_unpack(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::pystr::IntoPyStrRef;
|
||||
use super::{PyDictRef, PyStr, PyStrRef, PyTypeRef};
|
||||
use super::{PyDictRef, PyStr, PyStrRef, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
builtins::PyStrInterned,
|
||||
class::PyClassImpl,
|
||||
@@ -14,8 +14,8 @@ use crate::{
|
||||
pub struct PyModule {}
|
||||
|
||||
impl PyPayload for PyModule {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.module_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.module_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,5 +148,5 @@ impl GetAttr for PyModule {
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyModule::extend_class(context, &context.types.module_type);
|
||||
PyModule::extend_class(context, context.types.module_type);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use super::PyTypeRef;
|
||||
use super::{PyType, PyTypeRef};
|
||||
use crate::{
|
||||
builtins::PyDict,
|
||||
class::PyClassImpl,
|
||||
function::{FuncArgs, PyComparisonValue},
|
||||
recursion::ReprGuard,
|
||||
types::{Comparable, Constructor, Initializer, PyComparisonOp},
|
||||
AsObject, Context, PyObject, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
/// A simple attribute-based namespace.
|
||||
@@ -16,8 +16,8 @@ use crate::{
|
||||
pub struct PyNamespace {}
|
||||
|
||||
impl PyPayload for PyNamespace {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.namespace_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.namespace_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ impl PyNamespace {
|
||||
pub fn new_ref(ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(
|
||||
Self {},
|
||||
ctx.types.namespace_type.clone(),
|
||||
ctx.types.namespace_type.to_owned(),
|
||||
Some(ctx.new_dict()),
|
||||
)
|
||||
}
|
||||
@@ -44,7 +44,7 @@ impl PyNamespace {
|
||||
#[pymethod(magic)]
|
||||
fn repr(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<String> {
|
||||
let o = zelf.as_object();
|
||||
let name = if o.class().is(&vm.ctx.types.namespace_type) {
|
||||
let name = if o.class().is(vm.ctx.types.namespace_type) {
|
||||
"namespace".to_owned()
|
||||
} else {
|
||||
o.class().slot_name()
|
||||
@@ -98,5 +98,5 @@ impl Comparable for PyNamespace {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyNamespace::extend_class(context, &context.types.namespace_type);
|
||||
PyNamespace::extend_class(context, context.types.namespace_type);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::{
|
||||
function::Either,
|
||||
function::{FuncArgs, PyArithmeticValue, PyComparisonValue},
|
||||
types::PyComparisonOp,
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
/// object()
|
||||
@@ -20,8 +20,8 @@ use crate::{
|
||||
pub struct PyBaseObject;
|
||||
|
||||
impl PyPayload for PyBaseObject {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.object_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.object_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ impl PyBaseObject {
|
||||
#[pyslot]
|
||||
fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
// more or less __new__ operator
|
||||
let dict = if cls.is(&vm.ctx.types.object_type) {
|
||||
let dict = if cls.is(vm.ctx.types.object_type) {
|
||||
None
|
||||
} else {
|
||||
Some(vm.ctx.new_dict())
|
||||
@@ -348,7 +348,7 @@ pub fn object_set_dict(obj: PyObjectRef, dict: PyDictRef, vm: &VirtualMachine) -
|
||||
}
|
||||
|
||||
pub fn init(ctx: &Context) {
|
||||
PyBaseObject::extend_class(ctx, &ctx.types.object_type);
|
||||
PyBaseObject::extend_class(ctx, ctx.types.object_type);
|
||||
}
|
||||
|
||||
fn common_reduce(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/*! Python `property` descriptor class.
|
||||
|
||||
*/
|
||||
use super::PyTypeRef;
|
||||
use super::{PyType, PyTypeRef};
|
||||
use crate::common::lock::PyRwLock;
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
function::FuncArgs,
|
||||
types::{Constructor, GetDescriptor, Initializer},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
};
|
||||
|
||||
/// Property attribute.
|
||||
@@ -52,8 +52,8 @@ pub struct PyProperty {
|
||||
}
|
||||
|
||||
impl PyPayload for PyProperty {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.property_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.property_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,14 +256,14 @@ impl Initializer for PyProperty {
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyProperty::extend_class(context, &context.types.property_type);
|
||||
PyProperty::extend_class(context, context.types.property_type);
|
||||
|
||||
// This is a bit unfortunate, but this instance attribute overlaps with the
|
||||
// class __doc__ string..
|
||||
extend_class!(context, &context.types.property_type, {
|
||||
extend_class!(context, context.types.property_type, {
|
||||
"__doc__" => context.new_getset(
|
||||
"__doc__",
|
||||
context.types.property_type.clone(),
|
||||
context.types.property_type,
|
||||
PyProperty::doc_getter,
|
||||
PyProperty::doc_setter,
|
||||
),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{PyInt, PyIntRef, PySlice, PyTupleRef, PyTypeRef};
|
||||
use super::{PyInt, PyIntRef, PySlice, PyTupleRef, PyType, PyTypeRef};
|
||||
use crate::common::hash::PyHash;
|
||||
use crate::{
|
||||
builtins::builtins_iter,
|
||||
@@ -75,8 +75,8 @@ pub struct PyRange {
|
||||
}
|
||||
|
||||
impl PyPayload for PyRange {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.range_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.range_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,9 +174,9 @@ impl PyRange {
|
||||
// }
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyRange::extend_class(context, &context.types.range_type);
|
||||
PyLongRangeIterator::extend_class(context, &context.types.longrange_iterator_type);
|
||||
PyRangeIterator::extend_class(context, &context.types.range_iterator_type);
|
||||
PyRange::extend_class(context, context.types.range_type);
|
||||
PyLongRangeIterator::extend_class(context, context.types.longrange_iterator_type);
|
||||
PyRangeIterator::extend_class(context, context.types.range_iterator_type);
|
||||
}
|
||||
|
||||
#[pyimpl(with(AsMapping, AsSequence, Hashable, Comparable, Iterable))]
|
||||
@@ -301,7 +301,7 @@ impl PyRange {
|
||||
.map(|x| x.as_object().to_owned())
|
||||
.collect();
|
||||
let range_paramters_tuple = vm.ctx.new_tuple(range_paramters);
|
||||
(vm.ctx.types.range_type.clone(), range_paramters_tuple)
|
||||
(vm.ctx.types.range_type.to_owned(), range_paramters_tuple)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -529,8 +529,8 @@ pub struct PyLongRangeIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyLongRangeIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.longrange_iterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.longrange_iterator_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -594,8 +594,8 @@ pub struct PyRangeIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyRangeIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.range_iterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.range_iterator_type
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Builtin set type with a sequence of unique items.
|
||||
*/
|
||||
use super::{
|
||||
builtins_iter, IterStatus, PositionIterInternal, PyDictRef, PyGenericAlias, PyTupleRef,
|
||||
builtins_iter, IterStatus, PositionIterInternal, PyDictRef, PyGenericAlias, PyTupleRef, PyType,
|
||||
PyTypeRef,
|
||||
};
|
||||
use crate::common::{ascii, hash::PyHash, lock::PyMutex, rc::PyRc};
|
||||
@@ -18,7 +18,7 @@ use crate::{
|
||||
},
|
||||
utils::collection_repr,
|
||||
vm::VirtualMachine,
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
use std::{fmt, ops::Deref};
|
||||
@@ -72,14 +72,14 @@ impl fmt::Debug for PyFrozenSet {
|
||||
}
|
||||
|
||||
impl PyPayload for PySet {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.set_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.set_type
|
||||
}
|
||||
}
|
||||
|
||||
impl PyPayload for PyFrozenSet {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.frozenset_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.frozenset_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,7 +342,7 @@ impl PySetInner {
|
||||
)
|
||||
// If operation raised KeyError, report original set (set.remove)
|
||||
.map_err(|op_err| {
|
||||
if op_err.fast_isinstance(&vm.ctx.exceptions.key_error) {
|
||||
if op_err.fast_isinstance(vm.ctx.exceptions.key_error) {
|
||||
vm.new_key_error(item.to_owned())
|
||||
} else {
|
||||
op_err
|
||||
@@ -388,7 +388,7 @@ impl PySet {
|
||||
pub fn new_ref(ctx: &Context) -> PyRef<Self> {
|
||||
// Initialized empty, as calling __hash__ is required for adding each object to the set
|
||||
// which requires a VM context - this is done in the set code itself.
|
||||
PyRef::new_ref(Self::default(), ctx.types.set_type.clone(), None)
|
||||
PyRef::new_ref(Self::default(), ctx.types.set_type.to_owned(), None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -715,7 +715,7 @@ impl Constructor for PyFrozenSet {
|
||||
|
||||
fn py_new(cls: PyTypeRef, iterable: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let elements = if let OptionalArg::Present(iterable) = iterable {
|
||||
let iterable = if cls.is(&vm.ctx.types.frozenset_type) {
|
||||
let iterable = if cls.is(vm.ctx.types.frozenset_type) {
|
||||
match iterable.downcast_exact::<Self>(vm) {
|
||||
Ok(fs) => return Ok(fs.into()),
|
||||
Err(iterable) => iterable,
|
||||
@@ -729,7 +729,7 @@ impl Constructor for PyFrozenSet {
|
||||
};
|
||||
|
||||
// Return empty fs if iterable passed is empty and only for exact fs types.
|
||||
if elements.is_empty() && cls.is(&vm.ctx.types.frozenset_type) {
|
||||
if elements.is_empty() && cls.is(vm.ctx.types.frozenset_type) {
|
||||
Ok(vm.ctx.empty_frozenset.clone().into())
|
||||
} else {
|
||||
Self::from_iter(vm, elements)
|
||||
@@ -768,7 +768,7 @@ impl PyFrozenSet {
|
||||
|
||||
#[pymethod]
|
||||
fn copy(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRef<Self> {
|
||||
if zelf.class().is(&vm.ctx.types.frozenset_type) {
|
||||
if zelf.class().is(vm.ctx.types.frozenset_type) {
|
||||
zelf
|
||||
} else {
|
||||
Self {
|
||||
@@ -953,8 +953,8 @@ struct SetIterable {
|
||||
impl TryFromObject for SetIterable {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
let class = obj.class();
|
||||
if class.fast_issubclass(&vm.ctx.types.set_type)
|
||||
|| class.fast_issubclass(&vm.ctx.types.frozenset_type)
|
||||
if class.fast_issubclass(vm.ctx.types.set_type)
|
||||
|| class.fast_issubclass(vm.ctx.types.frozenset_type)
|
||||
{
|
||||
// the class lease needs to be drop to be able to return the object
|
||||
drop(class);
|
||||
@@ -981,8 +981,8 @@ impl fmt::Debug for PySetIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PySetIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.set_iterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.set_iterator_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1038,7 +1038,7 @@ impl IterNext for PySetIterator {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PySet::extend_class(context, &context.types.set_type);
|
||||
PyFrozenSet::extend_class(context, &context.types.frozenset_type);
|
||||
PySetIterator::extend_class(context, &context.types.set_iterator_type);
|
||||
PySet::extend_class(context, context.types.set_type);
|
||||
PyFrozenSet::extend_class(context, context.types.frozenset_type);
|
||||
PySetIterator::extend_class(context, context.types.set_iterator_type);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::PyTypeRef;
|
||||
use super::{PyType, PyTypeRef};
|
||||
use crate::{
|
||||
class::PyClassImpl, convert::ToPyObject, types::Constructor, AsObject, Context, PyObjectRef,
|
||||
class::PyClassImpl, convert::ToPyObject, types::Constructor, Context, Py, PyObjectRef,
|
||||
PyPayload, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
@@ -9,8 +9,8 @@ use crate::{
|
||||
pub struct PyNone;
|
||||
|
||||
impl PyPayload for PyNone {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.none_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.none_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,8 +57,8 @@ impl PyNone {
|
||||
pub struct PyNotImplemented;
|
||||
|
||||
impl PyPayload for PyNotImplemented {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.not_implemented_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.not_implemented_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +92,6 @@ impl PyNotImplemented {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyNone::extend_class(context, &context.none.class());
|
||||
PyNotImplemented::extend_class(context, &context.not_implemented.class());
|
||||
PyNone::extend_class(context, context.types.none_type);
|
||||
PyNotImplemented::extend_class(context, context.types.not_implemented_type);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// sliceobject.{h,c} in CPython
|
||||
use super::{PyInt, PyIntRef, PyTupleRef, PyTypeRef};
|
||||
use super::{PyInt, PyIntRef, PyTupleRef, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
convert::ToPyObject,
|
||||
function::{FuncArgs, OptionalArg, PyComparisonValue},
|
||||
sliceable::SaturatedSlice,
|
||||
types::{Comparable, Constructor, Hashable, PyComparisonOp, Unhashable},
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
use num_bigint::{BigInt, ToBigInt};
|
||||
use num_traits::{One, Signed, Zero};
|
||||
@@ -20,8 +20,8 @@ pub struct PySlice {
|
||||
}
|
||||
|
||||
impl PyPayload for PySlice {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.slice_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.slice_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,8 +265,8 @@ impl Unhashable for PySlice {}
|
||||
pub struct PyEllipsis;
|
||||
|
||||
impl PyPayload for PyEllipsis {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.ellipsis_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.ellipsis_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +291,7 @@ impl PyEllipsis {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PySlice::extend_class(context, &context.types.slice_type);
|
||||
PyEllipsis::extend_class(context, &context.ellipsis.class().clone());
|
||||
pub fn init(ctx: &Context) {
|
||||
PySlice::extend_class(ctx, ctx.types.slice_type);
|
||||
PyEllipsis::extend_class(ctx, ctx.types.ellipsis_type);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::{PyStr, PyTypeRef};
|
||||
use super::{PyStr, PyType, PyTypeRef};
|
||||
use crate::{
|
||||
builtins::builtinfunc::PyBuiltinMethod,
|
||||
class::PyClassImpl,
|
||||
function::{FuncArgs, IntoPyNativeFunc},
|
||||
types::{Callable, Constructor, GetDescriptor},
|
||||
Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
#[pyclass(module = false, name = "staticmethod")]
|
||||
@@ -14,8 +14,8 @@ pub struct PyStaticMethod {
|
||||
}
|
||||
|
||||
impl PyPayload for PyStaticMethod {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.staticmethod_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.staticmethod_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,9 +48,9 @@ impl Constructor for PyStaticMethod {
|
||||
}
|
||||
|
||||
impl PyStaticMethod {
|
||||
pub fn new_ref<F, FKind>(
|
||||
pub fn new_builtin_ref<F, FKind>(
|
||||
name: impl Into<PyStr>,
|
||||
class: PyTypeRef,
|
||||
class: &'static Py<PyType>,
|
||||
f: F,
|
||||
ctx: &Context,
|
||||
) -> PyRef<Self>
|
||||
@@ -58,7 +58,11 @@ impl PyStaticMethod {
|
||||
F: IntoPyNativeFunc<FKind>,
|
||||
{
|
||||
let callable = PyBuiltinMethod::new_ref(name, class, f, ctx).into();
|
||||
PyRef::new_ref(Self { callable }, ctx.types.staticmethod_type.clone(), None)
|
||||
PyRef::new_ref(
|
||||
Self { callable },
|
||||
ctx.types.staticmethod_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,5 +92,5 @@ impl Callable for PyStaticMethod {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyStaticMethod::extend_class(context, &context.types.staticmethod_type);
|
||||
PyStaticMethod::extend_class(context, context.types.staticmethod_type);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
int::{PyInt, PyIntRef},
|
||||
iter::IterStatus::{self, Exhausted},
|
||||
PositionIterInternal, PyBytesRef, PyDict, PyTupleRef, PyTypeRef,
|
||||
PositionIterInternal, PyBytesRef, PyDict, PyTupleRef, PyType, PyTypeRef,
|
||||
};
|
||||
use crate::{
|
||||
anystr::{self, adjust_indices, AnyStr, AnyStrContainer, AnyStrWrapper},
|
||||
@@ -242,8 +242,8 @@ pub struct PyStrIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyStrIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.str_iterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.str_iterator_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,7 +360,7 @@ impl PyStr {
|
||||
}
|
||||
|
||||
pub fn new_ref(s: impl Into<Self>, ctx: &Context) -> PyRef<Self> {
|
||||
PyRef::new_ref(s.into(), ctx.types.str_type.clone(), None)
|
||||
PyRef::new_ref(s.into(), ctx.types.str_type.to_owned(), None)
|
||||
}
|
||||
|
||||
fn new_substr(&self, s: String) -> Self {
|
||||
@@ -523,12 +523,12 @@ impl PyStr {
|
||||
#[pymethod(name = "__rmul__")]
|
||||
#[pymethod(magic)]
|
||||
fn mul(zelf: PyRef<Self>, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
|
||||
if value == 0 && zelf.class().is(&vm.ctx.types.str_type) {
|
||||
if value == 0 && zelf.class().is(vm.ctx.types.str_type) {
|
||||
// Special case: when some `str` is multiplied by `0`,
|
||||
// returns the empty `str`.
|
||||
return Ok(vm.ctx.empty_str.clone());
|
||||
}
|
||||
if (value == 1 || zelf.is_empty()) && zelf.class().is(&vm.ctx.types.str_type) {
|
||||
if (value == 1 || zelf.is_empty()) && zelf.class().is(vm.ctx.types.str_type) {
|
||||
// Special case: when some `str` is multiplied by `1` or is the empty `str`,
|
||||
// nothing really happens, we need to return an object itself
|
||||
// with the same `id()` to be compatible with CPython.
|
||||
@@ -1365,8 +1365,8 @@ pub(crate) fn encode_string(
|
||||
}
|
||||
|
||||
impl PyPayload for PyStr {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.str_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.str_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1426,9 +1426,9 @@ impl FindArgs {
|
||||
}
|
||||
|
||||
pub fn init(ctx: &Context) {
|
||||
PyStr::extend_class(ctx, &ctx.types.str_type);
|
||||
PyStr::extend_class(ctx, ctx.types.str_type);
|
||||
|
||||
PyStrIterator::extend_class(ctx, &ctx.types.str_iterator_type);
|
||||
PyStrIterator::extend_class(ctx, ctx.types.str_iterator_type);
|
||||
}
|
||||
|
||||
impl SliceableSequenceOp for PyStr {
|
||||
|
||||
@@ -19,8 +19,8 @@ pub struct PySuper {
|
||||
}
|
||||
|
||||
impl PyPayload for PySuper {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.super_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.super_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ impl GetDescriptor for PySuper {
|
||||
return Ok(zelf.into());
|
||||
}
|
||||
let zelf_class = zelf.as_object().class();
|
||||
if zelf_class.is(&vm.ctx.types.super_type) {
|
||||
if zelf_class.is(vm.ctx.types.super_type) {
|
||||
Ok(PySuper::new(zelf.typ.clone(), obj, vm)?.into_pyobject(vm))
|
||||
} else {
|
||||
let obj = vm.unwrap_or_none(zelf.obj.clone().map(|(o, _)| o));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::PyTypeRef;
|
||||
use crate::{class::PyClassImpl, frame::FrameRef, Context, PyPayload, PyRef, VirtualMachine};
|
||||
use super::PyType;
|
||||
use crate::{class::PyClassImpl, frame::FrameRef, Context, Py, PyPayload, PyRef, VirtualMachine};
|
||||
|
||||
#[pyclass(module = false, name = "traceback")]
|
||||
#[derive(Debug)]
|
||||
@@ -13,8 +13,8 @@ pub struct PyTraceback {
|
||||
pub type PyTracebackRef = PyRef<PyTraceback>;
|
||||
|
||||
impl PyPayload for PyTraceback {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.traceback_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.traceback_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ impl PyTracebackRef {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyTraceback::extend_class(context, &context.types.traceback_type);
|
||||
PyTraceback::extend_class(context, context.types.traceback_type);
|
||||
}
|
||||
|
||||
impl serde::Serialize for PyTraceback {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{PositionIterInternal, PyGenericAlias, PyTypeRef};
|
||||
use super::{PositionIterInternal, PyGenericAlias, PyType, PyTypeRef};
|
||||
use crate::common::{hash::PyHash, lock::PyMutex};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
@@ -15,7 +15,7 @@ use crate::{
|
||||
},
|
||||
utils::collection_repr,
|
||||
vm::VirtualMachine,
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
|
||||
};
|
||||
use std::{borrow::Cow, fmt, marker::PhantomData};
|
||||
|
||||
@@ -36,8 +36,8 @@ impl fmt::Debug for PyTuple {
|
||||
}
|
||||
|
||||
impl PyPayload for PyTuple {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.tuple_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.tuple_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ impl Constructor for PyTuple {
|
||||
|
||||
fn py_new(cls: PyTypeRef, iterable: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let elements = if let OptionalArg::Present(iterable) = iterable {
|
||||
let iterable = if cls.is(&vm.ctx.types.tuple_type) {
|
||||
let iterable = if cls.is(vm.ctx.types.tuple_type) {
|
||||
match iterable.downcast_exact::<Self>(vm) {
|
||||
Ok(tuple) => return Ok(tuple.into()),
|
||||
Err(iterable) => iterable,
|
||||
@@ -107,7 +107,7 @@ impl Constructor for PyTuple {
|
||||
vec![]
|
||||
};
|
||||
// Return empty tuple only for exact tuple types if the iterable is empty.
|
||||
if elements.is_empty() && cls.is(&vm.ctx.types.tuple_type) {
|
||||
if elements.is_empty() && cls.is(vm.ctx.types.tuple_type) {
|
||||
Ok(vm.ctx.empty_tuple.clone().into())
|
||||
} else {
|
||||
Self {
|
||||
@@ -156,7 +156,7 @@ impl PyTuple {
|
||||
ctx.empty_tuple.clone()
|
||||
} else {
|
||||
let elements = elements.into_boxed_slice();
|
||||
PyRef::new_ref(Self { elements }, ctx.types.tuple_type.clone(), None)
|
||||
PyRef::new_ref(Self { elements }, ctx.types.tuple_type.to_owned(), None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,9 +184,9 @@ impl PyTuple {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyArithmeticValue<PyRef<Self>> {
|
||||
let added = other.downcast::<Self>().map(|other| {
|
||||
if other.elements.is_empty() && zelf.class().is(&vm.ctx.types.tuple_type) {
|
||||
if other.elements.is_empty() && zelf.class().is(vm.ctx.types.tuple_type) {
|
||||
zelf
|
||||
} else if zelf.elements.is_empty() && other.class().is(&vm.ctx.types.tuple_type) {
|
||||
} else if zelf.elements.is_empty() && other.class().is(vm.ctx.types.tuple_type) {
|
||||
other
|
||||
} else {
|
||||
let elements = zelf
|
||||
@@ -248,7 +248,7 @@ impl PyTuple {
|
||||
fn mul(zelf: PyRef<Self>, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
|
||||
Ok(if zelf.elements.is_empty() || value == 0 {
|
||||
vm.ctx.empty_tuple.clone()
|
||||
} else if value == 1 && zelf.class().is(&vm.ctx.types.tuple_type) {
|
||||
} else if value == 1 && zelf.class().is(vm.ctx.types.tuple_type) {
|
||||
// Special case: when some `tuple` is multiplied by `1`,
|
||||
// nothing really happens, we need to return an object itself
|
||||
// with the same `id()` to be compatible with CPython.
|
||||
@@ -331,7 +331,7 @@ impl PyTuple {
|
||||
// the arguments to pass to tuple() is just one tuple - so we'll be doing tuple(tup), which
|
||||
// should just return tup, or tuplesubclass(tup), which'll copy/validate (e.g. for a
|
||||
// structseq)
|
||||
let tup_arg = if zelf.class().is(&vm.ctx.types.tuple_type) {
|
||||
let tup_arg = if zelf.class().is(vm.ctx.types.tuple_type) {
|
||||
zelf
|
||||
} else {
|
||||
PyTuple::new_ref(zelf.elements.clone().into_vec(), &vm.ctx)
|
||||
@@ -435,8 +435,8 @@ pub(crate) struct PyTupleIterator {
|
||||
}
|
||||
|
||||
impl PyPayload for PyTupleIterator {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.tuple_iterator_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.tuple_iterator_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,8 +475,8 @@ impl IterNext for PyTupleIterator {
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
PyTuple::extend_class(context, &context.types.tuple_type);
|
||||
PyTupleIterator::extend_class(context, &context.types.tuple_iterator_type);
|
||||
PyTuple::extend_class(context, context.types.tuple_type);
|
||||
PyTupleIterator::extend_class(context, context.types.tuple_iterator_type);
|
||||
}
|
||||
|
||||
pub struct PyTupleTyped<T: TransmuteFromObject> {
|
||||
|
||||
@@ -52,8 +52,8 @@ impl fmt::Debug for PyType {
|
||||
}
|
||||
|
||||
impl PyPayload for PyType {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.type_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.type_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ impl PyType {
|
||||
vec![base.clone()],
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Self::static_type().clone(),
|
||||
Self::static_type().to_owned(),
|
||||
)
|
||||
}
|
||||
pub fn new_ref(
|
||||
@@ -127,7 +127,7 @@ impl PyType {
|
||||
base.subclasses.write().push(
|
||||
new_type
|
||||
.as_object()
|
||||
.downgrade_with_weakref_typ_opt(None, weakref_type.clone())
|
||||
.downgrade_with_weakref_typ_opt(None, weakref_type.to_owned())
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
@@ -342,7 +342,7 @@ impl PyType {
|
||||
.cloned()
|
||||
// We need to exclude this method from going into recursion:
|
||||
.and_then(|found| {
|
||||
if found.fast_isinstance(&vm.ctx.types.getset_type) {
|
||||
if found.fast_isinstance(vm.ctx.types.getset_type) {
|
||||
None
|
||||
} else {
|
||||
Some(found)
|
||||
@@ -359,7 +359,7 @@ impl PyType {
|
||||
.cloned()
|
||||
// We need to exclude this method from going into recursion:
|
||||
.and_then(|found| {
|
||||
if found.fast_isinstance(&vm.ctx.types.getset_type) {
|
||||
if found.fast_isinstance(vm.ctx.types.getset_type) {
|
||||
None
|
||||
} else {
|
||||
Some(found)
|
||||
@@ -418,7 +418,7 @@ impl PyType {
|
||||
fn slot_new(metatype: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
vm_trace!("type.__new__ {:?}", args);
|
||||
|
||||
let is_type_type = metatype.is(&vm.ctx.types.type_type);
|
||||
let is_type_type = metatype.is(vm.ctx.types.type_type);
|
||||
if is_type_type && args.args.len() == 1 && args.kwargs.is_empty() {
|
||||
return Ok(args.args[0].class().clone().into());
|
||||
}
|
||||
@@ -442,7 +442,7 @@ impl PyType {
|
||||
}
|
||||
|
||||
let (metatype, base, bases) = if bases.is_empty() {
|
||||
let base = vm.ctx.types.object_type.clone();
|
||||
let base = vm.ctx.types.object_type.to_owned();
|
||||
(metatype, base.clone(), vec![base])
|
||||
} else {
|
||||
let bases = bases
|
||||
@@ -484,19 +484,19 @@ impl PyType {
|
||||
|
||||
let mut attributes = dict.to_attributes(vm);
|
||||
if let Some(f) = attributes.get_mut(identifier!(vm, __new__)) {
|
||||
if f.class().is(&vm.ctx.types.function_type) {
|
||||
if f.class().is(vm.ctx.types.function_type) {
|
||||
*f = PyStaticMethod::from(f.clone()).into_pyobject(vm);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(f) = attributes.get_mut(identifier!(vm, __init_subclass__)) {
|
||||
if f.class().is(&vm.ctx.types.function_type) {
|
||||
if f.class().is(vm.ctx.types.function_type) {
|
||||
*f = PyClassMethod::from(f.clone()).into_pyobject(vm);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(f) = attributes.get_mut(identifier!(vm, __class_getitem__)) {
|
||||
if f.class().is(&vm.ctx.types.function_type) {
|
||||
if f.class().is(vm.ctx.types.function_type) {
|
||||
*f = PyClassMethod::from(f.clone()).into_pyobject(vm);
|
||||
}
|
||||
}
|
||||
@@ -520,18 +520,17 @@ impl PyType {
|
||||
// All *classes* should have a dict. Exceptions are *instances* of
|
||||
// classes that define __slots__ and instances of built-in classes
|
||||
// (with exceptions, e.g function)
|
||||
attributes
|
||||
.entry(identifier!(vm, __dict__))
|
||||
.or_insert_with(|| {
|
||||
vm.ctx
|
||||
.new_getset(
|
||||
"__dict__",
|
||||
vm.ctx.types.object_type.clone(),
|
||||
subtype_get_dict,
|
||||
subtype_set_dict,
|
||||
)
|
||||
.into()
|
||||
});
|
||||
let __dict__ = identifier!(vm, __dict__);
|
||||
attributes.entry(__dict__).or_insert_with(|| {
|
||||
vm.ctx
|
||||
.new_getset(
|
||||
"__dict__",
|
||||
vm.ctx.types.object_type,
|
||||
subtype_get_dict,
|
||||
subtype_set_dict,
|
||||
)
|
||||
.into()
|
||||
});
|
||||
|
||||
// TODO: Flags is currently initialized with HAS_DICT. Should be
|
||||
// updated when __slots__ are supported (toggling the flag off if
|
||||
@@ -723,7 +722,7 @@ impl SetAttr for PyType {
|
||||
let prev_value = attributes.remove(attr_name);
|
||||
if prev_value.is_none() {
|
||||
return Err(vm.new_exception(
|
||||
vm.ctx.exceptions.attribute_error.clone(),
|
||||
vm.ctx.exceptions.attribute_error.to_owned(),
|
||||
vec![attr_name.to_object()],
|
||||
));
|
||||
}
|
||||
@@ -741,8 +740,7 @@ impl Callable for PyType {
|
||||
vm_trace!("type_call: {:?}", zelf);
|
||||
let obj = call_slot_new(zelf.to_owned(), zelf.to_owned(), args.clone(), vm)?;
|
||||
|
||||
if (zelf.is(&vm.ctx.types.type_type) && args.kwargs.is_empty())
|
||||
|| !obj.fast_isinstance(zelf)
|
||||
if (zelf.is(vm.ctx.types.type_type) && args.kwargs.is_empty()) || !obj.fast_isinstance(zelf)
|
||||
{
|
||||
return Ok(obj);
|
||||
}
|
||||
@@ -758,7 +756,7 @@ fn find_base_dict_descr(cls: &PyTypeRef, vm: &VirtualMachine) -> Option<PyObject
|
||||
cls.iter_base_chain().skip(1).find_map(|cls| {
|
||||
// TODO: should actually be some translation of:
|
||||
// cls.slot_dictoffset != 0 && !cls.flags.contains(HEAPTYPE)
|
||||
if cls.is(&vm.ctx.types.type_type) {
|
||||
if cls.is(vm.ctx.types.type_type) {
|
||||
cls.get_attr(identifier!(vm, __dict__))
|
||||
} else {
|
||||
None
|
||||
@@ -808,7 +806,7 @@ fn subtype_set_dict(obj: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -
|
||||
*/
|
||||
|
||||
pub(crate) fn init(ctx: &Context) {
|
||||
PyType::extend_class(ctx, &ctx.types.type_type);
|
||||
PyType::extend_class(ctx, ctx.types.type_type);
|
||||
}
|
||||
|
||||
pub(crate) fn call_slot_new(
|
||||
@@ -965,8 +963,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_linearise() {
|
||||
let context = Context::genesis();
|
||||
let object = &context.types.object_type;
|
||||
let type_type = &context.types.type_type;
|
||||
let object = context.types.object_type.to_owned();
|
||||
let type_type = context.types.type_type.to_owned();
|
||||
|
||||
let a = PyType::new_ref(
|
||||
"A",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::genericalias;
|
||||
use crate::{
|
||||
builtins::{PyFrozenSet, PyStr, PyStrRef, PyTuple, PyTupleRef, PyTypeRef},
|
||||
builtins::{PyFrozenSet, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef},
|
||||
class::PyClassImpl,
|
||||
common::hash,
|
||||
convert::ToPyObject,
|
||||
@@ -27,8 +27,8 @@ impl fmt::Debug for PyUnion {
|
||||
}
|
||||
|
||||
impl PyPayload for PyUnion {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.union_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.union_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,10 +103,10 @@ impl PyUnion {
|
||||
}
|
||||
|
||||
pub fn is_unionable(obj: PyObjectRef, vm: &VirtualMachine) -> bool {
|
||||
obj.class().is(&vm.ctx.types.none_type)
|
||||
|| obj.class().is(&vm.ctx.types.type_type)
|
||||
|| obj.class().is(&vm.ctx.types.generic_alias_type)
|
||||
|| obj.class().is(&vm.ctx.types.union_type)
|
||||
obj.class().is(vm.ctx.types.none_type)
|
||||
|| obj.class().is(vm.ctx.types.type_type)
|
||||
|| obj.class().is(vm.ctx.types.generic_alias_type)
|
||||
|| obj.class().is(vm.ctx.types.union_type)
|
||||
}
|
||||
|
||||
fn is_typevar(obj: &PyObjectRef, vm: &VirtualMachine) -> bool {
|
||||
@@ -175,8 +175,8 @@ fn dedup_and_flatten_args(args: PyTupleRef, vm: &VirtualMachine) -> PyTupleRef {
|
||||
PyTypeRef::try_from_object(vm, arg.clone()),
|
||||
) {
|
||||
(Ok(a), Ok(b))
|
||||
if a.is(&vm.ctx.types.generic_alias_type)
|
||||
&& b.is(&vm.ctx.types.generic_alias_type) =>
|
||||
if a.is(vm.ctx.types.generic_alias_type)
|
||||
&& b.is(vm.ctx.types.generic_alias_type) =>
|
||||
{
|
||||
param
|
||||
.rich_compare_bool(arg, PyComparisonOp::Eq, vm)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::{PyStrRef, PyTypeRef, PyWeak};
|
||||
use super::{PyStrRef, PyType, PyTypeRef, PyWeak};
|
||||
use crate::{
|
||||
class::PyClassImpl,
|
||||
function::OptionalArg,
|
||||
types::{Constructor, SetAttr},
|
||||
Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
#[pyclass(module = false, name = "weakproxy")]
|
||||
@@ -13,8 +13,8 @@ pub struct PyWeakProxy {
|
||||
}
|
||||
|
||||
impl PyPayload for PyWeakProxy {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.weakproxy_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.weakproxy_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ impl Constructor for PyWeakProxy {
|
||||
vm.ctx.new_class(
|
||||
None,
|
||||
"__weakproxy",
|
||||
&vm.ctx.types.weakref_type,
|
||||
vm.ctx.types.weakref_type.to_owned(),
|
||||
super::PyWeak::make_slots(),
|
||||
)
|
||||
});
|
||||
@@ -76,7 +76,7 @@ impl PyWeakProxy {
|
||||
|
||||
fn new_reference_error(vm: &VirtualMachine) -> PyRef<super::PyBaseException> {
|
||||
vm.new_exception_msg(
|
||||
vm.ctx.exceptions.reference_error.clone(),
|
||||
vm.ctx.exceptions.reference_error.to_owned(),
|
||||
"weakly-referenced object no longer exists".to_owned(),
|
||||
)
|
||||
}
|
||||
@@ -91,7 +91,7 @@ impl SetAttr for PyWeakProxy {
|
||||
match zelf.weak.upgrade() {
|
||||
Some(obj) => obj.call_set_attr(vm, attr_name, value),
|
||||
None => Err(vm.new_exception_msg(
|
||||
vm.ctx.exceptions.reference_error.clone(),
|
||||
vm.ctx.exceptions.reference_error.to_owned(),
|
||||
"weakly-referenced object no longer exists".to_owned(),
|
||||
)),
|
||||
}
|
||||
@@ -99,5 +99,5 @@ impl SetAttr for PyWeakProxy {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyWeakProxy::extend_class(context, &context.types.weakproxy_type);
|
||||
PyWeakProxy::extend_class(context, context.types.weakproxy_type);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{PyGenericAlias, PyTypeRef};
|
||||
use super::{PyGenericAlias, PyType, PyTypeRef};
|
||||
use crate::common::{
|
||||
atomic::{Ordering, Radium},
|
||||
hash::{self, PyHash},
|
||||
@@ -7,7 +7,7 @@ use crate::{
|
||||
class::PyClassImpl,
|
||||
function::OptionalArg,
|
||||
types::{Callable, Comparable, Constructor, Hashable, PyComparisonOp},
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
pub use crate::object::PyWeak;
|
||||
@@ -21,8 +21,8 @@ pub struct WeakNewArgs {
|
||||
}
|
||||
|
||||
impl PyPayload for PyWeak {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.weakref_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.weakref_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,5 +115,5 @@ impl Comparable for PyWeak {
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyWeak::extend_class(context, &context.types.weakref_type);
|
||||
PyWeak::extend_class(context, context.types.weakref_type);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use super::PyTypeRef;
|
||||
use super::{PyType, PyTypeRef};
|
||||
use crate::{
|
||||
builtins::PyTupleRef,
|
||||
class::PyClassImpl,
|
||||
function::{ArgIntoBool, OptionalArg, PosArgs},
|
||||
protocol::{PyIter, PyIterReturn},
|
||||
types::{Constructor, IterNext, IterNextIterable},
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
};
|
||||
use rustpython_common::atomic::{self, PyAtomic, Radium};
|
||||
|
||||
@@ -17,8 +17,8 @@ pub struct PyZip {
|
||||
}
|
||||
|
||||
impl PyPayload for PyZip {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.zip_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.zip_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,6 +109,6 @@ impl IterNext for PyZip {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
PyZip::extend_class(context, &context.types.zip_type);
|
||||
pub fn init(ctx: &Context) {
|
||||
PyZip::extend_class(ctx, ctx.types.zip_type);
|
||||
}
|
||||
|
||||
@@ -1213,7 +1213,7 @@ pub fn bytes_from_object(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Vec<u8
|
||||
return Ok(elements);
|
||||
}
|
||||
|
||||
if !obj.fast_isinstance(&vm.ctx.types.str_type) {
|
||||
if !obj.fast_isinstance(vm.ctx.types.str_type) {
|
||||
if let Ok(elements) = vm.map_iterable_object(obj, |x| value_from_object(vm, &x)) {
|
||||
return elements;
|
||||
}
|
||||
|
||||
@@ -448,7 +448,7 @@ impl CFormatSpec {
|
||||
CFormatType::Float(_) => {
|
||||
let type_name = obj.class().name().to_string();
|
||||
let value = ArgIntoFloat::try_from_object(vm, obj).map_err(|e| {
|
||||
if e.fast_isinstance(&vm.ctx.exceptions.type_error) {
|
||||
if e.fast_isinstance(vm.ctx.exceptions.type_error) {
|
||||
// formatfloat in bytesobject.c generates its own specific exception
|
||||
// text in this case, mirror it here.
|
||||
vm.new_type_error(format!("float argument required, not {}", type_name))
|
||||
@@ -690,9 +690,9 @@ impl CFormatBytes {
|
||||
let mut result = vec![];
|
||||
|
||||
let is_mapping = values_obj.class().has_attr(identifier!(vm, __getitem__))
|
||||
&& !values_obj.fast_isinstance(&vm.ctx.types.tuple_type)
|
||||
&& !values_obj.fast_isinstance(&vm.ctx.types.bytes_type)
|
||||
&& !values_obj.fast_isinstance(&vm.ctx.types.bytearray_type);
|
||||
&& !values_obj.fast_isinstance(vm.ctx.types.tuple_type)
|
||||
&& !values_obj.fast_isinstance(vm.ctx.types.bytes_type)
|
||||
&& !values_obj.fast_isinstance(vm.ctx.types.bytearray_type);
|
||||
|
||||
if num_specifiers == 0 {
|
||||
// literal only
|
||||
@@ -842,8 +842,8 @@ impl CFormatString {
|
||||
let mut result = String::new();
|
||||
|
||||
let is_mapping = values_obj.class().has_attr(identifier!(vm, __getitem__))
|
||||
&& !values_obj.fast_isinstance(&vm.ctx.types.tuple_type)
|
||||
&& !values_obj.fast_isinstance(&vm.ctx.types.str_type);
|
||||
&& !values_obj.fast_isinstance(vm.ctx.types.tuple_type)
|
||||
&& !values_obj.fast_isinstance(vm.ctx.types.str_type);
|
||||
|
||||
if num_specifiers == 0 {
|
||||
// literal only
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::{
|
||||
builtins::{PyBaseObject, PyBoundMethod, PyType, PyTypeRef},
|
||||
identifier,
|
||||
object::{PyObjectPayload, PyObjectRef, PyRef},
|
||||
object::{Py, PyObjectPayload, PyObjectRef, PyRef},
|
||||
types::{PyTypeFlags, PyTypeSlots},
|
||||
vm::Context,
|
||||
};
|
||||
@@ -12,24 +12,24 @@ use rustpython_common::{lock::PyRwLock, static_cell};
|
||||
pub trait StaticType {
|
||||
// Ideally, saving PyType is better than PyTypeRef
|
||||
fn static_cell() -> &'static static_cell::StaticCell<PyTypeRef>;
|
||||
fn static_metaclass() -> &'static PyTypeRef {
|
||||
fn static_metaclass() -> &'static Py<PyType> {
|
||||
PyType::static_type()
|
||||
}
|
||||
fn static_baseclass() -> &'static PyTypeRef {
|
||||
fn static_baseclass() -> &'static Py<PyType> {
|
||||
PyBaseObject::static_type()
|
||||
}
|
||||
fn static_type() -> &'static PyTypeRef {
|
||||
fn static_type() -> &'static Py<PyType> {
|
||||
Self::static_cell()
|
||||
.get()
|
||||
.expect("static type has not been initialized")
|
||||
}
|
||||
fn init_manually(typ: PyTypeRef) -> &'static PyTypeRef {
|
||||
fn init_manually(typ: PyTypeRef) -> &'static Py<PyType> {
|
||||
let cell = Self::static_cell();
|
||||
cell.set(typ)
|
||||
.unwrap_or_else(|_| panic!("double initialization from init_manually"));
|
||||
cell.get().unwrap()
|
||||
}
|
||||
fn init_bare_type() -> &'static PyTypeRef
|
||||
fn init_bare_type() -> &'static Py<PyType>
|
||||
where
|
||||
Self: PyClassImpl,
|
||||
{
|
||||
@@ -45,10 +45,10 @@ pub trait StaticType {
|
||||
{
|
||||
PyType::new_ref(
|
||||
Self::NAME,
|
||||
vec![Self::static_baseclass().clone()],
|
||||
vec![Self::static_baseclass().to_owned()],
|
||||
Default::default(),
|
||||
Self::make_slots(),
|
||||
Self::static_metaclass().clone(),
|
||||
Self::static_metaclass().to_owned(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -76,9 +76,9 @@ where
|
||||
pub trait PyClassImpl: PyClassDef {
|
||||
const TP_FLAGS: PyTypeFlags = PyTypeFlags::DEFAULT;
|
||||
|
||||
fn impl_extend_class(ctx: &Context, class: &PyTypeRef);
|
||||
fn impl_extend_class(ctx: &Context, class: &'static Py<PyType>);
|
||||
|
||||
fn extend_class(ctx: &Context, class: &PyTypeRef) {
|
||||
fn extend_class(ctx: &Context, class: &'static Py<PyType>) {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
assert!(class.slots.flags.is_created_with_flags());
|
||||
@@ -89,7 +89,7 @@ pub trait PyClassImpl: PyClassDef {
|
||||
__dict__,
|
||||
ctx.new_getset(
|
||||
"__dict__",
|
||||
class.clone(),
|
||||
class,
|
||||
crate::builtins::object::object_get_dict,
|
||||
crate::builtins::object::object_set_dict,
|
||||
)
|
||||
@@ -108,7 +108,7 @@ pub trait PyClassImpl: PyClassDef {
|
||||
}
|
||||
if class.slots.new.load().is_some() {
|
||||
let bound: PyObjectRef =
|
||||
PyBoundMethod::new_ref(class.clone().into(), ctx.slot_new_wrapper.clone(), ctx)
|
||||
PyBoundMethod::new_ref(class.to_owned().into(), ctx.slot_new_wrapper.clone(), ctx)
|
||||
.into();
|
||||
class.set_attr(identifier!(ctx, __new__), bound);
|
||||
}
|
||||
@@ -118,13 +118,16 @@ pub trait PyClassImpl: PyClassDef {
|
||||
where
|
||||
Self: StaticType,
|
||||
{
|
||||
Self::static_cell()
|
||||
.get_or_init(|| {
|
||||
let typ = Self::create_bare_type();
|
||||
Self::extend_class(ctx, &typ);
|
||||
typ
|
||||
})
|
||||
.clone()
|
||||
(*Self::static_cell().get_or_init(|| {
|
||||
let typ = Self::create_bare_type();
|
||||
Self::extend_class(ctx, unsafe {
|
||||
// typ will be saved in static_cell
|
||||
let r: &Py<PyType> = &typ;
|
||||
&*(r as *const _)
|
||||
});
|
||||
typ
|
||||
}))
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn extend_slots(slots: &mut PyTypeSlots);
|
||||
|
||||
@@ -359,12 +359,12 @@ fn extract_unicode_error_range(err: &PyObject, vm: &VirtualMachine) -> PyResult<
|
||||
|
||||
#[inline]
|
||||
fn is_decode_err(err: &PyObject, vm: &VirtualMachine) -> bool {
|
||||
err.fast_isinstance(&vm.ctx.exceptions.unicode_decode_error)
|
||||
err.fast_isinstance(vm.ctx.exceptions.unicode_decode_error)
|
||||
}
|
||||
#[inline]
|
||||
fn is_encode_ish_err(err: &PyObject, vm: &VirtualMachine) -> bool {
|
||||
err.fast_isinstance(&vm.ctx.exceptions.unicode_encode_error)
|
||||
|| err.fast_isinstance(&vm.ctx.exceptions.unicode_translate_error)
|
||||
err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error)
|
||||
|| err.fast_isinstance(vm.ctx.exceptions.unicode_translate_error)
|
||||
}
|
||||
|
||||
fn bad_err_type(err: PyObjectRef, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
@@ -393,12 +393,12 @@ fn ignore_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyObjectRef
|
||||
fn replace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String, usize)> {
|
||||
// char::REPLACEMENT_CHARACTER as a str
|
||||
let replacement_char = "\u{FFFD}";
|
||||
let replace = if err.fast_isinstance(&vm.ctx.exceptions.unicode_encode_error) {
|
||||
let replace = if err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) {
|
||||
"?"
|
||||
} else if err.fast_isinstance(&vm.ctx.exceptions.unicode_decode_error) {
|
||||
} else if err.fast_isinstance(vm.ctx.exceptions.unicode_decode_error) {
|
||||
let range = extract_unicode_error_range(&err, vm)?;
|
||||
return Ok((replacement_char.to_owned(), range.end));
|
||||
} else if err.fast_isinstance(&vm.ctx.exceptions.unicode_translate_error) {
|
||||
} else if err.fast_isinstance(vm.ctx.exceptions.unicode_translate_error) {
|
||||
replacement_char
|
||||
} else {
|
||||
return Err(bad_err_type(err, vm));
|
||||
@@ -456,7 +456,7 @@ fn backslashreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(S
|
||||
}
|
||||
|
||||
fn namereplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String, usize)> {
|
||||
if err.fast_isinstance(&vm.ctx.exceptions.unicode_encode_error) {
|
||||
if err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) {
|
||||
let range = extract_unicode_error_range(&err, vm)?;
|
||||
let s = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?;
|
||||
let s_after_start =
|
||||
@@ -550,7 +550,7 @@ fn get_standard_encoding(encoding: &str) -> (usize, StandardEncoding) {
|
||||
}
|
||||
|
||||
fn surrogatepass_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String, usize)> {
|
||||
if err.fast_isinstance(&vm.ctx.exceptions.unicode_encode_error) {
|
||||
if err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) {
|
||||
let range = extract_unicode_error_range(&err, vm)?;
|
||||
let s = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?;
|
||||
let s_encoding = PyStrRef::try_from_object(vm, err.get_attr("encoding", vm)?)?;
|
||||
@@ -662,7 +662,7 @@ fn surrogatepass_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(Stri
|
||||
}
|
||||
|
||||
fn surrogateescape_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String, usize)> {
|
||||
if err.fast_isinstance(&vm.ctx.exceptions.unicode_encode_error) {
|
||||
if err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) {
|
||||
let range = extract_unicode_error_range(&err, vm)?;
|
||||
let s = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?;
|
||||
let s_after_start =
|
||||
|
||||
@@ -38,9 +38,9 @@ pub struct Coro {
|
||||
|
||||
fn gen_name(gen: &PyObject, vm: &VirtualMachine) -> &'static str {
|
||||
let typ = gen.class();
|
||||
if typ.is(&vm.ctx.types.coroutine_type) {
|
||||
if typ.is(vm.ctx.types.coroutine_type) {
|
||||
"coroutine"
|
||||
} else if typ.is(&vm.ctx.types.async_generator) {
|
||||
} else if typ.is(vm.ctx.types.async_generator) {
|
||||
"async generator"
|
||||
} else {
|
||||
"generator"
|
||||
@@ -112,13 +112,13 @@ impl Coro {
|
||||
match result {
|
||||
Ok(exec_res) => Ok(exec_res.into_iter_return(vm)),
|
||||
Err(e) => {
|
||||
if e.fast_isinstance(&vm.ctx.exceptions.stop_iteration) {
|
||||
if e.fast_isinstance(vm.ctx.exceptions.stop_iteration) {
|
||||
let err =
|
||||
vm.new_runtime_error(format!("{} raised StopIteration", gen_name(gen, vm)));
|
||||
err.set_cause(Some(e));
|
||||
Err(err)
|
||||
} else if gen.class().is(&vm.ctx.types.async_generator)
|
||||
&& e.fast_isinstance(&vm.ctx.exceptions.stop_async_iteration)
|
||||
} else if gen.class().is(vm.ctx.types.async_generator)
|
||||
&& e.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
|
||||
{
|
||||
let err = vm
|
||||
.new_runtime_error("async generator raised StopAsyncIteration".to_owned());
|
||||
@@ -153,7 +153,7 @@ impl Coro {
|
||||
let result = self.run_with_context(gen, vm, |f| {
|
||||
f.gen_throw(
|
||||
vm,
|
||||
vm.ctx.exceptions.generator_exit.clone().into(),
|
||||
vm.ctx.exceptions.generator_exit.to_owned().into(),
|
||||
vm.ctx.none(),
|
||||
vm.ctx.none(),
|
||||
)
|
||||
@@ -194,5 +194,5 @@ impl Coro {
|
||||
}
|
||||
|
||||
pub fn is_gen_exit(exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> bool {
|
||||
exc.fast_isinstance(&vm.ctx.exceptions.generator_exit)
|
||||
exc.fast_isinstance(vm.ctx.exceptions.generator_exit)
|
||||
}
|
||||
|
||||
@@ -895,7 +895,7 @@ impl DictKey for usize {
|
||||
}
|
||||
|
||||
fn str_exact<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> Option<&'a PyStr> {
|
||||
if obj.class().is(&vm.ctx.types.str_type) {
|
||||
if obj.class().is(vm.ctx.types.str_type) {
|
||||
obj.payload::<PyStr>()
|
||||
} else {
|
||||
None
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
py_io::{self, Write},
|
||||
stdlib::sys,
|
||||
suggestion::offer_suggestions,
|
||||
AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
|
||||
};
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use itertools::Itertools;
|
||||
@@ -28,8 +28,8 @@ impl std::fmt::Debug for PyBaseException {
|
||||
}
|
||||
|
||||
impl PyPayload for PyBaseException {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.exceptions.base_exception_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.exceptions.base_exception_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,7 +264,7 @@ impl TryFromObject for ExceptionCtor {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
obj.downcast::<PyType>()
|
||||
.and_then(|cls| {
|
||||
if cls.fast_issubclass(&vm.ctx.exceptions.base_exception_type) {
|
||||
if cls.fast_issubclass(vm.ctx.exceptions.base_exception_type) {
|
||||
Ok(Self::Class(cls))
|
||||
} else {
|
||||
Err(cls.into())
|
||||
@@ -320,75 +320,75 @@ impl ExceptionCtor {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExceptionZoo {
|
||||
pub base_exception_type: PyTypeRef,
|
||||
pub system_exit: PyTypeRef,
|
||||
pub keyboard_interrupt: PyTypeRef,
|
||||
pub generator_exit: PyTypeRef,
|
||||
pub exception_type: PyTypeRef,
|
||||
pub stop_iteration: PyTypeRef,
|
||||
pub stop_async_iteration: PyTypeRef,
|
||||
pub arithmetic_error: PyTypeRef,
|
||||
pub floating_point_error: PyTypeRef,
|
||||
pub overflow_error: PyTypeRef,
|
||||
pub zero_division_error: PyTypeRef,
|
||||
pub assertion_error: PyTypeRef,
|
||||
pub attribute_error: PyTypeRef,
|
||||
pub buffer_error: PyTypeRef,
|
||||
pub eof_error: PyTypeRef,
|
||||
pub import_error: PyTypeRef,
|
||||
pub module_not_found_error: PyTypeRef,
|
||||
pub lookup_error: PyTypeRef,
|
||||
pub index_error: PyTypeRef,
|
||||
pub key_error: PyTypeRef,
|
||||
pub memory_error: PyTypeRef,
|
||||
pub name_error: PyTypeRef,
|
||||
pub unbound_local_error: PyTypeRef,
|
||||
pub os_error: PyTypeRef,
|
||||
pub blocking_io_error: PyTypeRef,
|
||||
pub child_process_error: PyTypeRef,
|
||||
pub connection_error: PyTypeRef,
|
||||
pub broken_pipe_error: PyTypeRef,
|
||||
pub connection_aborted_error: PyTypeRef,
|
||||
pub connection_refused_error: PyTypeRef,
|
||||
pub connection_reset_error: PyTypeRef,
|
||||
pub file_exists_error: PyTypeRef,
|
||||
pub file_not_found_error: PyTypeRef,
|
||||
pub interrupted_error: PyTypeRef,
|
||||
pub is_a_directory_error: PyTypeRef,
|
||||
pub not_a_directory_error: PyTypeRef,
|
||||
pub permission_error: PyTypeRef,
|
||||
pub process_lookup_error: PyTypeRef,
|
||||
pub timeout_error: PyTypeRef,
|
||||
pub reference_error: PyTypeRef,
|
||||
pub runtime_error: PyTypeRef,
|
||||
pub not_implemented_error: PyTypeRef,
|
||||
pub recursion_error: PyTypeRef,
|
||||
pub syntax_error: PyTypeRef,
|
||||
pub indentation_error: PyTypeRef,
|
||||
pub tab_error: PyTypeRef,
|
||||
pub system_error: PyTypeRef,
|
||||
pub type_error: PyTypeRef,
|
||||
pub value_error: PyTypeRef,
|
||||
pub unicode_error: PyTypeRef,
|
||||
pub unicode_decode_error: PyTypeRef,
|
||||
pub unicode_encode_error: PyTypeRef,
|
||||
pub unicode_translate_error: PyTypeRef,
|
||||
pub base_exception_type: &'static Py<PyType>,
|
||||
pub system_exit: &'static Py<PyType>,
|
||||
pub keyboard_interrupt: &'static Py<PyType>,
|
||||
pub generator_exit: &'static Py<PyType>,
|
||||
pub exception_type: &'static Py<PyType>,
|
||||
pub stop_iteration: &'static Py<PyType>,
|
||||
pub stop_async_iteration: &'static Py<PyType>,
|
||||
pub arithmetic_error: &'static Py<PyType>,
|
||||
pub floating_point_error: &'static Py<PyType>,
|
||||
pub overflow_error: &'static Py<PyType>,
|
||||
pub zero_division_error: &'static Py<PyType>,
|
||||
pub assertion_error: &'static Py<PyType>,
|
||||
pub attribute_error: &'static Py<PyType>,
|
||||
pub buffer_error: &'static Py<PyType>,
|
||||
pub eof_error: &'static Py<PyType>,
|
||||
pub import_error: &'static Py<PyType>,
|
||||
pub module_not_found_error: &'static Py<PyType>,
|
||||
pub lookup_error: &'static Py<PyType>,
|
||||
pub index_error: &'static Py<PyType>,
|
||||
pub key_error: &'static Py<PyType>,
|
||||
pub memory_error: &'static Py<PyType>,
|
||||
pub name_error: &'static Py<PyType>,
|
||||
pub unbound_local_error: &'static Py<PyType>,
|
||||
pub os_error: &'static Py<PyType>,
|
||||
pub blocking_io_error: &'static Py<PyType>,
|
||||
pub child_process_error: &'static Py<PyType>,
|
||||
pub connection_error: &'static Py<PyType>,
|
||||
pub broken_pipe_error: &'static Py<PyType>,
|
||||
pub connection_aborted_error: &'static Py<PyType>,
|
||||
pub connection_refused_error: &'static Py<PyType>,
|
||||
pub connection_reset_error: &'static Py<PyType>,
|
||||
pub file_exists_error: &'static Py<PyType>,
|
||||
pub file_not_found_error: &'static Py<PyType>,
|
||||
pub interrupted_error: &'static Py<PyType>,
|
||||
pub is_a_directory_error: &'static Py<PyType>,
|
||||
pub not_a_directory_error: &'static Py<PyType>,
|
||||
pub permission_error: &'static Py<PyType>,
|
||||
pub process_lookup_error: &'static Py<PyType>,
|
||||
pub timeout_error: &'static Py<PyType>,
|
||||
pub reference_error: &'static Py<PyType>,
|
||||
pub runtime_error: &'static Py<PyType>,
|
||||
pub not_implemented_error: &'static Py<PyType>,
|
||||
pub recursion_error: &'static Py<PyType>,
|
||||
pub syntax_error: &'static Py<PyType>,
|
||||
pub indentation_error: &'static Py<PyType>,
|
||||
pub tab_error: &'static Py<PyType>,
|
||||
pub system_error: &'static Py<PyType>,
|
||||
pub type_error: &'static Py<PyType>,
|
||||
pub value_error: &'static Py<PyType>,
|
||||
pub unicode_error: &'static Py<PyType>,
|
||||
pub unicode_decode_error: &'static Py<PyType>,
|
||||
pub unicode_encode_error: &'static Py<PyType>,
|
||||
pub unicode_translate_error: &'static Py<PyType>,
|
||||
|
||||
#[cfg(feature = "jit")]
|
||||
pub jit_error: PyTypeRef,
|
||||
pub jit_error: &'static Py<PyType>,
|
||||
|
||||
pub warning: PyTypeRef,
|
||||
pub deprecation_warning: PyTypeRef,
|
||||
pub pending_deprecation_warning: PyTypeRef,
|
||||
pub runtime_warning: PyTypeRef,
|
||||
pub syntax_warning: PyTypeRef,
|
||||
pub user_warning: PyTypeRef,
|
||||
pub future_warning: PyTypeRef,
|
||||
pub import_warning: PyTypeRef,
|
||||
pub unicode_warning: PyTypeRef,
|
||||
pub bytes_warning: PyTypeRef,
|
||||
pub resource_warning: PyTypeRef,
|
||||
pub encoding_warning: PyTypeRef,
|
||||
pub warning: &'static Py<PyType>,
|
||||
pub deprecation_warning: &'static Py<PyType>,
|
||||
pub pending_deprecation_warning: &'static Py<PyType>,
|
||||
pub runtime_warning: &'static Py<PyType>,
|
||||
pub syntax_warning: &'static Py<PyType>,
|
||||
pub user_warning: &'static Py<PyType>,
|
||||
pub future_warning: &'static Py<PyType>,
|
||||
pub import_warning: &'static Py<PyType>,
|
||||
pub unicode_warning: &'static Py<PyType>,
|
||||
pub bytes_warning: &'static Py<PyType>,
|
||||
pub resource_warning: &'static Py<PyType>,
|
||||
pub encoding_warning: &'static Py<PyType>,
|
||||
}
|
||||
|
||||
macro_rules! extend_exception {
|
||||
@@ -534,91 +534,91 @@ impl ExceptionZoo {
|
||||
pub(crate) fn init() -> Self {
|
||||
use self::types::*;
|
||||
|
||||
let base_exception_type = PyBaseException::init_bare_type().clone();
|
||||
let base_exception_type = PyBaseException::init_bare_type();
|
||||
|
||||
// Sorted By Hierarchy then alphabetized.
|
||||
let system_exit = PySystemExit::init_bare_type().clone();
|
||||
let keyboard_interrupt = PyKeyboardInterrupt::init_bare_type().clone();
|
||||
let generator_exit = PyGeneratorExit::init_bare_type().clone();
|
||||
let system_exit = PySystemExit::init_bare_type();
|
||||
let keyboard_interrupt = PyKeyboardInterrupt::init_bare_type();
|
||||
let generator_exit = PyGeneratorExit::init_bare_type();
|
||||
|
||||
let exception_type = PyException::init_bare_type().clone();
|
||||
let stop_iteration = PyStopIteration::init_bare_type().clone();
|
||||
let stop_async_iteration = PyStopAsyncIteration::init_bare_type().clone();
|
||||
let arithmetic_error = PyArithmeticError::init_bare_type().clone();
|
||||
let floating_point_error = PyFloatingPointError::init_bare_type().clone();
|
||||
let overflow_error = PyOverflowError::init_bare_type().clone();
|
||||
let zero_division_error = PyZeroDivisionError::init_bare_type().clone();
|
||||
let exception_type = PyException::init_bare_type();
|
||||
let stop_iteration = PyStopIteration::init_bare_type();
|
||||
let stop_async_iteration = PyStopAsyncIteration::init_bare_type();
|
||||
let arithmetic_error = PyArithmeticError::init_bare_type();
|
||||
let floating_point_error = PyFloatingPointError::init_bare_type();
|
||||
let overflow_error = PyOverflowError::init_bare_type();
|
||||
let zero_division_error = PyZeroDivisionError::init_bare_type();
|
||||
|
||||
let assertion_error = PyAssertionError::init_bare_type().clone();
|
||||
let attribute_error = PyAttributeError::init_bare_type().clone();
|
||||
let buffer_error = PyBufferError::init_bare_type().clone();
|
||||
let eof_error = PyEOFError::init_bare_type().clone();
|
||||
let assertion_error = PyAssertionError::init_bare_type();
|
||||
let attribute_error = PyAttributeError::init_bare_type();
|
||||
let buffer_error = PyBufferError::init_bare_type();
|
||||
let eof_error = PyEOFError::init_bare_type();
|
||||
|
||||
let import_error = PyImportError::init_bare_type().clone();
|
||||
let module_not_found_error = PyModuleNotFoundError::init_bare_type().clone();
|
||||
let import_error = PyImportError::init_bare_type();
|
||||
let module_not_found_error = PyModuleNotFoundError::init_bare_type();
|
||||
|
||||
let lookup_error = PyLookupError::init_bare_type().clone();
|
||||
let index_error = PyIndexError::init_bare_type().clone();
|
||||
let key_error = PyKeyError::init_bare_type().clone();
|
||||
let lookup_error = PyLookupError::init_bare_type();
|
||||
let index_error = PyIndexError::init_bare_type();
|
||||
let key_error = PyKeyError::init_bare_type();
|
||||
|
||||
let memory_error = PyMemoryError::init_bare_type().clone();
|
||||
let memory_error = PyMemoryError::init_bare_type();
|
||||
|
||||
let name_error = PyNameError::init_bare_type().clone();
|
||||
let unbound_local_error = PyUnboundLocalError::init_bare_type().clone();
|
||||
let name_error = PyNameError::init_bare_type();
|
||||
let unbound_local_error = PyUnboundLocalError::init_bare_type();
|
||||
|
||||
// os errors
|
||||
let os_error = PyOSError::init_bare_type().clone();
|
||||
let blocking_io_error = PyBlockingIOError::init_bare_type().clone();
|
||||
let child_process_error = PyChildProcessError::init_bare_type().clone();
|
||||
let os_error = PyOSError::init_bare_type();
|
||||
let blocking_io_error = PyBlockingIOError::init_bare_type();
|
||||
let child_process_error = PyChildProcessError::init_bare_type();
|
||||
|
||||
let connection_error = PyConnectionError::init_bare_type().clone();
|
||||
let broken_pipe_error = PyBrokenPipeError::init_bare_type().clone();
|
||||
let connection_aborted_error = PyConnectionAbortedError::init_bare_type().clone();
|
||||
let connection_refused_error = PyConnectionRefusedError::init_bare_type().clone();
|
||||
let connection_reset_error = PyConnectionResetError::init_bare_type().clone();
|
||||
let connection_error = PyConnectionError::init_bare_type();
|
||||
let broken_pipe_error = PyBrokenPipeError::init_bare_type();
|
||||
let connection_aborted_error = PyConnectionAbortedError::init_bare_type();
|
||||
let connection_refused_error = PyConnectionRefusedError::init_bare_type();
|
||||
let connection_reset_error = PyConnectionResetError::init_bare_type();
|
||||
|
||||
let file_exists_error = PyFileExistsError::init_bare_type().clone();
|
||||
let file_not_found_error = PyFileNotFoundError::init_bare_type().clone();
|
||||
let interrupted_error = PyInterruptedError::init_bare_type().clone();
|
||||
let is_a_directory_error = PyIsADirectoryError::init_bare_type().clone();
|
||||
let not_a_directory_error = PyNotADirectoryError::init_bare_type().clone();
|
||||
let permission_error = PyPermissionError::init_bare_type().clone();
|
||||
let process_lookup_error = PyProcessLookupError::init_bare_type().clone();
|
||||
let timeout_error = PyTimeoutError::init_bare_type().clone();
|
||||
let file_exists_error = PyFileExistsError::init_bare_type();
|
||||
let file_not_found_error = PyFileNotFoundError::init_bare_type();
|
||||
let interrupted_error = PyInterruptedError::init_bare_type();
|
||||
let is_a_directory_error = PyIsADirectoryError::init_bare_type();
|
||||
let not_a_directory_error = PyNotADirectoryError::init_bare_type();
|
||||
let permission_error = PyPermissionError::init_bare_type();
|
||||
let process_lookup_error = PyProcessLookupError::init_bare_type();
|
||||
let timeout_error = PyTimeoutError::init_bare_type();
|
||||
|
||||
let reference_error = PyReferenceError::init_bare_type().clone();
|
||||
let reference_error = PyReferenceError::init_bare_type();
|
||||
|
||||
let runtime_error = PyRuntimeError::init_bare_type().clone();
|
||||
let not_implemented_error = PyNotImplementedError::init_bare_type().clone();
|
||||
let recursion_error = PyRecursionError::init_bare_type().clone();
|
||||
let runtime_error = PyRuntimeError::init_bare_type();
|
||||
let not_implemented_error = PyNotImplementedError::init_bare_type();
|
||||
let recursion_error = PyRecursionError::init_bare_type();
|
||||
|
||||
let syntax_error = PySyntaxError::init_bare_type().clone();
|
||||
let indentation_error = PyIndentationError::init_bare_type().clone();
|
||||
let tab_error = PyTabError::init_bare_type().clone();
|
||||
let syntax_error = PySyntaxError::init_bare_type();
|
||||
let indentation_error = PyIndentationError::init_bare_type();
|
||||
let tab_error = PyTabError::init_bare_type();
|
||||
|
||||
let system_error = PySystemError::init_bare_type().clone();
|
||||
let type_error = PyTypeError::init_bare_type().clone();
|
||||
let value_error = PyValueError::init_bare_type().clone();
|
||||
let unicode_error = PyUnicodeError::init_bare_type().clone();
|
||||
let unicode_decode_error = PyUnicodeDecodeError::init_bare_type().clone();
|
||||
let unicode_encode_error = PyUnicodeEncodeError::init_bare_type().clone();
|
||||
let unicode_translate_error = PyUnicodeTranslateError::init_bare_type().clone();
|
||||
let system_error = PySystemError::init_bare_type();
|
||||
let type_error = PyTypeError::init_bare_type();
|
||||
let value_error = PyValueError::init_bare_type();
|
||||
let unicode_error = PyUnicodeError::init_bare_type();
|
||||
let unicode_decode_error = PyUnicodeDecodeError::init_bare_type();
|
||||
let unicode_encode_error = PyUnicodeEncodeError::init_bare_type();
|
||||
let unicode_translate_error = PyUnicodeTranslateError::init_bare_type();
|
||||
|
||||
#[cfg(feature = "jit")]
|
||||
let jit_error = PyJitError::init_bare_type().clone();
|
||||
let jit_error = PyJitError::init_bare_type();
|
||||
|
||||
let warning = PyWarning::init_bare_type().clone();
|
||||
let deprecation_warning = PyDeprecationWarning::init_bare_type().clone();
|
||||
let pending_deprecation_warning = PyPendingDeprecationWarning::init_bare_type().clone();
|
||||
let runtime_warning = PyRuntimeWarning::init_bare_type().clone();
|
||||
let syntax_warning = PySyntaxWarning::init_bare_type().clone();
|
||||
let user_warning = PyUserWarning::init_bare_type().clone();
|
||||
let future_warning = PyFutureWarning::init_bare_type().clone();
|
||||
let import_warning = PyImportWarning::init_bare_type().clone();
|
||||
let unicode_warning = PyUnicodeWarning::init_bare_type().clone();
|
||||
let bytes_warning = PyBytesWarning::init_bare_type().clone();
|
||||
let resource_warning = PyResourceWarning::init_bare_type().clone();
|
||||
let encoding_warning = PyEncodingWarning::init_bare_type().clone();
|
||||
let warning = PyWarning::init_bare_type();
|
||||
let deprecation_warning = PyDeprecationWarning::init_bare_type();
|
||||
let pending_deprecation_warning = PyPendingDeprecationWarning::init_bare_type();
|
||||
let runtime_warning = PyRuntimeWarning::init_bare_type();
|
||||
let syntax_warning = PySyntaxWarning::init_bare_type();
|
||||
let user_warning = PyUserWarning::init_bare_type();
|
||||
let future_warning = PyFutureWarning::init_bare_type();
|
||||
let import_warning = PyImportWarning::init_bare_type();
|
||||
let unicode_warning = PyUnicodeWarning::init_bare_type();
|
||||
let bytes_warning = PyBytesWarning::init_bare_type();
|
||||
let resource_warning = PyResourceWarning::init_bare_type();
|
||||
let encoding_warning = PyEncodingWarning::init_bare_type();
|
||||
|
||||
Self {
|
||||
base_exception_type,
|
||||
@@ -700,161 +700,153 @@ impl ExceptionZoo {
|
||||
|
||||
let excs = &ctx.exceptions;
|
||||
|
||||
PyBaseException::extend_class(ctx, &excs.base_exception_type);
|
||||
PyBaseException::extend_class(ctx, excs.base_exception_type);
|
||||
|
||||
// Sorted By Hierarchy then alphabetized.
|
||||
extend_exception!(PySystemExit, ctx, &excs.system_exit, {
|
||||
"code" => ctx.new_readonly_getset("code", excs.system_exit.clone(), system_exit_code),
|
||||
extend_exception!(PySystemExit, ctx, excs.system_exit, {
|
||||
"code" => ctx.new_readonly_getset("code", excs.system_exit, system_exit_code),
|
||||
});
|
||||
extend_exception!(PyKeyboardInterrupt, ctx, &excs.keyboard_interrupt);
|
||||
extend_exception!(PyGeneratorExit, ctx, &excs.generator_exit);
|
||||
extend_exception!(PyKeyboardInterrupt, ctx, excs.keyboard_interrupt);
|
||||
extend_exception!(PyGeneratorExit, ctx, excs.generator_exit);
|
||||
|
||||
extend_exception!(PyException, ctx, &excs.exception_type);
|
||||
extend_exception!(PyException, ctx, excs.exception_type);
|
||||
|
||||
extend_exception!(PyStopIteration, ctx, &excs.stop_iteration, {
|
||||
"value" => ctx.new_readonly_getset("value", excs.stop_iteration.clone(), make_arg_getter(0)),
|
||||
extend_exception!(PyStopIteration, ctx, excs.stop_iteration, {
|
||||
"value" => ctx.new_readonly_getset("value", excs.stop_iteration, make_arg_getter(0)),
|
||||
});
|
||||
extend_exception!(PyStopAsyncIteration, ctx, &excs.stop_async_iteration);
|
||||
extend_exception!(PyStopAsyncIteration, ctx, excs.stop_async_iteration);
|
||||
|
||||
extend_exception!(PyArithmeticError, ctx, &excs.arithmetic_error);
|
||||
extend_exception!(PyFloatingPointError, ctx, &excs.floating_point_error);
|
||||
extend_exception!(PyOverflowError, ctx, &excs.overflow_error);
|
||||
extend_exception!(PyZeroDivisionError, ctx, &excs.zero_division_error);
|
||||
extend_exception!(PyArithmeticError, ctx, excs.arithmetic_error);
|
||||
extend_exception!(PyFloatingPointError, ctx, excs.floating_point_error);
|
||||
extend_exception!(PyOverflowError, ctx, excs.overflow_error);
|
||||
extend_exception!(PyZeroDivisionError, ctx, excs.zero_division_error);
|
||||
|
||||
extend_exception!(PyAssertionError, ctx, &excs.assertion_error);
|
||||
extend_exception!(PyAttributeError, ctx, &excs.attribute_error, {
|
||||
extend_exception!(PyAssertionError, ctx, excs.assertion_error);
|
||||
extend_exception!(PyAttributeError, ctx, excs.attribute_error, {
|
||||
"name" => ctx.none(),
|
||||
"obj" => ctx.none(),
|
||||
});
|
||||
extend_exception!(PyBufferError, ctx, &excs.buffer_error);
|
||||
extend_exception!(PyEOFError, ctx, &excs.eof_error);
|
||||
extend_exception!(PyBufferError, ctx, excs.buffer_error);
|
||||
extend_exception!(PyEOFError, ctx, excs.eof_error);
|
||||
|
||||
extend_exception!(PyImportError, ctx, &excs.import_error, {
|
||||
"msg" => ctx.new_readonly_getset("msg", excs.import_error.clone(), make_arg_getter(0)),
|
||||
extend_exception!(PyImportError, ctx, excs.import_error, {
|
||||
"msg" => ctx.new_readonly_getset("msg", excs.import_error, make_arg_getter(0)),
|
||||
});
|
||||
extend_exception!(PyModuleNotFoundError, ctx, &excs.module_not_found_error);
|
||||
extend_exception!(PyModuleNotFoundError, ctx, excs.module_not_found_error);
|
||||
|
||||
extend_exception!(PyLookupError, ctx, &excs.lookup_error);
|
||||
extend_exception!(PyIndexError, ctx, &excs.index_error);
|
||||
extend_exception!(PyKeyError, ctx, &excs.key_error, {
|
||||
"__str__" => ctx.new_method("__str__", excs.key_error.clone(), key_error_str),
|
||||
extend_exception!(PyLookupError, ctx, excs.lookup_error);
|
||||
extend_exception!(PyIndexError, ctx, excs.index_error);
|
||||
extend_exception!(PyKeyError, ctx, excs.key_error, {
|
||||
"__str__" => ctx.new_method("__str__", excs.key_error, key_error_str),
|
||||
});
|
||||
|
||||
extend_exception!(PyMemoryError, ctx, &excs.memory_error);
|
||||
extend_exception!(PyNameError, ctx, &excs.name_error, {
|
||||
extend_exception!(PyMemoryError, ctx, excs.memory_error);
|
||||
extend_exception!(PyNameError, ctx, excs.name_error, {
|
||||
"name" => ctx.none(),
|
||||
});
|
||||
extend_exception!(PyUnboundLocalError, ctx, &excs.unbound_local_error);
|
||||
extend_exception!(PyUnboundLocalError, ctx, excs.unbound_local_error);
|
||||
|
||||
// os errors:
|
||||
let errno_getter =
|
||||
ctx.new_readonly_getset("errno", excs.os_error.clone(), |exc: PyBaseExceptionRef| {
|
||||
ctx.new_readonly_getset("errno", excs.os_error, |exc: PyBaseExceptionRef| {
|
||||
let args = exc.args();
|
||||
args.get(0).filter(|_| args.len() > 1).cloned()
|
||||
});
|
||||
extend_exception!(PyOSError, ctx, &excs.os_error, {
|
||||
extend_exception!(PyOSError, ctx, excs.os_error, {
|
||||
// POSIX exception code
|
||||
"errno" => errno_getter.clone(),
|
||||
// exception strerror
|
||||
"strerror" => ctx.new_readonly_getset("strerror", excs.os_error.clone(), make_arg_getter(1)),
|
||||
"strerror" => ctx.new_readonly_getset("strerror", excs.os_error, make_arg_getter(1)),
|
||||
// exception filename
|
||||
"filename" => ctx.none(),
|
||||
// second exception filename
|
||||
"filename2" => ctx.none(),
|
||||
"__str__" => ctx.new_method("__str__", excs.os_error.clone(), os_error_str),
|
||||
"__str__" => ctx.new_method("__str__", excs.os_error, os_error_str),
|
||||
});
|
||||
// TODO: this isn't really accurate
|
||||
#[cfg(windows)]
|
||||
excs.os_error
|
||||
.set_str_attr("winerror", errno_getter.clone(), ctx);
|
||||
|
||||
extend_exception!(PyBlockingIOError, ctx, &excs.blocking_io_error);
|
||||
extend_exception!(PyChildProcessError, ctx, &excs.child_process_error);
|
||||
extend_exception!(PyBlockingIOError, ctx, excs.blocking_io_error);
|
||||
extend_exception!(PyChildProcessError, ctx, excs.child_process_error);
|
||||
|
||||
extend_exception!(PyConnectionError, ctx, &excs.connection_error);
|
||||
extend_exception!(PyBrokenPipeError, ctx, &excs.broken_pipe_error);
|
||||
extend_exception!(
|
||||
PyConnectionAbortedError,
|
||||
ctx,
|
||||
&excs.connection_aborted_error
|
||||
);
|
||||
extend_exception!(
|
||||
PyConnectionRefusedError,
|
||||
ctx,
|
||||
&excs.connection_refused_error
|
||||
);
|
||||
extend_exception!(PyConnectionResetError, ctx, &excs.connection_reset_error);
|
||||
extend_exception!(PyConnectionError, ctx, excs.connection_error);
|
||||
extend_exception!(PyBrokenPipeError, ctx, excs.broken_pipe_error);
|
||||
extend_exception!(PyConnectionAbortedError, ctx, excs.connection_aborted_error);
|
||||
extend_exception!(PyConnectionRefusedError, ctx, excs.connection_refused_error);
|
||||
extend_exception!(PyConnectionResetError, ctx, excs.connection_reset_error);
|
||||
|
||||
extend_exception!(PyFileExistsError, ctx, &excs.file_exists_error);
|
||||
extend_exception!(PyFileNotFoundError, ctx, &excs.file_not_found_error);
|
||||
extend_exception!(PyInterruptedError, ctx, &excs.interrupted_error);
|
||||
extend_exception!(PyIsADirectoryError, ctx, &excs.is_a_directory_error);
|
||||
extend_exception!(PyNotADirectoryError, ctx, &excs.not_a_directory_error);
|
||||
extend_exception!(PyPermissionError, ctx, &excs.permission_error);
|
||||
extend_exception!(PyProcessLookupError, ctx, &excs.process_lookup_error);
|
||||
extend_exception!(PyTimeoutError, ctx, &excs.timeout_error);
|
||||
extend_exception!(PyFileExistsError, ctx, excs.file_exists_error);
|
||||
extend_exception!(PyFileNotFoundError, ctx, excs.file_not_found_error);
|
||||
extend_exception!(PyInterruptedError, ctx, excs.interrupted_error);
|
||||
extend_exception!(PyIsADirectoryError, ctx, excs.is_a_directory_error);
|
||||
extend_exception!(PyNotADirectoryError, ctx, excs.not_a_directory_error);
|
||||
extend_exception!(PyPermissionError, ctx, excs.permission_error);
|
||||
extend_exception!(PyProcessLookupError, ctx, excs.process_lookup_error);
|
||||
extend_exception!(PyTimeoutError, ctx, excs.timeout_error);
|
||||
|
||||
extend_exception!(PyReferenceError, ctx, &excs.reference_error);
|
||||
extend_exception!(PyRuntimeError, ctx, &excs.runtime_error);
|
||||
extend_exception!(PyNotImplementedError, ctx, &excs.not_implemented_error);
|
||||
extend_exception!(PyRecursionError, ctx, &excs.recursion_error);
|
||||
extend_exception!(PyReferenceError, ctx, excs.reference_error);
|
||||
extend_exception!(PyRuntimeError, ctx, excs.runtime_error);
|
||||
extend_exception!(PyNotImplementedError, ctx, excs.not_implemented_error);
|
||||
extend_exception!(PyRecursionError, ctx, excs.recursion_error);
|
||||
|
||||
extend_exception!(PySyntaxError, ctx, &excs.syntax_error, {
|
||||
"msg" => ctx.new_readonly_getset("msg", excs.syntax_error.clone(), make_arg_getter(0)),
|
||||
extend_exception!(PySyntaxError, ctx, excs.syntax_error, {
|
||||
"msg" => ctx.new_readonly_getset("msg", excs.syntax_error, make_arg_getter(0)),
|
||||
// TODO: members
|
||||
"filename" => ctx.none(),
|
||||
"lineno" => ctx.none(),
|
||||
"offset" => ctx.none(),
|
||||
"text" => ctx.none(),
|
||||
});
|
||||
extend_exception!(PyIndentationError, ctx, &excs.indentation_error);
|
||||
extend_exception!(PyTabError, ctx, &excs.tab_error);
|
||||
extend_exception!(PyIndentationError, ctx, excs.indentation_error);
|
||||
extend_exception!(PyTabError, ctx, excs.tab_error);
|
||||
|
||||
extend_exception!(PySystemError, ctx, &excs.system_error);
|
||||
extend_exception!(PyTypeError, ctx, &excs.type_error);
|
||||
extend_exception!(PyValueError, ctx, &excs.value_error);
|
||||
extend_exception!(PyUnicodeError, ctx, &excs.unicode_error);
|
||||
extend_exception!(PyUnicodeDecodeError, ctx, &excs.unicode_decode_error, {
|
||||
"encoding" => ctx.new_readonly_getset("encoding", excs.unicode_decode_error.clone(), make_arg_getter(0)),
|
||||
"object" => ctx.new_readonly_getset("object", excs.unicode_decode_error.clone(), make_arg_getter(1)),
|
||||
"start" => ctx.new_readonly_getset("start", excs.unicode_decode_error.clone(), make_arg_getter(2)),
|
||||
"end" => ctx.new_readonly_getset("end", excs.unicode_decode_error.clone(), make_arg_getter(3)),
|
||||
"reason" => ctx.new_readonly_getset("reason", excs.unicode_decode_error.clone(), make_arg_getter(4)),
|
||||
extend_exception!(PySystemError, ctx, excs.system_error);
|
||||
extend_exception!(PyTypeError, ctx, excs.type_error);
|
||||
extend_exception!(PyValueError, ctx, excs.value_error);
|
||||
extend_exception!(PyUnicodeError, ctx, excs.unicode_error);
|
||||
extend_exception!(PyUnicodeDecodeError, ctx, excs.unicode_decode_error, {
|
||||
"encoding" => ctx.new_readonly_getset("encoding", excs.unicode_decode_error, make_arg_getter(0)),
|
||||
"object" => ctx.new_readonly_getset("object", excs.unicode_decode_error, make_arg_getter(1)),
|
||||
"start" => ctx.new_readonly_getset("start", excs.unicode_decode_error, make_arg_getter(2)),
|
||||
"end" => ctx.new_readonly_getset("end", excs.unicode_decode_error, make_arg_getter(3)),
|
||||
"reason" => ctx.new_readonly_getset("reason", excs.unicode_decode_error, make_arg_getter(4)),
|
||||
});
|
||||
extend_exception!(PyUnicodeEncodeError, ctx, &excs.unicode_encode_error, {
|
||||
"encoding" => ctx.new_readonly_getset("encoding", excs.unicode_encode_error.clone(), make_arg_getter(0)),
|
||||
"object" => ctx.new_readonly_getset("object", excs.unicode_encode_error.clone(), make_arg_getter(1)),
|
||||
"start" => ctx.new_readonly_getset("start", excs.unicode_encode_error.clone(), make_arg_getter(2), ),
|
||||
"end" => ctx.new_readonly_getset("end", excs.unicode_encode_error.clone(), make_arg_getter(3)),
|
||||
"reason" => ctx.new_readonly_getset("reason", excs.unicode_encode_error.clone(), make_arg_getter(4)),
|
||||
extend_exception!(PyUnicodeEncodeError, ctx, excs.unicode_encode_error, {
|
||||
"encoding" => ctx.new_readonly_getset("encoding", excs.unicode_encode_error, make_arg_getter(0)),
|
||||
"object" => ctx.new_readonly_getset("object", excs.unicode_encode_error, make_arg_getter(1)),
|
||||
"start" => ctx.new_readonly_getset("start", excs.unicode_encode_error, make_arg_getter(2), ),
|
||||
"end" => ctx.new_readonly_getset("end", excs.unicode_encode_error, make_arg_getter(3)),
|
||||
"reason" => ctx.new_readonly_getset("reason", excs.unicode_encode_error, make_arg_getter(4)),
|
||||
});
|
||||
extend_exception!(PyUnicodeTranslateError, ctx, &excs.unicode_translate_error, {
|
||||
"encoding" => ctx.new_readonly_getset("encoding", excs.unicode_translate_error.clone(), none_getter),
|
||||
"object" => ctx.new_readonly_getset("object", excs.unicode_translate_error.clone(), make_arg_getter(0)),
|
||||
"start" => ctx.new_readonly_getset("start", excs.unicode_translate_error.clone(), make_arg_getter(1)),
|
||||
"end" => ctx.new_readonly_getset("end", excs.unicode_translate_error.clone(), make_arg_getter(2)),
|
||||
"reason" => ctx.new_readonly_getset("reason", excs.unicode_translate_error.clone(), make_arg_getter(3)),
|
||||
extend_exception!(PyUnicodeTranslateError, ctx, excs.unicode_translate_error, {
|
||||
"encoding" => ctx.new_readonly_getset("encoding", excs.unicode_translate_error, none_getter),
|
||||
"object" => ctx.new_readonly_getset("object", excs.unicode_translate_error, make_arg_getter(0)),
|
||||
"start" => ctx.new_readonly_getset("start", excs.unicode_translate_error, make_arg_getter(1)),
|
||||
"end" => ctx.new_readonly_getset("end", excs.unicode_translate_error, make_arg_getter(2)),
|
||||
"reason" => ctx.new_readonly_getset("reason", excs.unicode_translate_error, make_arg_getter(3)),
|
||||
});
|
||||
|
||||
#[cfg(feature = "jit")]
|
||||
extend_exception!(PyJitError, ctx, &excs.jit_error);
|
||||
extend_exception!(PyJitError, ctx, excs.jit_error);
|
||||
|
||||
extend_exception!(PyWarning, ctx, &excs.warning);
|
||||
extend_exception!(PyDeprecationWarning, ctx, &excs.deprecation_warning);
|
||||
extend_exception!(PyWarning, ctx, excs.warning);
|
||||
extend_exception!(PyDeprecationWarning, ctx, excs.deprecation_warning);
|
||||
extend_exception!(
|
||||
PyPendingDeprecationWarning,
|
||||
ctx,
|
||||
&excs.pending_deprecation_warning
|
||||
excs.pending_deprecation_warning
|
||||
);
|
||||
extend_exception!(PyRuntimeWarning, ctx, &excs.runtime_warning);
|
||||
extend_exception!(PySyntaxWarning, ctx, &excs.syntax_warning);
|
||||
extend_exception!(PyUserWarning, ctx, &excs.user_warning);
|
||||
extend_exception!(PyFutureWarning, ctx, &excs.future_warning);
|
||||
extend_exception!(PyImportWarning, ctx, &excs.import_warning);
|
||||
extend_exception!(PyUnicodeWarning, ctx, &excs.unicode_warning);
|
||||
extend_exception!(PyBytesWarning, ctx, &excs.bytes_warning);
|
||||
extend_exception!(PyResourceWarning, ctx, &excs.resource_warning);
|
||||
extend_exception!(PyEncodingWarning, ctx, &excs.encoding_warning);
|
||||
extend_exception!(PyRuntimeWarning, ctx, excs.runtime_warning);
|
||||
extend_exception!(PySyntaxWarning, ctx, excs.syntax_warning);
|
||||
extend_exception!(PyUserWarning, ctx, excs.user_warning);
|
||||
extend_exception!(PyFutureWarning, ctx, excs.future_warning);
|
||||
extend_exception!(PyImportWarning, ctx, excs.import_warning);
|
||||
extend_exception!(PyUnicodeWarning, ctx, excs.unicode_warning);
|
||||
extend_exception!(PyBytesWarning, ctx, excs.bytes_warning);
|
||||
extend_exception!(PyResourceWarning, ctx, excs.resource_warning);
|
||||
extend_exception!(PyEncodingWarning, ctx, excs.encoding_warning);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1007,35 +999,41 @@ impl<C: widestring::UChar> ToPyException for widestring::NulError<C> {
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows, target_os = "wasi"))]
|
||||
pub(crate) fn raw_os_error_to_exc_type(errno: i32, vm: &VirtualMachine) -> Option<PyTypeRef> {
|
||||
pub(crate) fn raw_os_error_to_exc_type(
|
||||
errno: i32,
|
||||
vm: &VirtualMachine,
|
||||
) -> Option<&'static Py<PyType>> {
|
||||
use crate::stdlib::errno::errors;
|
||||
let excs = &vm.ctx.exceptions;
|
||||
match errno {
|
||||
errors::EWOULDBLOCK => Some(excs.blocking_io_error.clone()),
|
||||
errors::EALREADY => Some(excs.blocking_io_error.clone()),
|
||||
errors::EINPROGRESS => Some(excs.blocking_io_error.clone()),
|
||||
errors::EPIPE => Some(excs.broken_pipe_error.clone()),
|
||||
errors::EWOULDBLOCK => Some(excs.blocking_io_error),
|
||||
errors::EALREADY => Some(excs.blocking_io_error),
|
||||
errors::EINPROGRESS => Some(excs.blocking_io_error),
|
||||
errors::EPIPE => Some(excs.broken_pipe_error),
|
||||
#[cfg(not(target_os = "wasi"))]
|
||||
errors::ESHUTDOWN => Some(excs.broken_pipe_error.clone()),
|
||||
errors::ECHILD => Some(excs.child_process_error.clone()),
|
||||
errors::ECONNABORTED => Some(excs.connection_aborted_error.clone()),
|
||||
errors::ECONNREFUSED => Some(excs.connection_refused_error.clone()),
|
||||
errors::ECONNRESET => Some(excs.connection_reset_error.clone()),
|
||||
errors::EEXIST => Some(excs.file_exists_error.clone()),
|
||||
errors::ENOENT => Some(excs.file_not_found_error.clone()),
|
||||
errors::EISDIR => Some(excs.is_a_directory_error.clone()),
|
||||
errors::ENOTDIR => Some(excs.not_a_directory_error.clone()),
|
||||
errors::EINTR => Some(excs.interrupted_error.clone()),
|
||||
errors::EACCES => Some(excs.permission_error.clone()),
|
||||
errors::EPERM => Some(excs.permission_error.clone()),
|
||||
errors::ESRCH => Some(excs.process_lookup_error.clone()),
|
||||
errors::ETIMEDOUT => Some(excs.timeout_error.clone()),
|
||||
errors::ESHUTDOWN => Some(excs.broken_pipe_error),
|
||||
errors::ECHILD => Some(excs.child_process_error),
|
||||
errors::ECONNABORTED => Some(excs.connection_aborted_error),
|
||||
errors::ECONNREFUSED => Some(excs.connection_refused_error),
|
||||
errors::ECONNRESET => Some(excs.connection_reset_error),
|
||||
errors::EEXIST => Some(excs.file_exists_error),
|
||||
errors::ENOENT => Some(excs.file_not_found_error),
|
||||
errors::EISDIR => Some(excs.is_a_directory_error),
|
||||
errors::ENOTDIR => Some(excs.not_a_directory_error),
|
||||
errors::EINTR => Some(excs.interrupted_error),
|
||||
errors::EACCES => Some(excs.permission_error),
|
||||
errors::EPERM => Some(excs.permission_error),
|
||||
errors::ESRCH => Some(excs.process_lookup_error),
|
||||
errors::ETIMEDOUT => Some(excs.timeout_error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
|
||||
pub(crate) fn raw_os_error_to_exc_type(_errno: i32, _vm: &VirtualMachine) -> Option<PyTypeRef> {
|
||||
pub(crate) fn raw_os_error_to_exc_type(
|
||||
_errno: i32,
|
||||
_vm: &VirtualMachine,
|
||||
) -> Option<&'static Py<PyType>> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -1253,7 +1251,7 @@ pub(super) mod types {
|
||||
.payload_if_subclass::<PyInt>(vm)
|
||||
.and_then(|errno| errno.try_to_primitive::<i32>(vm).ok())
|
||||
.and_then(|errno| super::raw_os_error_to_exc_type(errno, vm))
|
||||
.and_then(|typ| vm.invoke_exception(typ, args.to_vec()).ok())
|
||||
.and_then(|typ| vm.invoke_exception(typ.to_owned(), args.to_vec()).ok())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::{
|
||||
function::{PyCell, PyCellRef, PyFunction},
|
||||
tuple::{PyTuple, PyTupleTyped},
|
||||
PyBaseExceptionRef, PyCode, PyCoroutine, PyDict, PyDictRef, PyGenerator, PyList, PySet,
|
||||
PySlice, PyStr, PyStrInterned, PyStrRef, PyTraceback, PyTypeRef,
|
||||
PySlice, PyStr, PyStrInterned, PyStrRef, PyTraceback, PyType,
|
||||
},
|
||||
bytecode,
|
||||
convert::{IntoObject, ToPyResult},
|
||||
@@ -114,8 +114,8 @@ pub struct Frame {
|
||||
}
|
||||
|
||||
impl PyPayload for Frame {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef {
|
||||
&vm.ctx.types.frame_type
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
|
||||
vm.ctx.types.frame_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ impl FrameRef {
|
||||
for (&k, v) in itertools::zip(&map[..j], &**fastlocals) {
|
||||
match locals.mapping().ass_subscript(k, v.clone(), vm) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.fast_isinstance(&vm.ctx.exceptions.key_error) => {}
|
||||
Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
@@ -203,7 +203,7 @@ impl FrameRef {
|
||||
} else {
|
||||
match locals.mapping().ass_subscript(k, None, vm) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.fast_isinstance(&vm.ctx.exceptions.key_error) => {}
|
||||
Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
@@ -404,7 +404,7 @@ impl ExecutingFrame<'_> {
|
||||
return ret.map(ExecutionResult::Yield).or_else(|err| {
|
||||
self.pop_value();
|
||||
self.update_lasti(|i| *i += 1);
|
||||
if err.fast_isinstance(&vm.ctx.exceptions.stop_iteration) {
|
||||
if err.fast_isinstance(vm.ctx.exceptions.stop_iteration) {
|
||||
let val = vm.unwrap_or_none(err.get_arg(0));
|
||||
self.push_value(val);
|
||||
self.run(vm)
|
||||
@@ -426,7 +426,7 @@ impl ExecutingFrame<'_> {
|
||||
fn unbound_cell_exception(&self, i: usize, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
if let Some(&name) = self.code.cellvars.get(i) {
|
||||
vm.new_exception_msg(
|
||||
vm.ctx.exceptions.unbound_local_error.clone(),
|
||||
vm.ctx.exceptions.unbound_local_error.to_owned(),
|
||||
format!("local variable '{}' referenced before assignment", name),
|
||||
)
|
||||
} else {
|
||||
@@ -484,7 +484,7 @@ impl ExecutingFrame<'_> {
|
||||
let idx = *idx as usize;
|
||||
let x = self.fastlocals.lock()[idx].clone().ok_or_else(|| {
|
||||
vm.new_exception_msg(
|
||||
vm.ctx.exceptions.unbound_local_error.clone(),
|
||||
vm.ctx.exceptions.unbound_local_error.to_owned(),
|
||||
format!(
|
||||
"local variable '{}' referenced before assignment",
|
||||
self.code.varnames[idx]
|
||||
@@ -561,7 +561,7 @@ impl ExecutingFrame<'_> {
|
||||
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.fast_isinstance(&vm.ctx.exceptions.key_error) => {
|
||||
Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {
|
||||
return Err(vm.new_name_error(
|
||||
format!("name '{}' is not defined", name),
|
||||
name.to_owned(),
|
||||
@@ -575,7 +575,7 @@ impl ExecutingFrame<'_> {
|
||||
let name = self.code.names[*idx as usize];
|
||||
match self.globals.del_item(name, vm) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.fast_isinstance(&vm.ctx.exceptions.key_error) => {
|
||||
Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {
|
||||
return Err(vm.new_name_error(
|
||||
format!("name '{}' is not defined", name),
|
||||
name.to_owned(),
|
||||
@@ -905,7 +905,7 @@ impl ExecutingFrame<'_> {
|
||||
bytecode::Instruction::EndAsyncFor => {
|
||||
let exc = self.pop_value();
|
||||
self.pop_value(); // async iterator we were calling __anext__ on
|
||||
if exc.fast_isinstance(&vm.ctx.exceptions.stop_async_iteration) {
|
||||
if exc.fast_isinstance(vm.ctx.exceptions.stop_async_iteration) {
|
||||
vm.take_exception().expect("Should have exception in stack");
|
||||
Ok(None)
|
||||
} else {
|
||||
@@ -1022,7 +1022,7 @@ impl ExecutingFrame<'_> {
|
||||
bytecode::Instruction::UnpackSequence { size } => {
|
||||
let value = self.pop_value();
|
||||
let elements: Vec<_> = value.try_to_value(vm).map_err(|e| {
|
||||
if e.class().is(&vm.ctx.exceptions.type_error) {
|
||||
if e.class().is(vm.ctx.exceptions.type_error) {
|
||||
vm.new_type_error(format!(
|
||||
"cannot unpack non-iterable {} object",
|
||||
value.class().name()
|
||||
|
||||
@@ -203,7 +203,7 @@ pub fn remove_importlib_frames(
|
||||
vm: &VirtualMachine,
|
||||
exc: &PyBaseExceptionRef,
|
||||
) -> PyBaseExceptionRef {
|
||||
let always_trim = exc.fast_isinstance(&vm.ctx.exceptions.import_error);
|
||||
let always_trim = exc.fast_isinstance(vm.ctx.exceptions.import_error);
|
||||
|
||||
if let Some(tb) = exc.traceback() {
|
||||
let trimmed_tb = remove_importlib_frames_inner(vm, Some(tb), always_trim).0;
|
||||
|
||||
@@ -600,7 +600,7 @@ impl PyObject {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let cls_is_weakref = typ.is(&vm.ctx.types.weakref_type);
|
||||
let cls_is_weakref = typ.is(vm.ctx.types.weakref_type);
|
||||
self.weak_ref_list()
|
||||
.map(|wrl| wrl.add(self, typ, cls_is_weakref, callback, dict))
|
||||
.ok_or_else(|| {
|
||||
@@ -616,7 +616,7 @@ impl PyObject {
|
||||
callback: Option<PyObjectRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyRef<PyWeak>> {
|
||||
self.downgrade_with_typ(callback, vm.ctx.types.weakref_type.clone(), vm)
|
||||
self.downgrade_with_typ(callback, vm.ctx.types.weakref_type.to_owned(), vm)
|
||||
}
|
||||
|
||||
pub fn get_weak_references(&self) -> Option<Vec<PyRef<PyWeak>>> {
|
||||
@@ -968,6 +968,12 @@ impl<T: PyObjectPayload> PyRef<T> {
|
||||
ptr: unsafe { NonNull::new_unchecked(inner.cast::<Py<T>>()) },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn leak(pyref: Self) -> &'static Py<T> {
|
||||
let ptr = pyref.ptr;
|
||||
std::mem::forget(pyref);
|
||||
unsafe { &*ptr.as_ptr() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Borrow<PyObject> for PyRef<T>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{PyObject, PyObjectRef, PyRef, PyResult};
|
||||
use super::{Py, PyObject, PyObjectRef, PyRef, PyResult};
|
||||
use crate::{
|
||||
builtins::{PyBaseExceptionRef, PyTypeRef},
|
||||
builtins::{PyBaseExceptionRef, PyType, PyTypeRef},
|
||||
types::PyTypeFlags,
|
||||
vm::VirtualMachine,
|
||||
};
|
||||
@@ -16,7 +16,7 @@ cfg_if::cfg_if! {
|
||||
}
|
||||
|
||||
pub trait PyPayload: std::fmt::Debug + PyThreadingConstraint + Sized + 'static {
|
||||
fn class(vm: &VirtualMachine) -> &PyTypeRef;
|
||||
fn class(vm: &VirtualMachine) -> &'static Py<PyType>;
|
||||
|
||||
#[inline]
|
||||
fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
|
||||
@@ -41,7 +41,7 @@ pub trait PyPayload: std::fmt::Debug + PyThreadingConstraint + Sized + 'static {
|
||||
#[inline]
|
||||
fn into_ref(self, vm: &VirtualMachine) -> PyRef<Self> {
|
||||
let cls = Self::class(vm);
|
||||
self._into_ref(cls.clone(), vm)
|
||||
self._into_ref(cls.to_owned(), vm)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -55,7 +55,7 @@ pub trait PyPayload: std::fmt::Debug + PyThreadingConstraint + Sized + 'static {
|
||||
fn _into_ref_with_type_error(
|
||||
vm: &VirtualMachine,
|
||||
cls: &PyTypeRef,
|
||||
exact_class: &PyTypeRef,
|
||||
exact_class: &Py<PyType>,
|
||||
) -> PyBaseExceptionRef {
|
||||
vm.new_type_error(format!(
|
||||
"'{}' is not a subtype of '{}'",
|
||||
|
||||
@@ -153,7 +153,7 @@ impl PyIterReturn {
|
||||
pub fn from_pyresult(result: PyResult, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
match result {
|
||||
Ok(obj) => Ok(Self::Return(obj)),
|
||||
Err(err) if err.fast_isinstance(&vm.ctx.exceptions.stop_iteration) => {
|
||||
Err(err) if err.fast_isinstance(vm.ctx.exceptions.stop_iteration) => {
|
||||
let args = err.get_arg(0);
|
||||
Ok(Self::StopIteration(args))
|
||||
}
|
||||
@@ -164,10 +164,10 @@ impl PyIterReturn {
|
||||
pub fn from_getitem_result(result: PyResult, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
match result {
|
||||
Ok(obj) => Ok(Self::Return(obj)),
|
||||
Err(err) if err.fast_isinstance(&vm.ctx.exceptions.index_error) => {
|
||||
Err(err) if err.fast_isinstance(vm.ctx.exceptions.index_error) => {
|
||||
Ok(Self::StopIteration(None))
|
||||
}
|
||||
Err(err) if err.fast_isinstance(&vm.ctx.exceptions.stop_iteration) => {
|
||||
Err(err) if err.fast_isinstance(vm.ctx.exceptions.stop_iteration) => {
|
||||
let args = err.get_arg(0);
|
||||
Ok(Self::StopIteration(args))
|
||||
}
|
||||
@@ -180,7 +180,7 @@ impl PyIterReturn {
|
||||
Self::Return(obj) => Ok(obj),
|
||||
Self::StopIteration(v) => Err({
|
||||
let args = if let Some(v) = v { vec![v] } else { Vec::new() };
|
||||
vm.new_exception(vm.ctx.exceptions.stop_async_iteration.clone(), args)
|
||||
vm.new_exception(vm.ctx.exceptions.stop_async_iteration.to_owned(), args)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ impl PyMapping<'_> {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
let meth_output = vm.call_method(self.obj, method_name.as_str(), ())?;
|
||||
if meth_output.is(&vm.ctx.types.list_type) {
|
||||
if meth_output.is(vm.ctx.types.list_type) {
|
||||
return Ok(meth_output);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,11 +33,11 @@ impl PyObjectRef {
|
||||
}
|
||||
|
||||
pub fn bytes(self, vm: &VirtualMachine) -> PyResult {
|
||||
let bytes_type = &vm.ctx.types.bytes_type;
|
||||
let bytes_type = vm.ctx.types.bytes_type;
|
||||
match self.downcast_exact::<PyInt>(vm) {
|
||||
Ok(int) => Err(vm.new_downcast_type_error(bytes_type, &int)),
|
||||
Err(obj) => PyBytes::py_new(
|
||||
bytes_type.clone(),
|
||||
bytes_type.to_owned(),
|
||||
ByteInnerNewOptions {
|
||||
source: OptionalArg::Present(obj),
|
||||
encoding: OptionalArg::Missing,
|
||||
@@ -159,7 +159,7 @@ impl PyObject {
|
||||
dict.set_item(&*attr_name, value, vm)?;
|
||||
} else {
|
||||
dict.del_item(&*attr_name, vm).map_err(|e| {
|
||||
if e.fast_isinstance(&vm.ctx.exceptions.key_error) {
|
||||
if e.fast_isinstance(vm.ctx.exceptions.key_error) {
|
||||
vm.new_attribute_error(format!(
|
||||
"'{}' object has no attribute '{}'",
|
||||
self.class().name(),
|
||||
@@ -327,7 +327,7 @@ impl PyObject {
|
||||
|
||||
// Container of the virtual machine state:
|
||||
pub fn str(&self, vm: &VirtualMachine) -> PyResult<PyStrRef> {
|
||||
if self.class().is(&vm.ctx.types.str_type) {
|
||||
if self.class().is(vm.ctx.types.str_type) {
|
||||
Ok(self.to_owned().downcast().unwrap())
|
||||
} else {
|
||||
let s = vm.call_special_method(self.to_owned(), identifier!(vm, __str__), ())?;
|
||||
@@ -345,7 +345,7 @@ impl PyObject {
|
||||
.get_attr(identifier!(vm, __bases__), vm)
|
||||
.map_err(|e| {
|
||||
// Only mask AttributeErrors.
|
||||
if e.class().is(&vm.ctx.exceptions.attribute_error) {
|
||||
if e.class().is(vm.ctx.exceptions.attribute_error) {
|
||||
vm.new_type_error(msg())
|
||||
} else {
|
||||
e
|
||||
@@ -412,7 +412,7 @@ impl PyObject {
|
||||
/// Determines if `self` is a subclass of `cls`, either directly, indirectly or virtually
|
||||
/// via the __subclasscheck__ magic method.
|
||||
pub fn is_subclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
if cls.class().is(&vm.ctx.types.type_type) {
|
||||
if cls.class().is(vm.ctx.types.type_type) {
|
||||
if self.is(cls) {
|
||||
return Ok(true);
|
||||
}
|
||||
@@ -483,7 +483,7 @@ impl PyObject {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
if cls.class().is(&vm.ctx.types.type_type) {
|
||||
if cls.class().is(vm.ctx.types.type_type) {
|
||||
return self.abstract_isinstance(cls, vm);
|
||||
}
|
||||
|
||||
@@ -545,8 +545,8 @@ impl PyObject {
|
||||
let i = needle.key_as_isize(vm)?;
|
||||
seq.get_item(i, vm)
|
||||
} else {
|
||||
if self.class().fast_issubclass(&vm.ctx.types.type_type) {
|
||||
if self.is(&vm.ctx.types.type_type) {
|
||||
if self.class().fast_issubclass(vm.ctx.types.type_type) {
|
||||
if self.is(vm.ctx.types.type_type) {
|
||||
return PyGenericAlias::new(self.class().clone(), needle, vm).to_pyresult(vm);
|
||||
}
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ impl PySequence<'_> {
|
||||
pub fn methods_cow(&self, vm: &VirtualMachine) -> &Cow<'static, PySequenceMethods> {
|
||||
self.methods.get_or_init(|| {
|
||||
let cls = self.obj.class();
|
||||
if !cls.is(&vm.ctx.types.dict_type) {
|
||||
if !cls.is(vm.ctx.types.dict_type) {
|
||||
if let Some(f) = cls.mro_find_map(|x| x.slots.as_sequence.load()) {
|
||||
return f(self.obj, vm);
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ pub fn file_readline(obj: &PyObject, size: Option<usize>, vm: &VirtualMachine) -
|
||||
let ret = vm.call_method(obj, "readline", args)?;
|
||||
let eof_err = || {
|
||||
vm.new_exception(
|
||||
vm.ctx.exceptions.eof_error.clone(),
|
||||
vm.ctx.exceptions.eof_error.to_owned(),
|
||||
vec![vm.ctx.new_str(ascii!("EOF when reading a line")).into()],
|
||||
)
|
||||
};
|
||||
|
||||
@@ -64,11 +64,11 @@ impl<'s> serde::Serialize for PyObjectSerializer<'s> {
|
||||
};
|
||||
if let Some(s) = self.pyobject.payload::<PyStr>() {
|
||||
serializer.serialize_str(s.as_ref())
|
||||
} else if self.pyobject.fast_isinstance(&self.vm.ctx.types.float_type) {
|
||||
} else if self.pyobject.fast_isinstance(self.vm.ctx.types.float_type) {
|
||||
serializer.serialize_f64(float::get_value(self.pyobject))
|
||||
} else if self.pyobject.fast_isinstance(&self.vm.ctx.types.bool_type) {
|
||||
} else if self.pyobject.fast_isinstance(self.vm.ctx.types.bool_type) {
|
||||
serializer.serialize_bool(bool_::get_value(self.pyobject))
|
||||
} else if self.pyobject.fast_isinstance(&self.vm.ctx.types.int_type) {
|
||||
} else if self.pyobject.fast_isinstance(self.vm.ctx.types.int_type) {
|
||||
let v = int::get_value(self.pyobject);
|
||||
let int_too_large = || serde::ser::Error::custom("int too large to serialize");
|
||||
// TODO: serialize BigInt when it does not fit into i64
|
||||
@@ -84,7 +84,7 @@ impl<'s> serde::Serialize for PyObjectSerializer<'s> {
|
||||
serialize_seq_elements(serializer, &list.borrow_vec())
|
||||
} else if let Some(tuple) = self.pyobject.payload_if_subclass::<PyTuple>(self.vm) {
|
||||
serialize_seq_elements(serializer, tuple)
|
||||
} else if self.pyobject.fast_isinstance(&self.vm.ctx.types.dict_type) {
|
||||
} else if self.pyobject.fast_isinstance(self.vm.ctx.types.dict_type) {
|
||||
let dict: PyDictRef = self.pyobject.to_owned().downcast().unwrap();
|
||||
let pairs: Vec<_> = dict.into_iter().collect();
|
||||
let mut map = serializer.serialize_map(Some(pairs.len()))?;
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
mod gen;
|
||||
|
||||
use crate::{
|
||||
builtins::{self, PyStrRef, PyTypeRef},
|
||||
builtins::{self, PyStrRef, PyType},
|
||||
class::{PyClassImpl, StaticType},
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject,
|
||||
VirtualMachine,
|
||||
};
|
||||
use num_complex::Complex64;
|
||||
use num_traits::{ToPrimitive, Zero};
|
||||
@@ -213,7 +214,7 @@ impl Node for ast::Constant {
|
||||
let constant = match_class!(match object {
|
||||
ref i @ builtins::int::PyInt => {
|
||||
let value = i.as_bigint();
|
||||
if object.class().is(&vm.ctx.types.bool_type) {
|
||||
if object.class().is(vm.ctx.types.bool_type) {
|
||||
ast::Constant::Bool(!value.is_zero())
|
||||
} else {
|
||||
ast::Constant::Int(value.clone())
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -37,7 +37,7 @@ mod atexit {
|
||||
let funcs: Vec<_> = std::mem::take(&mut *vm.state.atexit_funcs.lock());
|
||||
for (func, args) in funcs.into_iter().rev() {
|
||||
if let Err(e) = vm.invoke(&func, args) {
|
||||
let exit = e.fast_isinstance(&vm.ctx.exceptions.system_exit);
|
||||
let exit = e.fast_isinstance(vm.ctx.exceptions.system_exit);
|
||||
vm.run_unraisable(e, Some("Error in atexit._run_exitfuncs".to_owned()), func);
|
||||
if exit {
|
||||
break;
|
||||
|
||||
@@ -374,10 +374,10 @@ mod builtins {
|
||||
match readline.readline(prompt) {
|
||||
ReadlineResult::Line(s) => Ok(vm.ctx.new_str(s).into()),
|
||||
ReadlineResult::Eof => {
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.eof_error.clone()))
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.eof_error.to_owned()))
|
||||
}
|
||||
ReadlineResult::Interrupt => {
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.clone()))
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned()))
|
||||
}
|
||||
ReadlineResult::Io(e) => Err(vm.new_os_error(e.to_string())),
|
||||
ReadlineResult::EncodingError => {
|
||||
@@ -634,7 +634,7 @@ mod builtins {
|
||||
#[pyfunction]
|
||||
pub fn exit(exit_code_arg: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
|
||||
let code = exit_code_arg.unwrap_or_else(|| vm.ctx.new_int(0).into());
|
||||
Err(vm.new_exception(vm.ctx.exceptions.system_exit.clone(), vec![code]))
|
||||
Err(vm.new_exception(vm.ctx.exceptions.system_exit.to_owned(), vec![code]))
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, FromArgs)]
|
||||
@@ -820,7 +820,7 @@ mod builtins {
|
||||
let mut new_bases: Option<Vec<PyObjectRef>> = None;
|
||||
let bases = PyTuple::new_ref(bases.into_vec(), &vm.ctx);
|
||||
for (i, base) in bases.iter().enumerate() {
|
||||
if base.fast_isinstance(&vm.ctx.types.type_type) {
|
||||
if base.fast_isinstance(vm.ctx.types.type_type) {
|
||||
if let Some(bases) = &mut new_bases {
|
||||
bases.push(base.clone());
|
||||
}
|
||||
@@ -854,7 +854,7 @@ mod builtins {
|
||||
let metaclass = kwargs
|
||||
.pop_kwarg("metaclass")
|
||||
.map(|metaclass| metaclass.downcast_exact::<PyType>(vm))
|
||||
.unwrap_or_else(|| Ok(vm.ctx.types.type_type.clone()));
|
||||
.unwrap_or_else(|| Ok(vm.ctx.types.type_type.to_owned()));
|
||||
|
||||
let (metaclass, meta_name) = match metaclass {
|
||||
Ok(mut metaclass) => {
|
||||
@@ -934,31 +934,31 @@ pub fn make_module(vm: &VirtualMachine, module: PyObjectRef) {
|
||||
extend_module!(vm, module, {
|
||||
"__debug__" => ctx.new_bool(debug_mode),
|
||||
|
||||
"bool" => ctx.types.bool_type.clone(),
|
||||
"bytearray" => ctx.types.bytearray_type.clone(),
|
||||
"bytes" => ctx.types.bytes_type.clone(),
|
||||
"classmethod" => ctx.types.classmethod_type.clone(),
|
||||
"complex" => ctx.types.complex_type.clone(),
|
||||
"dict" => ctx.types.dict_type.clone(),
|
||||
"enumerate" => ctx.types.enumerate_type.clone(),
|
||||
"float" => ctx.types.float_type.clone(),
|
||||
"frozenset" => ctx.types.frozenset_type.clone(),
|
||||
"filter" => ctx.types.filter_type.clone(),
|
||||
"int" => ctx.types.int_type.clone(),
|
||||
"list" => ctx.types.list_type.clone(),
|
||||
"map" => ctx.types.map_type.clone(),
|
||||
"memoryview" => ctx.types.memoryview_type.clone(),
|
||||
"object" => ctx.types.object_type.clone(),
|
||||
"property" => ctx.types.property_type.clone(),
|
||||
"range" => ctx.types.range_type.clone(),
|
||||
"set" => ctx.types.set_type.clone(),
|
||||
"slice" => ctx.types.slice_type.clone(),
|
||||
"staticmethod" => ctx.types.staticmethod_type.clone(),
|
||||
"str" => ctx.types.str_type.clone(),
|
||||
"super" => ctx.types.super_type.clone(),
|
||||
"tuple" => ctx.types.tuple_type.clone(),
|
||||
"type" => ctx.types.type_type.clone(),
|
||||
"zip" => ctx.types.zip_type.clone(),
|
||||
"bool" => ctx.types.bool_type.to_owned(),
|
||||
"bytearray" => ctx.types.bytearray_type.to_owned(),
|
||||
"bytes" => ctx.types.bytes_type.to_owned(),
|
||||
"classmethod" => ctx.types.classmethod_type.to_owned(),
|
||||
"complex" => ctx.types.complex_type.to_owned(),
|
||||
"dict" => ctx.types.dict_type.to_owned(),
|
||||
"enumerate" => ctx.types.enumerate_type.to_owned(),
|
||||
"float" => ctx.types.float_type.to_owned(),
|
||||
"frozenset" => ctx.types.frozenset_type.to_owned(),
|
||||
"filter" => ctx.types.filter_type.to_owned(),
|
||||
"int" => ctx.types.int_type.to_owned(),
|
||||
"list" => ctx.types.list_type.to_owned(),
|
||||
"map" => ctx.types.map_type.to_owned(),
|
||||
"memoryview" => ctx.types.memoryview_type.to_owned(),
|
||||
"object" => ctx.types.object_type.to_owned(),
|
||||
"property" => ctx.types.property_type.to_owned(),
|
||||
"range" => ctx.types.range_type.to_owned(),
|
||||
"set" => ctx.types.set_type.to_owned(),
|
||||
"slice" => ctx.types.slice_type.to_owned(),
|
||||
"staticmethod" => ctx.types.staticmethod_type.to_owned(),
|
||||
"str" => ctx.types.str_type.to_owned(),
|
||||
"super" => ctx.types.super_type.to_owned(),
|
||||
"tuple" => ctx.types.tuple_type.to_owned(),
|
||||
"type" => ctx.types.type_type.to_owned(),
|
||||
"zip" => ctx.types.zip_type.to_owned(),
|
||||
|
||||
// Constants
|
||||
"None" => ctx.none(),
|
||||
@@ -969,80 +969,80 @@ pub fn make_module(vm: &VirtualMachine, module: PyObjectRef) {
|
||||
|
||||
// ordered by exception_hierarachy.txt
|
||||
// Exceptions:
|
||||
"BaseException" => ctx.exceptions.base_exception_type.clone(),
|
||||
"SystemExit" => ctx.exceptions.system_exit.clone(),
|
||||
"KeyboardInterrupt" => ctx.exceptions.keyboard_interrupt.clone(),
|
||||
"GeneratorExit" => ctx.exceptions.generator_exit.clone(),
|
||||
"Exception" => ctx.exceptions.exception_type.clone(),
|
||||
"StopIteration" => ctx.exceptions.stop_iteration.clone(),
|
||||
"StopAsyncIteration" => ctx.exceptions.stop_async_iteration.clone(),
|
||||
"ArithmeticError" => ctx.exceptions.arithmetic_error.clone(),
|
||||
"FloatingPointError" => ctx.exceptions.floating_point_error.clone(),
|
||||
"OverflowError" => ctx.exceptions.overflow_error.clone(),
|
||||
"ZeroDivisionError" => ctx.exceptions.zero_division_error.clone(),
|
||||
"AssertionError" => ctx.exceptions.assertion_error.clone(),
|
||||
"AttributeError" => ctx.exceptions.attribute_error.clone(),
|
||||
"BufferError" => ctx.exceptions.buffer_error.clone(),
|
||||
"EOFError" => ctx.exceptions.eof_error.clone(),
|
||||
"ImportError" => ctx.exceptions.import_error.clone(),
|
||||
"ModuleNotFoundError" => ctx.exceptions.module_not_found_error.clone(),
|
||||
"LookupError" => ctx.exceptions.lookup_error.clone(),
|
||||
"IndexError" => ctx.exceptions.index_error.clone(),
|
||||
"KeyError" => ctx.exceptions.key_error.clone(),
|
||||
"MemoryError" => ctx.exceptions.memory_error.clone(),
|
||||
"NameError" => ctx.exceptions.name_error.clone(),
|
||||
"UnboundLocalError" => ctx.exceptions.unbound_local_error.clone(),
|
||||
"OSError" => ctx.exceptions.os_error.clone(),
|
||||
"BaseException" => ctx.exceptions.base_exception_type.to_owned(),
|
||||
"SystemExit" => ctx.exceptions.system_exit.to_owned(),
|
||||
"KeyboardInterrupt" => ctx.exceptions.keyboard_interrupt.to_owned(),
|
||||
"GeneratorExit" => ctx.exceptions.generator_exit.to_owned(),
|
||||
"Exception" => ctx.exceptions.exception_type.to_owned(),
|
||||
"StopIteration" => ctx.exceptions.stop_iteration.to_owned(),
|
||||
"StopAsyncIteration" => ctx.exceptions.stop_async_iteration.to_owned(),
|
||||
"ArithmeticError" => ctx.exceptions.arithmetic_error.to_owned(),
|
||||
"FloatingPointError" => ctx.exceptions.floating_point_error.to_owned(),
|
||||
"OverflowError" => ctx.exceptions.overflow_error.to_owned(),
|
||||
"ZeroDivisionError" => ctx.exceptions.zero_division_error.to_owned(),
|
||||
"AssertionError" => ctx.exceptions.assertion_error.to_owned(),
|
||||
"AttributeError" => ctx.exceptions.attribute_error.to_owned(),
|
||||
"BufferError" => ctx.exceptions.buffer_error.to_owned(),
|
||||
"EOFError" => ctx.exceptions.eof_error.to_owned(),
|
||||
"ImportError" => ctx.exceptions.import_error.to_owned(),
|
||||
"ModuleNotFoundError" => ctx.exceptions.module_not_found_error.to_owned(),
|
||||
"LookupError" => ctx.exceptions.lookup_error.to_owned(),
|
||||
"IndexError" => ctx.exceptions.index_error.to_owned(),
|
||||
"KeyError" => ctx.exceptions.key_error.to_owned(),
|
||||
"MemoryError" => ctx.exceptions.memory_error.to_owned(),
|
||||
"NameError" => ctx.exceptions.name_error.to_owned(),
|
||||
"UnboundLocalError" => ctx.exceptions.unbound_local_error.to_owned(),
|
||||
"OSError" => ctx.exceptions.os_error.to_owned(),
|
||||
// OSError alias
|
||||
"IOError" => ctx.exceptions.os_error.clone(),
|
||||
"EnvironmentError" => ctx.exceptions.os_error.clone(),
|
||||
"BlockingIOError" => ctx.exceptions.blocking_io_error.clone(),
|
||||
"ChildProcessError" => ctx.exceptions.child_process_error.clone(),
|
||||
"ConnectionError" => ctx.exceptions.connection_error.clone(),
|
||||
"BrokenPipeError" => ctx.exceptions.broken_pipe_error.clone(),
|
||||
"ConnectionAbortedError" => ctx.exceptions.connection_aborted_error.clone(),
|
||||
"ConnectionRefusedError" => ctx.exceptions.connection_refused_error.clone(),
|
||||
"ConnectionResetError" => ctx.exceptions.connection_reset_error.clone(),
|
||||
"FileExistsError" => ctx.exceptions.file_exists_error.clone(),
|
||||
"FileNotFoundError" => ctx.exceptions.file_not_found_error.clone(),
|
||||
"InterruptedError" => ctx.exceptions.interrupted_error.clone(),
|
||||
"IsADirectoryError" => ctx.exceptions.is_a_directory_error.clone(),
|
||||
"NotADirectoryError" => ctx.exceptions.not_a_directory_error.clone(),
|
||||
"PermissionError" => ctx.exceptions.permission_error.clone(),
|
||||
"ProcessLookupError" => ctx.exceptions.process_lookup_error.clone(),
|
||||
"TimeoutError" => ctx.exceptions.timeout_error.clone(),
|
||||
"ReferenceError" => ctx.exceptions.reference_error.clone(),
|
||||
"RuntimeError" => ctx.exceptions.runtime_error.clone(),
|
||||
"NotImplementedError" => ctx.exceptions.not_implemented_error.clone(),
|
||||
"RecursionError" => ctx.exceptions.recursion_error.clone(),
|
||||
"SyntaxError" => ctx.exceptions.syntax_error.clone(),
|
||||
"IndentationError" => ctx.exceptions.indentation_error.clone(),
|
||||
"TabError" => ctx.exceptions.tab_error.clone(),
|
||||
"SystemError" => ctx.exceptions.system_error.clone(),
|
||||
"TypeError" => ctx.exceptions.type_error.clone(),
|
||||
"ValueError" => ctx.exceptions.value_error.clone(),
|
||||
"UnicodeError" => ctx.exceptions.unicode_error.clone(),
|
||||
"UnicodeDecodeError" => ctx.exceptions.unicode_decode_error.clone(),
|
||||
"UnicodeEncodeError" => ctx.exceptions.unicode_encode_error.clone(),
|
||||
"UnicodeTranslateError" => ctx.exceptions.unicode_translate_error.clone(),
|
||||
"IOError" => ctx.exceptions.os_error.to_owned(),
|
||||
"EnvironmentError" => ctx.exceptions.os_error.to_owned(),
|
||||
"BlockingIOError" => ctx.exceptions.blocking_io_error.to_owned(),
|
||||
"ChildProcessError" => ctx.exceptions.child_process_error.to_owned(),
|
||||
"ConnectionError" => ctx.exceptions.connection_error.to_owned(),
|
||||
"BrokenPipeError" => ctx.exceptions.broken_pipe_error.to_owned(),
|
||||
"ConnectionAbortedError" => ctx.exceptions.connection_aborted_error.to_owned(),
|
||||
"ConnectionRefusedError" => ctx.exceptions.connection_refused_error.to_owned(),
|
||||
"ConnectionResetError" => ctx.exceptions.connection_reset_error.to_owned(),
|
||||
"FileExistsError" => ctx.exceptions.file_exists_error.to_owned(),
|
||||
"FileNotFoundError" => ctx.exceptions.file_not_found_error.to_owned(),
|
||||
"InterruptedError" => ctx.exceptions.interrupted_error.to_owned(),
|
||||
"IsADirectoryError" => ctx.exceptions.is_a_directory_error.to_owned(),
|
||||
"NotADirectoryError" => ctx.exceptions.not_a_directory_error.to_owned(),
|
||||
"PermissionError" => ctx.exceptions.permission_error.to_owned(),
|
||||
"ProcessLookupError" => ctx.exceptions.process_lookup_error.to_owned(),
|
||||
"TimeoutError" => ctx.exceptions.timeout_error.to_owned(),
|
||||
"ReferenceError" => ctx.exceptions.reference_error.to_owned(),
|
||||
"RuntimeError" => ctx.exceptions.runtime_error.to_owned(),
|
||||
"NotImplementedError" => ctx.exceptions.not_implemented_error.to_owned(),
|
||||
"RecursionError" => ctx.exceptions.recursion_error.to_owned(),
|
||||
"SyntaxError" => ctx.exceptions.syntax_error.to_owned(),
|
||||
"IndentationError" => ctx.exceptions.indentation_error.to_owned(),
|
||||
"TabError" => ctx.exceptions.tab_error.to_owned(),
|
||||
"SystemError" => ctx.exceptions.system_error.to_owned(),
|
||||
"TypeError" => ctx.exceptions.type_error.to_owned(),
|
||||
"ValueError" => ctx.exceptions.value_error.to_owned(),
|
||||
"UnicodeError" => ctx.exceptions.unicode_error.to_owned(),
|
||||
"UnicodeDecodeError" => ctx.exceptions.unicode_decode_error.to_owned(),
|
||||
"UnicodeEncodeError" => ctx.exceptions.unicode_encode_error.to_owned(),
|
||||
"UnicodeTranslateError" => ctx.exceptions.unicode_translate_error.to_owned(),
|
||||
|
||||
// Warnings
|
||||
"Warning" => ctx.exceptions.warning.clone(),
|
||||
"DeprecationWarning" => ctx.exceptions.deprecation_warning.clone(),
|
||||
"PendingDeprecationWarning" => ctx.exceptions.pending_deprecation_warning.clone(),
|
||||
"RuntimeWarning" => ctx.exceptions.runtime_warning.clone(),
|
||||
"SyntaxWarning" => ctx.exceptions.syntax_warning.clone(),
|
||||
"UserWarning" => ctx.exceptions.user_warning.clone(),
|
||||
"FutureWarning" => ctx.exceptions.future_warning.clone(),
|
||||
"ImportWarning" => ctx.exceptions.import_warning.clone(),
|
||||
"UnicodeWarning" => ctx.exceptions.unicode_warning.clone(),
|
||||
"BytesWarning" => ctx.exceptions.bytes_warning.clone(),
|
||||
"ResourceWarning" => ctx.exceptions.resource_warning.clone(),
|
||||
"EncodingWarning" => ctx.exceptions.encoding_warning.clone(),
|
||||
"Warning" => ctx.exceptions.warning.to_owned(),
|
||||
"DeprecationWarning" => ctx.exceptions.deprecation_warning.to_owned(),
|
||||
"PendingDeprecationWarning" => ctx.exceptions.pending_deprecation_warning.to_owned(),
|
||||
"RuntimeWarning" => ctx.exceptions.runtime_warning.to_owned(),
|
||||
"SyntaxWarning" => ctx.exceptions.syntax_warning.to_owned(),
|
||||
"UserWarning" => ctx.exceptions.user_warning.to_owned(),
|
||||
"FutureWarning" => ctx.exceptions.future_warning.to_owned(),
|
||||
"ImportWarning" => ctx.exceptions.import_warning.to_owned(),
|
||||
"UnicodeWarning" => ctx.exceptions.unicode_warning.to_owned(),
|
||||
"BytesWarning" => ctx.exceptions.bytes_warning.to_owned(),
|
||||
"ResourceWarning" => ctx.exceptions.resource_warning.to_owned(),
|
||||
"EncodingWarning" => ctx.exceptions.encoding_warning.to_owned(),
|
||||
});
|
||||
|
||||
#[cfg(feature = "jit")]
|
||||
extend_module!(vm, module, {
|
||||
"JitError" => ctx.exceptions.jit_error.clone(),
|
||||
"JitError" => ctx.exceptions.jit_error.to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ mod _codecs {
|
||||
let vm = self.vm;
|
||||
let data_str = vm.ctx.new_str(data).into();
|
||||
let encode_exc = vm.new_exception(
|
||||
vm.ctx.exceptions.unicode_encode_error.clone(),
|
||||
vm.ctx.exceptions.unicode_encode_error.to_owned(),
|
||||
vec![
|
||||
vm.ctx.new_str(self.encoding).into(),
|
||||
data_str,
|
||||
@@ -164,7 +164,7 @@ mod _codecs {
|
||||
let vm = self.vm;
|
||||
let data_bytes: PyObjectRef = vm.ctx.new_bytes(data.to_vec()).into();
|
||||
let decode_exc = vm.new_exception(
|
||||
vm.ctx.exceptions.unicode_decode_error.clone(),
|
||||
vm.ctx.exceptions.unicode_decode_error.to_owned(),
|
||||
vec![
|
||||
vm.ctx.new_str(self.encoding).into(),
|
||||
data_bytes.clone(),
|
||||
@@ -222,7 +222,7 @@ mod _codecs {
|
||||
) -> Self::Error {
|
||||
let vm = self.vm;
|
||||
vm.new_exception(
|
||||
vm.ctx.exceptions.unicode_encode_error.clone(),
|
||||
vm.ctx.exceptions.unicode_encode_error.to_owned(),
|
||||
vec![
|
||||
vm.ctx.new_str(self.encoding).into(),
|
||||
vm.ctx.new_str(data).into(),
|
||||
|
||||
@@ -16,7 +16,7 @@ mod _functools {
|
||||
val
|
||||
} else {
|
||||
iter.next().transpose()?.ok_or_else(|| {
|
||||
let exc_type = vm.ctx.exceptions.type_error.clone();
|
||||
let exc_type = vm.ctx.exceptions.type_error.to_owned();
|
||||
vm.new_exception_msg(
|
||||
exc_type,
|
||||
"reduce() of empty sequence with no initial value".to_owned(),
|
||||
|
||||
@@ -29,18 +29,18 @@ impl ToPyException for &'_ std::io::Error {
|
||||
let excs = &vm.ctx.exceptions;
|
||||
#[allow(unreachable_patterns)] // some errors are just aliases of each other
|
||||
let exc_type = match self.kind() {
|
||||
ErrorKind::NotFound => excs.file_not_found_error.clone(),
|
||||
ErrorKind::PermissionDenied => excs.permission_error.clone(),
|
||||
ErrorKind::AlreadyExists => excs.file_exists_error.clone(),
|
||||
ErrorKind::WouldBlock => excs.blocking_io_error.clone(),
|
||||
ErrorKind::NotFound => excs.file_not_found_error,
|
||||
ErrorKind::PermissionDenied => excs.permission_error,
|
||||
ErrorKind::AlreadyExists => excs.file_exists_error,
|
||||
ErrorKind::WouldBlock => excs.blocking_io_error,
|
||||
_ => self
|
||||
.raw_os_error()
|
||||
.and_then(|errno| crate::exceptions::raw_os_error_to_exc_type(errno, vm))
|
||||
.unwrap_or_else(|| excs.os_error.clone()),
|
||||
.unwrap_or(excs.os_error),
|
||||
};
|
||||
let errno = self.raw_os_error().to_pyobject(vm);
|
||||
let msg = vm.ctx.new_str(self.to_string()).into();
|
||||
vm.new_exception(exc_type, vec![errno, msg])
|
||||
vm.new_exception(exc_type.to_owned(), vec![errno, msg])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ pub(crate) fn make_module(vm: &VirtualMachine) -> PyObjectRef {
|
||||
.clone();
|
||||
extend_module!(vm, module, {
|
||||
"UnsupportedOperation" => unsupported_operation,
|
||||
"BlockingIOError" => ctx.exceptions.blocking_io_error.clone(),
|
||||
"BlockingIOError" => ctx.exceptions.blocking_io_error.to_owned(),
|
||||
});
|
||||
|
||||
module
|
||||
@@ -121,7 +121,7 @@ mod _io {
|
||||
recursion::ReprGuard,
|
||||
types::{Constructor, DefaultConstructor, Destructor, Initializer, IterNext, Iterable},
|
||||
vm::VirtualMachine,
|
||||
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
|
||||
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
|
||||
TryFromBorrowedObject, TryFromObject,
|
||||
};
|
||||
use bstr::ByteSlice;
|
||||
@@ -808,7 +808,7 @@ mod _io {
|
||||
self.raw_write(None, self.write_pos as usize..self.write_end as usize, vm)?;
|
||||
let n = n.ok_or_else(|| {
|
||||
vm.new_exception_msg(
|
||||
vm.ctx.exceptions.blocking_io_error.clone(),
|
||||
vm.ctx.exceptions.blocking_io_error.to_owned(),
|
||||
"write could not complete without blocking".to_owned(),
|
||||
)
|
||||
})?;
|
||||
@@ -1006,7 +1006,7 @@ mod _io {
|
||||
// TODO: BlockingIOError(errno, msg, written)
|
||||
// written += self.buffer.len();
|
||||
return Err(vm.new_exception_msg(
|
||||
vm.ctx.exceptions.blocking_io_error.clone(),
|
||||
vm.ctx.exceptions.blocking_io_error.to_owned(),
|
||||
"write could not complete without blocking".to_owned(),
|
||||
));
|
||||
} else {
|
||||
@@ -1343,8 +1343,8 @@ mod _io {
|
||||
let name = match obj.to_owned().get_attr("name", vm) {
|
||||
Ok(name) => Some(name),
|
||||
Err(e)
|
||||
if e.fast_isinstance(&vm.ctx.exceptions.attribute_error)
|
||||
|| e.fast_isinstance(&vm.ctx.exceptions.value_error) =>
|
||||
if e.fast_isinstance(vm.ctx.exceptions.attribute_error)
|
||||
|| e.fast_isinstance(vm.ctx.exceptions.value_error) =>
|
||||
{
|
||||
None
|
||||
}
|
||||
@@ -3561,7 +3561,7 @@ mod _io {
|
||||
|
||||
// Construct a FileIO (subclass of RawIOBase)
|
||||
// This is subsequently consumed by a Buffered Class.
|
||||
let file_io_class = {
|
||||
let file_io_class: &Py<PyType> = {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] {
|
||||
Some(super::fileio::FileIO::static_type())
|
||||
@@ -3569,8 +3569,8 @@ mod _io {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let file_io_class: &PyTypeRef = file_io_class.ok_or_else(|| {
|
||||
}
|
||||
.ok_or_else(|| {
|
||||
new_unsupported_operation(
|
||||
vm,
|
||||
"Couldn't get FileIO, io.open likely isn't supported on your platform".to_owned(),
|
||||
@@ -3641,12 +3641,12 @@ mod _io {
|
||||
PyType::new_ref(
|
||||
"UnsupportedOperation",
|
||||
vec![
|
||||
ctx.exceptions.os_error.clone(),
|
||||
ctx.exceptions.value_error.clone(),
|
||||
ctx.exceptions.os_error.to_owned(),
|
||||
ctx.exceptions.value_error.to_owned(),
|
||||
],
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
ctx.types.type_type.clone(),
|
||||
ctx.types.type_type.to_owned(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -3865,7 +3865,7 @@ mod fileio {
|
||||
zelf.mode.store(mode);
|
||||
let fd = if let Some(opener) = args.opener {
|
||||
let fd = vm.invoke(&opener, (name.clone(), flags))?;
|
||||
if !fd.fast_isinstance(&vm.ctx.types.int_type) {
|
||||
if !fd.fast_isinstance(vm.ctx.types.int_type) {
|
||||
return Err(vm.new_type_error("expected integer from opener".to_owned()));
|
||||
}
|
||||
let fd = i32::try_from_object(vm, fd)?;
|
||||
|
||||
@@ -729,7 +729,7 @@ mod decl {
|
||||
name: &'static str,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<usize> {
|
||||
let is_int = obj.fast_isinstance(&vm.ctx.types.int_type);
|
||||
let is_int = obj.fast_isinstance(vm.ctx.types.int_type);
|
||||
if is_int {
|
||||
let value = int::get_value(&obj).to_usize();
|
||||
if let Some(value) = value {
|
||||
@@ -1066,7 +1066,7 @@ mod decl {
|
||||
tee_data: PyItertoolsTeeData::new(iterator, vm)?,
|
||||
index: AtomicCell::new(0),
|
||||
}
|
||||
.into_ref_with_type(vm, class.clone())?
|
||||
.into_ref_with_type(vm, class.to_owned())?
|
||||
.into())
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ mod decl {
|
||||
fn _dumps(value: PyObjectRef, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
let r = match_class!(match value {
|
||||
pyint @ PyInt => {
|
||||
if pyint.class().is(&vm.ctx.types.bool_type) {
|
||||
if pyint.class().is(vm.ctx.types.bool_type) {
|
||||
let (_, mut bool_bytes) = pyint.as_bigint().to_bytes_le();
|
||||
bool_bytes.push(BOOL_BYTE);
|
||||
bool_bytes
|
||||
@@ -213,7 +213,7 @@ mod decl {
|
||||
})?;
|
||||
let (type_indicator, buf) = full_buff.split_last().ok_or_else(|| {
|
||||
vm.new_exception_msg(
|
||||
vm.ctx.exceptions.eof_error.clone(),
|
||||
vm.ctx.exceptions.eof_error.to_owned(),
|
||||
"EOF where object expected.".to_owned(),
|
||||
)
|
||||
})?;
|
||||
@@ -300,7 +300,7 @@ mod decl {
|
||||
// If prefix is not identifiable, assume CodeObject, error out if it doesn't match.
|
||||
let code = bytecode::CodeObject::from_bytes(&full_buff).map_err(|e| match e {
|
||||
bytecode::CodeDeserializeError::Eof => vm.new_exception_msg(
|
||||
vm.ctx.exceptions.eof_error.clone(),
|
||||
vm.ctx.exceptions.eof_error.to_owned(),
|
||||
"End of file while deserializing bytecode".to_owned(),
|
||||
),
|
||||
_ => vm.new_value_error("Couldn't deserialize python bytecode".to_owned()),
|
||||
|
||||
@@ -198,7 +198,7 @@ mod _operator {
|
||||
fn concat(a: PyObjectRef, b: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
// Best attempt at checking that a is sequence-like.
|
||||
if !a.class().has_attr(identifier!(vm, __getitem__))
|
||||
|| a.fast_isinstance(&vm.ctx.types.dict_type)
|
||||
|| a.fast_isinstance(vm.ctx.types.dict_type)
|
||||
{
|
||||
return Err(
|
||||
vm.new_type_error(format!("{} object can't be concatenated", a.class().name()))
|
||||
@@ -272,7 +272,7 @@ mod _operator {
|
||||
fn length_hint(obj: PyObjectRef, default: OptionalArg, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
let default: usize = default
|
||||
.map(|v| {
|
||||
if !v.fast_isinstance(&vm.ctx.types.int_type) {
|
||||
if !v.fast_isinstance(vm.ctx.types.int_type) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"'{}' type cannot be interpreted as an integer",
|
||||
v.class().name()
|
||||
@@ -303,7 +303,7 @@ mod _operator {
|
||||
fn iconcat(a: PyObjectRef, b: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
// Best attempt at checking that a is sequence-like.
|
||||
if !a.class().has_attr(identifier!(vm, __getitem__))
|
||||
|| a.fast_isinstance(&vm.ctx.types.dict_type)
|
||||
|| a.fast_isinstance(vm.ctx.types.dict_type)
|
||||
{
|
||||
return Err(
|
||||
vm.new_type_error(format!("{} object can't be concatenated", a.class().name()))
|
||||
|
||||
@@ -832,8 +832,8 @@ pub(super) mod _os {
|
||||
let name = match zelf.get_attr("name", vm) {
|
||||
Ok(name) => Some(name),
|
||||
Err(e)
|
||||
if e.fast_isinstance(&vm.ctx.exceptions.attribute_error)
|
||||
|| e.fast_isinstance(&vm.ctx.exceptions.value_error) =>
|
||||
if e.fast_isinstance(vm.ctx.exceptions.attribute_error)
|
||||
|| e.fast_isinstance(vm.ctx.exceptions.value_error) =>
|
||||
{
|
||||
None
|
||||
}
|
||||
@@ -1805,7 +1805,7 @@ pub fn extend_module(vm: &VirtualMachine, module: &PyObject) {
|
||||
"supports_fd" => supports_fd,
|
||||
"supports_dir_fd" => supports_dir_fd,
|
||||
"supports_follow_symlinks" => supports_follow_symlinks,
|
||||
"error" => vm.ctx.exceptions.os_error.clone(),
|
||||
"error" => vm.ctx.exceptions.os_error.to_owned(),
|
||||
});
|
||||
}
|
||||
pub(crate) use _os::os_open as open;
|
||||
|
||||
@@ -176,7 +176,7 @@ pub(crate) mod _signal {
|
||||
_arg: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.clone()))
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned()))
|
||||
}
|
||||
|
||||
#[derive(FromArgs)]
|
||||
|
||||
@@ -279,7 +279,7 @@ mod sys {
|
||||
#[pyfunction]
|
||||
fn exit(code: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
|
||||
let code = code.unwrap_or_none(vm);
|
||||
Err(vm.new_exception(vm.ctx.exceptions.system_exit.clone(), vec![code]))
|
||||
Err(vm.new_exception(vm.ctx.exceptions.system_exit.to_owned(), vec![code]))
|
||||
}
|
||||
|
||||
#[pyfunction(name = "__displayhook__")]
|
||||
@@ -479,7 +479,7 @@ mod sys {
|
||||
}
|
||||
assert!(unraisable
|
||||
.exc_type
|
||||
.fast_issubclass(&vm.ctx.exceptions.exception_type));
|
||||
.fast_issubclass(vm.ctx.exceptions.exception_type));
|
||||
|
||||
// TODO: print module name and qualname
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(crate) mod _thread {
|
||||
|
||||
#[pyattr]
|
||||
fn error(vm: &VirtualMachine) -> PyTypeRef {
|
||||
vm.ctx.exceptions.runtime_error.clone()
|
||||
vm.ctx.exceptions.runtime_error.to_owned()
|
||||
}
|
||||
|
||||
#[derive(FromArgs)]
|
||||
@@ -270,7 +270,7 @@ pub(crate) mod _thread {
|
||||
fn run_thread(func: ArgCallable, args: FuncArgs, vm: &VirtualMachine) {
|
||||
match func.invoke(args, vm) {
|
||||
Ok(_obj) => {}
|
||||
Err(e) if e.fast_isinstance(&vm.ctx.exceptions.system_exit) => {}
|
||||
Err(e) if e.fast_isinstance(vm.ctx.exceptions.system_exit) => {}
|
||||
Err(exc) => {
|
||||
vm.run_unraisable(
|
||||
exc,
|
||||
@@ -291,7 +291,7 @@ pub(crate) mod _thread {
|
||||
|
||||
#[pyfunction]
|
||||
fn exit(vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.system_exit.clone()))
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.system_exit.to_owned()))
|
||||
}
|
||||
|
||||
thread_local!(static SENTINELS: RefCell<Vec<PyRef<Lock>>> = RefCell::default());
|
||||
|
||||
@@ -24,7 +24,7 @@ mod _warnings {
|
||||
// TODO: Implement correctly
|
||||
let level = args.stacklevel.unwrap_or(1);
|
||||
let category = if let OptionalArg::Present(category) = args.category {
|
||||
if !category.fast_issubclass(&vm.ctx.exceptions.warning) {
|
||||
if !category.fast_issubclass(vm.ctx.exceptions.warning) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"category must be a Warning subclass, not '{}'",
|
||||
category.class().name()
|
||||
@@ -32,7 +32,7 @@ mod _warnings {
|
||||
}
|
||||
category
|
||||
} else {
|
||||
vm.ctx.exceptions.user_warning.clone()
|
||||
vm.ctx.exceptions.user_warning.to_owned()
|
||||
};
|
||||
let stderr = PyStderr(vm);
|
||||
writeln!(
|
||||
|
||||
@@ -15,23 +15,23 @@ mod _weakref {
|
||||
|
||||
#[pyattr(name = "ref")]
|
||||
fn ref_(vm: &VirtualMachine) -> PyTypeRef {
|
||||
vm.ctx.types.weakref_type.clone()
|
||||
vm.ctx.types.weakref_type.to_owned()
|
||||
}
|
||||
#[pyattr]
|
||||
fn proxy(vm: &VirtualMachine) -> PyTypeRef {
|
||||
vm.ctx.types.weakproxy_type.clone()
|
||||
vm.ctx.types.weakproxy_type.to_owned()
|
||||
}
|
||||
#[pyattr(name = "ReferenceType")]
|
||||
fn reference_type(vm: &VirtualMachine) -> PyTypeRef {
|
||||
vm.ctx.types.weakref_type.clone()
|
||||
vm.ctx.types.weakref_type.to_owned()
|
||||
}
|
||||
#[pyattr(name = "ProxyType")]
|
||||
fn proxy_type(vm: &VirtualMachine) -> PyTypeRef {
|
||||
vm.ctx.types.weakproxy_type.clone()
|
||||
vm.ctx.types.weakproxy_type.to_owned()
|
||||
}
|
||||
#[pyattr(name = "CallableProxyType")]
|
||||
fn callable_proxy_type(vm: &VirtualMachine) -> PyTypeRef {
|
||||
vm.ctx.types.weakproxy_type.clone()
|
||||
vm.ctx.types.weakproxy_type.to_owned()
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -45,12 +45,12 @@ fn calculate_suggestions<'a>(
|
||||
}
|
||||
|
||||
pub fn offer_suggestions(exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> Option<PyStrRef> {
|
||||
if exc.class().is(&vm.ctx.exceptions.attribute_error) {
|
||||
if exc.class().is(vm.ctx.exceptions.attribute_error) {
|
||||
let name = exc.as_object().to_owned().get_attr("name", vm).unwrap();
|
||||
let obj = exc.as_object().to_owned().get_attr("obj", vm).unwrap();
|
||||
|
||||
calculate_suggestions(vm.dir(Some(obj)).ok()?.borrow_vec().iter(), &name)
|
||||
} else if exc.class().is(&vm.ctx.exceptions.name_error) {
|
||||
} else if exc.class().is(vm.ctx.exceptions.name_error) {
|
||||
let name = exc.as_object().to_owned().get_attr("name", vm).unwrap();
|
||||
let mut tb = exc.traceback().unwrap();
|
||||
while let Some(traceback) = tb.next.clone() {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::{
|
||||
builtins::{PyTuple, PyTupleRef, PyTypeRef},
|
||||
builtins::{PyTuple, PyTupleRef, PyType},
|
||||
class::{PyClassImpl, StaticType},
|
||||
vm::Context,
|
||||
AsObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
|
||||
};
|
||||
|
||||
#[pyimpl]
|
||||
@@ -13,7 +13,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
|
||||
|
||||
fn into_struct_sequence(self, vm: &VirtualMachine) -> PyTupleRef {
|
||||
self.into_tuple(vm)
|
||||
.into_ref_with_type(vm, Self::static_type().clone())
|
||||
.into_ref_with_type(vm, Self::static_type().to_owned())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
@@ -73,14 +73,14 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
|
||||
}
|
||||
|
||||
#[extend_class]
|
||||
fn extend_pyclass(ctx: &Context, class: &PyTypeRef) {
|
||||
fn extend_pyclass(ctx: &Context, class: &'static Py<PyType>) {
|
||||
for (i, &name) in Self::FIELD_NAMES.iter().enumerate() {
|
||||
// cast i to a u8 so there's less to store in the getter closure.
|
||||
// Hopefully there's not struct sequences with >=256 elements :P
|
||||
let i = i as u8;
|
||||
class.set_attr(
|
||||
ctx.intern_str(name),
|
||||
ctx.new_readonly_getset(name, class.clone(), move |zelf: &PyTuple| {
|
||||
ctx.new_readonly_getset(name, class, move |zelf: &PyTuple| {
|
||||
zelf.fast_getitem(i.into())
|
||||
})
|
||||
.into(),
|
||||
|
||||
@@ -4,89 +4,90 @@ use crate::{
|
||||
coroutine, dict, enumerate, filter, float, frame, function, generator, genericalias,
|
||||
getset, int, iter, list, map, mappingproxy, memory, module, namespace, object, property,
|
||||
pystr, range, set, singletons, slice, staticmethod, super_, traceback, tuple,
|
||||
type_::{self, PyTypeRef},
|
||||
type_::{self, PyType},
|
||||
union_, weakproxy, weakref, zip,
|
||||
},
|
||||
class::StaticType,
|
||||
vm::Context,
|
||||
Py,
|
||||
};
|
||||
|
||||
/// Holder of references to builtin types.
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
pub struct TypeZoo {
|
||||
pub async_generator: PyTypeRef,
|
||||
pub async_generator_asend: PyTypeRef,
|
||||
pub async_generator_athrow: PyTypeRef,
|
||||
pub async_generator_wrapped_value: PyTypeRef,
|
||||
pub bytes_type: PyTypeRef,
|
||||
pub bytes_iterator_type: PyTypeRef,
|
||||
pub bytearray_type: PyTypeRef,
|
||||
pub bytearray_iterator_type: PyTypeRef,
|
||||
pub bool_type: PyTypeRef,
|
||||
pub callable_iterator: PyTypeRef,
|
||||
pub cell_type: PyTypeRef,
|
||||
pub classmethod_type: PyTypeRef,
|
||||
pub code_type: PyTypeRef,
|
||||
pub coroutine_type: PyTypeRef,
|
||||
pub coroutine_wrapper_type: PyTypeRef,
|
||||
pub dict_type: PyTypeRef,
|
||||
pub enumerate_type: PyTypeRef,
|
||||
pub filter_type: PyTypeRef,
|
||||
pub float_type: PyTypeRef,
|
||||
pub frame_type: PyTypeRef,
|
||||
pub frozenset_type: PyTypeRef,
|
||||
pub generator_type: PyTypeRef,
|
||||
pub int_type: PyTypeRef,
|
||||
pub iter_type: PyTypeRef,
|
||||
pub reverse_iter_type: PyTypeRef,
|
||||
pub complex_type: PyTypeRef,
|
||||
pub list_type: PyTypeRef,
|
||||
pub list_iterator_type: PyTypeRef,
|
||||
pub list_reverseiterator_type: PyTypeRef,
|
||||
pub str_iterator_type: PyTypeRef,
|
||||
pub dict_keyiterator_type: PyTypeRef,
|
||||
pub dict_reversekeyiterator_type: PyTypeRef,
|
||||
pub dict_valueiterator_type: PyTypeRef,
|
||||
pub dict_reversevalueiterator_type: PyTypeRef,
|
||||
pub dict_itemiterator_type: PyTypeRef,
|
||||
pub dict_reverseitemiterator_type: PyTypeRef,
|
||||
pub dict_keys_type: PyTypeRef,
|
||||
pub dict_values_type: PyTypeRef,
|
||||
pub dict_items_type: PyTypeRef,
|
||||
pub map_type: PyTypeRef,
|
||||
pub memoryview_type: PyTypeRef,
|
||||
pub tuple_type: PyTypeRef,
|
||||
pub tuple_iterator_type: PyTypeRef,
|
||||
pub set_type: PyTypeRef,
|
||||
pub set_iterator_type: PyTypeRef,
|
||||
pub staticmethod_type: PyTypeRef,
|
||||
pub super_type: PyTypeRef,
|
||||
pub str_type: PyTypeRef,
|
||||
pub range_type: PyTypeRef,
|
||||
pub range_iterator_type: PyTypeRef,
|
||||
pub longrange_iterator_type: PyTypeRef,
|
||||
pub slice_type: PyTypeRef,
|
||||
pub type_type: PyTypeRef,
|
||||
pub zip_type: PyTypeRef,
|
||||
pub function_type: PyTypeRef,
|
||||
pub builtin_function_or_method_type: PyTypeRef,
|
||||
pub method_descriptor_type: PyTypeRef,
|
||||
pub property_type: PyTypeRef,
|
||||
pub getset_type: PyTypeRef,
|
||||
pub module_type: PyTypeRef,
|
||||
pub namespace_type: PyTypeRef,
|
||||
pub bound_method_type: PyTypeRef,
|
||||
pub weakref_type: PyTypeRef,
|
||||
pub weakproxy_type: PyTypeRef,
|
||||
pub mappingproxy_type: PyTypeRef,
|
||||
pub traceback_type: PyTypeRef,
|
||||
pub object_type: PyTypeRef,
|
||||
pub ellipsis_type: PyTypeRef,
|
||||
pub none_type: PyTypeRef,
|
||||
pub not_implemented_type: PyTypeRef,
|
||||
pub generic_alias_type: PyTypeRef,
|
||||
pub union_type: PyTypeRef,
|
||||
pub async_generator: &'static Py<PyType>,
|
||||
pub async_generator_asend: &'static Py<PyType>,
|
||||
pub async_generator_athrow: &'static Py<PyType>,
|
||||
pub async_generator_wrapped_value: &'static Py<PyType>,
|
||||
pub bytes_type: &'static Py<PyType>,
|
||||
pub bytes_iterator_type: &'static Py<PyType>,
|
||||
pub bytearray_type: &'static Py<PyType>,
|
||||
pub bytearray_iterator_type: &'static Py<PyType>,
|
||||
pub bool_type: &'static Py<PyType>,
|
||||
pub callable_iterator: &'static Py<PyType>,
|
||||
pub cell_type: &'static Py<PyType>,
|
||||
pub classmethod_type: &'static Py<PyType>,
|
||||
pub code_type: &'static Py<PyType>,
|
||||
pub coroutine_type: &'static Py<PyType>,
|
||||
pub coroutine_wrapper_type: &'static Py<PyType>,
|
||||
pub dict_type: &'static Py<PyType>,
|
||||
pub enumerate_type: &'static Py<PyType>,
|
||||
pub filter_type: &'static Py<PyType>,
|
||||
pub float_type: &'static Py<PyType>,
|
||||
pub frame_type: &'static Py<PyType>,
|
||||
pub frozenset_type: &'static Py<PyType>,
|
||||
pub generator_type: &'static Py<PyType>,
|
||||
pub int_type: &'static Py<PyType>,
|
||||
pub iter_type: &'static Py<PyType>,
|
||||
pub reverse_iter_type: &'static Py<PyType>,
|
||||
pub complex_type: &'static Py<PyType>,
|
||||
pub list_type: &'static Py<PyType>,
|
||||
pub list_iterator_type: &'static Py<PyType>,
|
||||
pub list_reverseiterator_type: &'static Py<PyType>,
|
||||
pub str_iterator_type: &'static Py<PyType>,
|
||||
pub dict_keyiterator_type: &'static Py<PyType>,
|
||||
pub dict_reversekeyiterator_type: &'static Py<PyType>,
|
||||
pub dict_valueiterator_type: &'static Py<PyType>,
|
||||
pub dict_reversevalueiterator_type: &'static Py<PyType>,
|
||||
pub dict_itemiterator_type: &'static Py<PyType>,
|
||||
pub dict_reverseitemiterator_type: &'static Py<PyType>,
|
||||
pub dict_keys_type: &'static Py<PyType>,
|
||||
pub dict_values_type: &'static Py<PyType>,
|
||||
pub dict_items_type: &'static Py<PyType>,
|
||||
pub map_type: &'static Py<PyType>,
|
||||
pub memoryview_type: &'static Py<PyType>,
|
||||
pub tuple_type: &'static Py<PyType>,
|
||||
pub tuple_iterator_type: &'static Py<PyType>,
|
||||
pub set_type: &'static Py<PyType>,
|
||||
pub set_iterator_type: &'static Py<PyType>,
|
||||
pub staticmethod_type: &'static Py<PyType>,
|
||||
pub super_type: &'static Py<PyType>,
|
||||
pub str_type: &'static Py<PyType>,
|
||||
pub range_type: &'static Py<PyType>,
|
||||
pub range_iterator_type: &'static Py<PyType>,
|
||||
pub longrange_iterator_type: &'static Py<PyType>,
|
||||
pub slice_type: &'static Py<PyType>,
|
||||
pub type_type: &'static Py<PyType>,
|
||||
pub zip_type: &'static Py<PyType>,
|
||||
pub function_type: &'static Py<PyType>,
|
||||
pub builtin_function_or_method_type: &'static Py<PyType>,
|
||||
pub method_descriptor_type: &'static Py<PyType>,
|
||||
pub property_type: &'static Py<PyType>,
|
||||
pub getset_type: &'static Py<PyType>,
|
||||
pub module_type: &'static Py<PyType>,
|
||||
pub namespace_type: &'static Py<PyType>,
|
||||
pub bound_method_type: &'static Py<PyType>,
|
||||
pub weakref_type: &'static Py<PyType>,
|
||||
pub weakproxy_type: &'static Py<PyType>,
|
||||
pub mappingproxy_type: &'static Py<PyType>,
|
||||
pub traceback_type: &'static Py<PyType>,
|
||||
pub object_type: &'static Py<PyType>,
|
||||
pub ellipsis_type: &'static Py<PyType>,
|
||||
pub none_type: &'static Py<PyType>,
|
||||
pub not_implemented_type: &'static Py<PyType>,
|
||||
pub generic_alias_type: &'static Py<PyType>,
|
||||
pub union_type: &'static Py<PyType>,
|
||||
}
|
||||
|
||||
impl TypeZoo {
|
||||
@@ -95,86 +96,82 @@ impl TypeZoo {
|
||||
let (type_type, object_type, weakref_type) = crate::object::init_type_hierarchy();
|
||||
Self {
|
||||
// the order matters for type, object, weakref, and int
|
||||
type_type: type_::PyType::init_manually(type_type).clone(),
|
||||
object_type: object::PyBaseObject::init_manually(object_type).clone(),
|
||||
weakref_type: weakref::PyWeak::init_manually(weakref_type).clone(),
|
||||
int_type: int::PyInt::init_bare_type().clone(),
|
||||
type_type: type_::PyType::init_manually(type_type),
|
||||
object_type: object::PyBaseObject::init_manually(object_type),
|
||||
weakref_type: weakref::PyWeak::init_manually(weakref_type),
|
||||
int_type: int::PyInt::init_bare_type(),
|
||||
|
||||
// types exposed as builtins
|
||||
bool_type: bool_::PyBool::init_bare_type().clone(),
|
||||
bytearray_type: bytearray::PyByteArray::init_bare_type().clone(),
|
||||
bytes_type: bytes::PyBytes::init_bare_type().clone(),
|
||||
classmethod_type: classmethod::PyClassMethod::init_bare_type().clone(),
|
||||
complex_type: complex::PyComplex::init_bare_type().clone(),
|
||||
dict_type: dict::PyDict::init_bare_type().clone(),
|
||||
enumerate_type: enumerate::PyEnumerate::init_bare_type().clone(),
|
||||
float_type: float::PyFloat::init_bare_type().clone(),
|
||||
frozenset_type: set::PyFrozenSet::init_bare_type().clone(),
|
||||
filter_type: filter::PyFilter::init_bare_type().clone(),
|
||||
list_type: list::PyList::init_bare_type().clone(),
|
||||
map_type: map::PyMap::init_bare_type().clone(),
|
||||
memoryview_type: memory::PyMemoryView::init_bare_type().clone(),
|
||||
property_type: property::PyProperty::init_bare_type().clone(),
|
||||
range_type: range::PyRange::init_bare_type().clone(),
|
||||
set_type: set::PySet::init_bare_type().clone(),
|
||||
slice_type: slice::PySlice::init_bare_type().clone(),
|
||||
staticmethod_type: staticmethod::PyStaticMethod::init_bare_type().clone(),
|
||||
str_type: pystr::PyStr::init_bare_type().clone(),
|
||||
super_type: super_::PySuper::init_bare_type().clone(),
|
||||
tuple_type: tuple::PyTuple::init_bare_type().clone(),
|
||||
zip_type: zip::PyZip::init_bare_type().clone(),
|
||||
bool_type: bool_::PyBool::init_bare_type(),
|
||||
bytearray_type: bytearray::PyByteArray::init_bare_type(),
|
||||
bytes_type: bytes::PyBytes::init_bare_type(),
|
||||
classmethod_type: classmethod::PyClassMethod::init_bare_type(),
|
||||
complex_type: complex::PyComplex::init_bare_type(),
|
||||
dict_type: dict::PyDict::init_bare_type(),
|
||||
enumerate_type: enumerate::PyEnumerate::init_bare_type(),
|
||||
float_type: float::PyFloat::init_bare_type(),
|
||||
frozenset_type: set::PyFrozenSet::init_bare_type(),
|
||||
filter_type: filter::PyFilter::init_bare_type(),
|
||||
list_type: list::PyList::init_bare_type(),
|
||||
map_type: map::PyMap::init_bare_type(),
|
||||
memoryview_type: memory::PyMemoryView::init_bare_type(),
|
||||
property_type: property::PyProperty::init_bare_type(),
|
||||
range_type: range::PyRange::init_bare_type(),
|
||||
set_type: set::PySet::init_bare_type(),
|
||||
slice_type: slice::PySlice::init_bare_type(),
|
||||
staticmethod_type: staticmethod::PyStaticMethod::init_bare_type(),
|
||||
str_type: pystr::PyStr::init_bare_type(),
|
||||
super_type: super_::PySuper::init_bare_type(),
|
||||
tuple_type: tuple::PyTuple::init_bare_type(),
|
||||
zip_type: zip::PyZip::init_bare_type(),
|
||||
|
||||
// hidden internal types. is this really need to be cached here?
|
||||
async_generator: asyncgenerator::PyAsyncGen::init_bare_type().clone(),
|
||||
async_generator_asend: asyncgenerator::PyAsyncGenASend::init_bare_type().clone(),
|
||||
async_generator_athrow: asyncgenerator::PyAsyncGenAThrow::init_bare_type().clone(),
|
||||
async_generator_wrapped_value: asyncgenerator::PyAsyncGenWrappedValue::init_bare_type()
|
||||
.clone(),
|
||||
bound_method_type: function::PyBoundMethod::init_bare_type().clone(),
|
||||
builtin_function_or_method_type: builtinfunc::PyBuiltinFunction::init_bare_type()
|
||||
.clone(),
|
||||
bytearray_iterator_type: bytearray::PyByteArrayIterator::init_bare_type().clone(),
|
||||
bytes_iterator_type: bytes::PyBytesIterator::init_bare_type().clone(),
|
||||
callable_iterator: iter::PyCallableIterator::init_bare_type().clone(),
|
||||
cell_type: function::PyCell::init_bare_type().clone(),
|
||||
code_type: code::PyCode::init_bare_type().clone(),
|
||||
coroutine_type: coroutine::PyCoroutine::init_bare_type().clone(),
|
||||
coroutine_wrapper_type: coroutine::PyCoroutineWrapper::init_bare_type().clone(),
|
||||
dict_keys_type: dict::PyDictKeys::init_bare_type().clone(),
|
||||
dict_values_type: dict::PyDictValues::init_bare_type().clone(),
|
||||
dict_items_type: dict::PyDictItems::init_bare_type().clone(),
|
||||
dict_keyiterator_type: dict::PyDictKeyIterator::init_bare_type().clone(),
|
||||
dict_reversekeyiterator_type: dict::PyDictReverseKeyIterator::init_bare_type().clone(),
|
||||
dict_valueiterator_type: dict::PyDictValueIterator::init_bare_type().clone(),
|
||||
dict_reversevalueiterator_type: dict::PyDictReverseValueIterator::init_bare_type()
|
||||
.clone(),
|
||||
dict_itemiterator_type: dict::PyDictItemIterator::init_bare_type().clone(),
|
||||
dict_reverseitemiterator_type: dict::PyDictReverseItemIterator::init_bare_type()
|
||||
.clone(),
|
||||
ellipsis_type: slice::PyEllipsis::init_bare_type().clone(),
|
||||
frame_type: crate::frame::Frame::init_bare_type().clone(),
|
||||
function_type: function::PyFunction::init_bare_type().clone(),
|
||||
generator_type: generator::PyGenerator::init_bare_type().clone(),
|
||||
getset_type: getset::PyGetSet::init_bare_type().clone(),
|
||||
iter_type: iter::PySequenceIterator::init_bare_type().clone(),
|
||||
reverse_iter_type: enumerate::PyReverseSequenceIterator::init_bare_type().clone(),
|
||||
list_iterator_type: list::PyListIterator::init_bare_type().clone(),
|
||||
list_reverseiterator_type: list::PyListReverseIterator::init_bare_type().clone(),
|
||||
mappingproxy_type: mappingproxy::PyMappingProxy::init_bare_type().clone(),
|
||||
module_type: module::PyModule::init_bare_type().clone(),
|
||||
namespace_type: namespace::PyNamespace::init_bare_type().clone(),
|
||||
range_iterator_type: range::PyRangeIterator::init_bare_type().clone(),
|
||||
longrange_iterator_type: range::PyLongRangeIterator::init_bare_type().clone(),
|
||||
set_iterator_type: set::PySetIterator::init_bare_type().clone(),
|
||||
str_iterator_type: pystr::PyStrIterator::init_bare_type().clone(),
|
||||
traceback_type: traceback::PyTraceback::init_bare_type().clone(),
|
||||
tuple_iterator_type: tuple::PyTupleIterator::init_bare_type().clone(),
|
||||
weakproxy_type: weakproxy::PyWeakProxy::init_bare_type().clone(),
|
||||
method_descriptor_type: builtinfunc::PyBuiltinMethod::init_bare_type().clone(),
|
||||
none_type: singletons::PyNone::init_bare_type().clone(),
|
||||
not_implemented_type: singletons::PyNotImplemented::init_bare_type().clone(),
|
||||
generic_alias_type: genericalias::PyGenericAlias::init_bare_type().clone(),
|
||||
union_type: union_::PyUnion::init_bare_type().clone(),
|
||||
async_generator: asyncgenerator::PyAsyncGen::init_bare_type(),
|
||||
async_generator_asend: asyncgenerator::PyAsyncGenASend::init_bare_type(),
|
||||
async_generator_athrow: asyncgenerator::PyAsyncGenAThrow::init_bare_type(),
|
||||
async_generator_wrapped_value: asyncgenerator::PyAsyncGenWrappedValue::init_bare_type(),
|
||||
bound_method_type: function::PyBoundMethod::init_bare_type(),
|
||||
builtin_function_or_method_type: builtinfunc::PyBuiltinFunction::init_bare_type(),
|
||||
bytearray_iterator_type: bytearray::PyByteArrayIterator::init_bare_type(),
|
||||
bytes_iterator_type: bytes::PyBytesIterator::init_bare_type(),
|
||||
callable_iterator: iter::PyCallableIterator::init_bare_type(),
|
||||
cell_type: function::PyCell::init_bare_type(),
|
||||
code_type: code::PyCode::init_bare_type(),
|
||||
coroutine_type: coroutine::PyCoroutine::init_bare_type(),
|
||||
coroutine_wrapper_type: coroutine::PyCoroutineWrapper::init_bare_type(),
|
||||
dict_keys_type: dict::PyDictKeys::init_bare_type(),
|
||||
dict_values_type: dict::PyDictValues::init_bare_type(),
|
||||
dict_items_type: dict::PyDictItems::init_bare_type(),
|
||||
dict_keyiterator_type: dict::PyDictKeyIterator::init_bare_type(),
|
||||
dict_reversekeyiterator_type: dict::PyDictReverseKeyIterator::init_bare_type(),
|
||||
dict_valueiterator_type: dict::PyDictValueIterator::init_bare_type(),
|
||||
dict_reversevalueiterator_type: dict::PyDictReverseValueIterator::init_bare_type(),
|
||||
dict_itemiterator_type: dict::PyDictItemIterator::init_bare_type(),
|
||||
dict_reverseitemiterator_type: dict::PyDictReverseItemIterator::init_bare_type(),
|
||||
ellipsis_type: slice::PyEllipsis::init_bare_type(),
|
||||
frame_type: crate::frame::Frame::init_bare_type(),
|
||||
function_type: function::PyFunction::init_bare_type(),
|
||||
generator_type: generator::PyGenerator::init_bare_type(),
|
||||
getset_type: getset::PyGetSet::init_bare_type(),
|
||||
iter_type: iter::PySequenceIterator::init_bare_type(),
|
||||
reverse_iter_type: enumerate::PyReverseSequenceIterator::init_bare_type(),
|
||||
list_iterator_type: list::PyListIterator::init_bare_type(),
|
||||
list_reverseiterator_type: list::PyListReverseIterator::init_bare_type(),
|
||||
mappingproxy_type: mappingproxy::PyMappingProxy::init_bare_type(),
|
||||
module_type: module::PyModule::init_bare_type(),
|
||||
namespace_type: namespace::PyNamespace::init_bare_type(),
|
||||
range_iterator_type: range::PyRangeIterator::init_bare_type(),
|
||||
longrange_iterator_type: range::PyLongRangeIterator::init_bare_type(),
|
||||
set_iterator_type: set::PySetIterator::init_bare_type(),
|
||||
str_iterator_type: pystr::PyStrIterator::init_bare_type(),
|
||||
traceback_type: traceback::PyTraceback::init_bare_type(),
|
||||
tuple_iterator_type: tuple::PyTupleIterator::init_bare_type(),
|
||||
weakproxy_type: weakproxy::PyWeakProxy::init_bare_type(),
|
||||
method_descriptor_type: builtinfunc::PyBuiltinMethod::init_bare_type(),
|
||||
none_type: singletons::PyNone::init_bare_type(),
|
||||
not_implemented_type: singletons::PyNotImplemented::init_bare_type(),
|
||||
generic_alias_type: genericalias::PyGenericAlias::init_bare_type(),
|
||||
union_type: union_::PyUnion::init_bare_type(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::{
|
||||
exceptions,
|
||||
function::IntoPyNativeFunc,
|
||||
intern::{Internable, MaybeInterned, StringPool},
|
||||
object::{PyObjectPayload, PyObjectRef, PyPayload, PyRef},
|
||||
object::{Py, PyObjectPayload, PyObjectRef, PyPayload, PyRef},
|
||||
types::{PyTypeFlags, PyTypeSlots, TypeZoo},
|
||||
};
|
||||
use num_bigint::BigInt;
|
||||
@@ -228,8 +228,11 @@ impl Context {
|
||||
let exceptions = exceptions::ExceptionZoo::init();
|
||||
|
||||
#[inline]
|
||||
fn create_object<T: PyObjectPayload + PyPayload>(payload: T, cls: &PyTypeRef) -> PyRef<T> {
|
||||
PyRef::new_ref(payload, cls.clone(), None)
|
||||
fn create_object<T: PyObjectPayload + PyPayload>(
|
||||
payload: T,
|
||||
cls: &'static Py<PyType>,
|
||||
) -> PyRef<T> {
|
||||
PyRef::new_ref(payload, cls.to_owned(), None)
|
||||
}
|
||||
|
||||
let none = create_object(PyNone, PyNone::static_type());
|
||||
@@ -237,30 +240,39 @@ impl Context {
|
||||
let not_implemented = create_object(PyNotImplemented, PyNotImplemented::static_type());
|
||||
|
||||
let int_cache_pool = (Self::INT_CACHE_POOL_MIN..=Self::INT_CACHE_POOL_MAX)
|
||||
.map(|v| PyRef::new_ref(PyInt::from(BigInt::from(v)), types.int_type.clone(), None))
|
||||
.map(|v| {
|
||||
PyRef::new_ref(
|
||||
PyInt::from(BigInt::from(v)),
|
||||
types.int_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let true_value = create_object(PyInt::from(1), &types.bool_type);
|
||||
let false_value = create_object(PyInt::from(0), &types.bool_type);
|
||||
let true_value = create_object(PyInt::from(1), types.bool_type);
|
||||
let false_value = create_object(PyInt::from(0), types.bool_type);
|
||||
|
||||
let empty_tuple = create_object(
|
||||
PyTuple::new_unchecked(Vec::new().into_boxed_slice()),
|
||||
&types.tuple_type,
|
||||
types.tuple_type,
|
||||
);
|
||||
let empty_frozenset = PyRef::new_ref(
|
||||
PyFrozenSet::default(),
|
||||
types.frozenset_type.to_owned(),
|
||||
None,
|
||||
);
|
||||
let empty_frozenset =
|
||||
PyRef::new_ref(PyFrozenSet::default(), types.frozenset_type.clone(), None);
|
||||
|
||||
let string_pool = StringPool::default();
|
||||
let names = unsafe { ConstName::new(&string_pool, &types.str_type) };
|
||||
let names = unsafe { ConstName::new(&string_pool, &types.str_type.to_owned()) };
|
||||
|
||||
let slot_new_wrapper = create_object(
|
||||
PyNativeFuncDef::new(PyType::__new__.into_func(), names.__new__.to_owned())
|
||||
.into_function(),
|
||||
&types.builtin_function_or_method_type,
|
||||
types.builtin_function_or_method_type,
|
||||
)
|
||||
.into();
|
||||
|
||||
let empty_str = unsafe { string_pool.intern("", types.str_type.clone()) }.to_owned();
|
||||
let empty_str = unsafe { string_pool.intern("", types.str_type.to_owned()) }.to_owned();
|
||||
|
||||
let context = Context {
|
||||
true_value,
|
||||
@@ -286,7 +298,7 @@ impl Context {
|
||||
}
|
||||
|
||||
pub fn intern_str<S: Internable>(&self, s: S) -> &'static PyStrInterned {
|
||||
unsafe { self.string_pool.intern(s, self.types.str_type.clone()) }
|
||||
unsafe { self.string_pool.intern(s, self.types.str_type.to_owned()) }
|
||||
}
|
||||
|
||||
pub fn interned_str<S: MaybeInterned + ?Sized>(&self, s: &S) -> Option<&'static PyStrInterned> {
|
||||
@@ -318,7 +330,7 @@ impl Context {
|
||||
return self.int_cache_pool[inner_idx].clone();
|
||||
}
|
||||
}
|
||||
PyRef::new_ref(PyInt::from(i), self.types.int_type.clone(), None)
|
||||
PyRef::new_ref(PyInt::from(i), self.types.int_type.to_owned(), None)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -329,19 +341,19 @@ impl Context {
|
||||
return self.int_cache_pool[inner_idx].clone();
|
||||
}
|
||||
}
|
||||
PyRef::new_ref(PyInt::from(i.clone()), self.types.int_type.clone(), None)
|
||||
PyRef::new_ref(PyInt::from(i.clone()), self.types.int_type.to_owned(), None)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_float(&self, value: f64) -> PyRef<PyFloat> {
|
||||
PyRef::new_ref(PyFloat::from(value), self.types.float_type.clone(), None)
|
||||
PyRef::new_ref(PyFloat::from(value), self.types.float_type.to_owned(), None)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_complex(&self, value: Complex64) -> PyRef<PyComplex> {
|
||||
PyRef::new_ref(
|
||||
PyComplex::from(value),
|
||||
self.types.complex_type.clone(),
|
||||
self.types.complex_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -385,7 +397,7 @@ impl Context {
|
||||
&self,
|
||||
module: Option<&str>,
|
||||
name: &str,
|
||||
base: &PyTypeRef,
|
||||
base: PyTypeRef,
|
||||
slots: PyTypeSlots,
|
||||
) -> PyTypeRef {
|
||||
let mut attrs = PyAttributes::default();
|
||||
@@ -394,10 +406,10 @@ impl Context {
|
||||
};
|
||||
PyType::new_ref(
|
||||
name,
|
||||
vec![base.clone()],
|
||||
vec![base],
|
||||
attrs,
|
||||
slots,
|
||||
self.types.type_type.clone(),
|
||||
self.types.type_type.to_owned(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -411,7 +423,7 @@ impl Context {
|
||||
let bases = if let Some(bases) = bases {
|
||||
bases
|
||||
} else {
|
||||
vec![self.exceptions.exception_type.clone()]
|
||||
vec![self.exceptions.exception_type.to_owned()]
|
||||
};
|
||||
let mut attrs = PyAttributes::default();
|
||||
attrs.insert(identifier!(self, __module__), self.new_str(module).into());
|
||||
@@ -421,7 +433,7 @@ impl Context {
|
||||
bases,
|
||||
attrs,
|
||||
PyBaseException::make_slots(),
|
||||
self.types.type_type.clone(),
|
||||
self.types.type_type.to_owned(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -445,7 +457,7 @@ impl Context {
|
||||
pub fn new_method<F, FKind>(
|
||||
&self,
|
||||
name: impl Into<PyStr>,
|
||||
class: PyTypeRef,
|
||||
class: &'static Py<PyType>,
|
||||
f: F,
|
||||
) -> PyRef<PyBuiltinMethod>
|
||||
where
|
||||
@@ -457,7 +469,7 @@ impl Context {
|
||||
pub fn new_readonly_getset<F, T>(
|
||||
&self,
|
||||
name: impl Into<String>,
|
||||
class: PyTypeRef,
|
||||
class: &'static Py<PyType>,
|
||||
f: F,
|
||||
) -> PyRef<PyGetSet>
|
||||
where
|
||||
@@ -465,7 +477,7 @@ impl Context {
|
||||
{
|
||||
PyRef::new_ref(
|
||||
PyGetSet::new(name.into(), class).with_get(f),
|
||||
self.types.getset_type.clone(),
|
||||
self.types.getset_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -473,7 +485,7 @@ impl Context {
|
||||
pub fn new_getset<G, S, T, U>(
|
||||
&self,
|
||||
name: impl Into<String>,
|
||||
class: PyTypeRef,
|
||||
class: &'static Py<PyType>,
|
||||
g: G,
|
||||
s: S,
|
||||
) -> PyRef<PyGetSet>
|
||||
@@ -483,7 +495,7 @@ impl Context {
|
||||
{
|
||||
PyRef::new_ref(
|
||||
PyGetSet::new(name.into(), class).with_get(g).with_set(s),
|
||||
self.types.getset_type.clone(),
|
||||
self.types.getset_type.to_owned(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -498,7 +510,7 @@ impl Context {
|
||||
|
||||
pub fn new_code(&self, code: impl code::IntoCodeObject) -> PyRef<PyCode> {
|
||||
let code = code.into_codeobj(self);
|
||||
PyRef::new_ref(PyCode { code }, self.types.code_type.clone(), None)
|
||||
PyRef::new_ref(PyCode { code }, self.types.code_type.to_owned(), None)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ impl VirtualMachine {
|
||||
let new_module = || {
|
||||
PyRef::new_ref(
|
||||
PyModule {},
|
||||
ctx.types.module_type.clone(),
|
||||
ctx.types.module_type.to_owned(),
|
||||
Some(ctx.new_dict()),
|
||||
)
|
||||
};
|
||||
@@ -468,9 +468,9 @@ impl VirtualMachine {
|
||||
// Extract elements from item, if possible:
|
||||
let cls = value.class();
|
||||
let list_borrow;
|
||||
let slice = if cls.is(&self.ctx.types.tuple_type) {
|
||||
let slice = if cls.is(self.ctx.types.tuple_type) {
|
||||
value.payload::<PyTuple>().unwrap().as_slice()
|
||||
} else if cls.is(&self.ctx.types.list_type) {
|
||||
} else if cls.is(self.ctx.types.list_type) {
|
||||
list_borrow = value.payload::<PyList>().unwrap().borrow_vec();
|
||||
&list_borrow
|
||||
} else {
|
||||
@@ -519,7 +519,7 @@ impl VirtualMachine {
|
||||
{
|
||||
let iter = value.to_owned().get_iter(self)?;
|
||||
let cap = match self.length_hint_opt(value.to_owned()) {
|
||||
Err(e) if e.class().is(&self.ctx.exceptions.runtime_error) => return Err(e),
|
||||
Err(e) if e.class().is(self.ctx.exceptions.runtime_error) => return Err(e),
|
||||
Ok(Some(value)) => Some(value),
|
||||
// Use a power of 2 as a default capacity.
|
||||
_ => None,
|
||||
@@ -549,7 +549,7 @@ impl VirtualMachine {
|
||||
{
|
||||
match obj.get_attr(attr_name, self) {
|
||||
Ok(attr) => Ok(Some(attr)),
|
||||
Err(e) if e.fast_isinstance(&self.ctx.exceptions.attribute_error) => Ok(None),
|
||||
Err(e) if e.fast_isinstance(self.ctx.exceptions.attribute_error) => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
@@ -560,7 +560,7 @@ impl VirtualMachine {
|
||||
obj: PyObjectRef,
|
||||
name: PyStrRef,
|
||||
) {
|
||||
if exc.class().is(&self.ctx.exceptions.attribute_error) {
|
||||
if exc.class().is(self.ctx.exceptions.attribute_error) {
|
||||
let exc = exc.as_object();
|
||||
exc.set_attr("name", name, self).unwrap();
|
||||
exc.set_attr("obj", obj, self).unwrap();
|
||||
@@ -676,7 +676,7 @@ impl VirtualMachine {
|
||||
}
|
||||
|
||||
pub fn handle_exit_exception(&self, exc: PyBaseExceptionRef) -> i32 {
|
||||
if exc.fast_isinstance(&self.ctx.exceptions.system_exit) {
|
||||
if exc.fast_isinstance(self.ctx.exceptions.system_exit) {
|
||||
let args = exc.args();
|
||||
let msg = match args.as_slice() {
|
||||
[] => return 0,
|
||||
@@ -803,7 +803,7 @@ fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>
|
||||
importer = Some(imp);
|
||||
break;
|
||||
}
|
||||
Err(e) if e.fast_isinstance(&vm.ctx.exceptions.import_error) => continue,
|
||||
Err(e) if e.fast_isinstance(vm.ctx.exceptions.import_error) => continue,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ where
|
||||
let vm_owns_obj = |intp: NonNull<VirtualMachine>| {
|
||||
// SAFETY: all references in VM_STACK should be valid
|
||||
let vm = unsafe { intp.as_ref() };
|
||||
obj.fast_isinstance(&vm.ctx.types.object_type)
|
||||
obj.fast_isinstance(vm.ctx.types.object_type)
|
||||
};
|
||||
VM_STACK.with(|vms| {
|
||||
let intp = match vms.borrow().iter().copied().exactly_one() {
|
||||
|
||||
@@ -4,12 +4,12 @@ use crate::{
|
||||
builtins::{
|
||||
pystr::IntoPyStrRef,
|
||||
tuple::{IntoPyTuple, PyTupleRef},
|
||||
PyBaseException, PyBaseExceptionRef, PyDictRef, PyModule, PyStrRef, PyTypeRef,
|
||||
PyBaseException, PyBaseExceptionRef, PyDictRef, PyModule, PyStrRef, PyType, PyTypeRef,
|
||||
},
|
||||
convert::ToPyObject,
|
||||
scope::Scope,
|
||||
vm::VirtualMachine,
|
||||
AsObject, PyObject, PyObjectRef, PyPayload, PyRef,
|
||||
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef,
|
||||
};
|
||||
|
||||
/// Collection of object creation helpers
|
||||
@@ -32,7 +32,11 @@ impl VirtualMachine {
|
||||
}
|
||||
|
||||
pub fn new_module(&self, name: &str, dict: PyDictRef, doc: Option<&str>) -> PyObjectRef {
|
||||
let module = PyRef::new_ref(PyModule {}, self.ctx.types.module_type.clone(), Some(dict));
|
||||
let module = PyRef::new_ref(
|
||||
PyModule {},
|
||||
self.ctx.types.module_type.to_owned(),
|
||||
Some(dict),
|
||||
);
|
||||
module.init_module_dict(
|
||||
self.ctx.intern_str(name),
|
||||
doc.map(|doc| self.new_pyobj(doc.to_owned()))
|
||||
@@ -83,22 +87,22 @@ impl VirtualMachine {
|
||||
}
|
||||
|
||||
pub fn new_lookup_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let lookup_error = self.ctx.exceptions.lookup_error.clone();
|
||||
let lookup_error = self.ctx.exceptions.lookup_error.to_owned();
|
||||
self.new_exception_msg(lookup_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_attribute_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let attribute_error = self.ctx.exceptions.attribute_error.clone();
|
||||
let attribute_error = self.ctx.exceptions.attribute_error.to_owned();
|
||||
self.new_exception_msg(attribute_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_type_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let type_error = self.ctx.exceptions.type_error.clone();
|
||||
let type_error = self.ctx.exceptions.type_error.to_owned();
|
||||
self.new_exception_msg(type_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_name_error(&self, msg: String, name: PyStrRef) -> PyBaseExceptionRef {
|
||||
let name_error_type = self.ctx.exceptions.name_error.clone();
|
||||
let name_error_type = self.ctx.exceptions.name_error.to_owned();
|
||||
let name_error = self.new_exception_msg(name_error_type, msg);
|
||||
name_error.as_object().set_attr("name", name, self).unwrap();
|
||||
name_error
|
||||
@@ -143,60 +147,60 @@ impl VirtualMachine {
|
||||
}
|
||||
|
||||
pub fn new_os_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let os_error = self.ctx.exceptions.os_error.clone();
|
||||
let os_error = self.ctx.exceptions.os_error.to_owned();
|
||||
self.new_exception_msg(os_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_unicode_decode_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let unicode_decode_error = self.ctx.exceptions.unicode_decode_error.clone();
|
||||
let unicode_decode_error = self.ctx.exceptions.unicode_decode_error.to_owned();
|
||||
self.new_exception_msg(unicode_decode_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_unicode_encode_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let unicode_encode_error = self.ctx.exceptions.unicode_encode_error.clone();
|
||||
let unicode_encode_error = self.ctx.exceptions.unicode_encode_error.to_owned();
|
||||
self.new_exception_msg(unicode_encode_error, msg)
|
||||
}
|
||||
|
||||
/// Create a new python ValueError object. Useful for raising errors from
|
||||
/// python functions implemented in rust.
|
||||
pub fn new_value_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let value_error = self.ctx.exceptions.value_error.clone();
|
||||
let value_error = self.ctx.exceptions.value_error.to_owned();
|
||||
self.new_exception_msg(value_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_buffer_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let buffer_error = self.ctx.exceptions.buffer_error.clone();
|
||||
let buffer_error = self.ctx.exceptions.buffer_error.to_owned();
|
||||
self.new_exception_msg(buffer_error, msg)
|
||||
}
|
||||
|
||||
// TODO: don't take ownership should make the success path faster
|
||||
pub fn new_key_error(&self, obj: PyObjectRef) -> PyBaseExceptionRef {
|
||||
let key_error = self.ctx.exceptions.key_error.clone();
|
||||
let key_error = self.ctx.exceptions.key_error.to_owned();
|
||||
self.new_exception(key_error, vec![obj])
|
||||
}
|
||||
|
||||
pub fn new_index_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let index_error = self.ctx.exceptions.index_error.clone();
|
||||
let index_error = self.ctx.exceptions.index_error.to_owned();
|
||||
self.new_exception_msg(index_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_not_implemented_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let not_implemented_error = self.ctx.exceptions.not_implemented_error.clone();
|
||||
let not_implemented_error = self.ctx.exceptions.not_implemented_error.to_owned();
|
||||
self.new_exception_msg(not_implemented_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_recursion_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let recursion_error = self.ctx.exceptions.recursion_error.clone();
|
||||
let recursion_error = self.ctx.exceptions.recursion_error.to_owned();
|
||||
self.new_exception_msg(recursion_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_zero_division_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let zero_division_error = self.ctx.exceptions.zero_division_error.clone();
|
||||
let zero_division_error = self.ctx.exceptions.zero_division_error.to_owned();
|
||||
self.new_exception_msg(zero_division_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_overflow_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let overflow_error = self.ctx.exceptions.overflow_error.clone();
|
||||
let overflow_error = self.ctx.exceptions.overflow_error.to_owned();
|
||||
self.new_exception_msg(overflow_error, msg)
|
||||
}
|
||||
|
||||
@@ -204,11 +208,12 @@ impl VirtualMachine {
|
||||
pub fn new_syntax_error(&self, error: &CompileError) -> PyBaseExceptionRef {
|
||||
let syntax_error_type = match &error.error {
|
||||
CompileErrorType::Parse(p) if p.is_indentation_error() => {
|
||||
self.ctx.exceptions.indentation_error.clone()
|
||||
self.ctx.exceptions.indentation_error
|
||||
}
|
||||
CompileErrorType::Parse(p) if p.is_tab_error() => self.ctx.exceptions.tab_error.clone(),
|
||||
_ => self.ctx.exceptions.syntax_error.clone(),
|
||||
};
|
||||
CompileErrorType::Parse(p) if p.is_tab_error() => self.ctx.exceptions.tab_error,
|
||||
_ => self.ctx.exceptions.syntax_error,
|
||||
}
|
||||
.to_owned();
|
||||
let syntax_error = self.new_exception_msg(syntax_error_type, error.to_string());
|
||||
let lineno = self.ctx.new_int(error.location.row());
|
||||
let offset = self.ctx.new_int(error.location.column());
|
||||
@@ -236,7 +241,7 @@ impl VirtualMachine {
|
||||
}
|
||||
|
||||
pub fn new_import_error(&self, msg: String, name: impl IntoPyStrRef) -> PyBaseExceptionRef {
|
||||
let import_error = self.ctx.exceptions.import_error.clone();
|
||||
let import_error = self.ctx.exceptions.import_error.to_owned();
|
||||
let exc = self.new_exception_msg(import_error, msg);
|
||||
exc.as_object()
|
||||
.set_attr("name", name.into_pystr_ref(self), self)
|
||||
@@ -245,12 +250,12 @@ impl VirtualMachine {
|
||||
}
|
||||
|
||||
pub fn new_runtime_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let runtime_error = self.ctx.exceptions.runtime_error.clone();
|
||||
let runtime_error = self.ctx.exceptions.runtime_error.to_owned();
|
||||
self.new_exception_msg(runtime_error, msg)
|
||||
}
|
||||
|
||||
pub fn new_memory_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
let memory_error_type = self.ctx.exceptions.memory_error.clone();
|
||||
let memory_error_type = self.ctx.exceptions.memory_error.to_owned();
|
||||
self.new_exception_msg(memory_error_type, msg)
|
||||
}
|
||||
|
||||
@@ -260,31 +265,31 @@ impl VirtualMachine {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
self.new_exception(self.ctx.exceptions.stop_iteration.clone(), args)
|
||||
self.new_exception(self.ctx.exceptions.stop_iteration.to_owned(), args)
|
||||
}
|
||||
|
||||
fn new_downcast_error(
|
||||
&self,
|
||||
msg: &'static str,
|
||||
error_type: &PyTypeRef,
|
||||
class: &PyTypeRef,
|
||||
error_type: &'static Py<PyType>,
|
||||
class: &Py<PyType>,
|
||||
obj: &PyObject, // the impl Borrow allows to pass PyObjectRef or &PyObject
|
||||
) -> PyBaseExceptionRef {
|
||||
let actual_class = obj.class();
|
||||
let actual_type = &*actual_class.name();
|
||||
let expected_type = &*class.name();
|
||||
let msg = format!("Expected {msg} '{expected_type}' but '{actual_type}' found");
|
||||
self.new_exception_msg(error_type.clone(), msg)
|
||||
self.new_exception_msg(error_type.to_owned(), msg)
|
||||
}
|
||||
|
||||
pub(crate) fn new_downcast_runtime_error(
|
||||
&self,
|
||||
class: &PyTypeRef,
|
||||
class: &Py<PyType>,
|
||||
obj: &impl AsObject,
|
||||
) -> PyBaseExceptionRef {
|
||||
self.new_downcast_error(
|
||||
"payload",
|
||||
&self.ctx.exceptions.runtime_error,
|
||||
self.ctx.exceptions.runtime_error,
|
||||
class,
|
||||
obj.as_object(),
|
||||
)
|
||||
@@ -292,12 +297,12 @@ impl VirtualMachine {
|
||||
|
||||
pub(crate) fn new_downcast_type_error(
|
||||
&self,
|
||||
class: &PyTypeRef,
|
||||
class: &Py<PyType>,
|
||||
obj: &impl AsObject,
|
||||
) -> PyBaseExceptionRef {
|
||||
self.new_downcast_error(
|
||||
"type",
|
||||
&self.ctx.exceptions.type_error,
|
||||
self.ctx.exceptions.type_error,
|
||||
class,
|
||||
obj.as_object(),
|
||||
)
|
||||
|
||||
@@ -74,7 +74,7 @@ impl VirtualMachine {
|
||||
match iter.length(self) {
|
||||
Ok(len) => return Ok(Some(len)),
|
||||
Err(e) => {
|
||||
if !e.fast_isinstance(&self.ctx.exceptions.type_error) {
|
||||
if !e.fast_isinstance(self.ctx.exceptions.type_error) {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ impl VirtualMachine {
|
||||
res
|
||||
}
|
||||
Err(e) => {
|
||||
return if e.fast_isinstance(&self.ctx.exceptions.type_error) {
|
||||
return if e.fast_isinstance(self.ctx.exceptions.type_error) {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(e)
|
||||
@@ -178,7 +178,7 @@ impl VirtualMachine {
|
||||
if let Some((lop, rop)) = lop.zip(rop) {
|
||||
if !lop.is(&rop) {
|
||||
if let Ok(r) = self.call_or_unsupported(rhs, lhs, reflection, |vm, _, _| {
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.exception_type.clone()))
|
||||
Err(vm.new_exception_empty(vm.ctx.exceptions.exception_type.to_owned()))
|
||||
}) {
|
||||
return Ok(r);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user