From 59582ed295a827225fe8bc393deff828be590b4d Mon Sep 17 00:00:00 2001 From: snowapril Date: Sat, 6 Nov 2021 17:17:31 +0900 Subject: [PATCH] Add new_exception_type for module-level exception At previous, `vm.ctx.new_class` did role for adding exception in module-level. This commit add `new_exception_type` for doing that part of role. As cpython implementation, if no bases is given, pass `exception_type` by default Signed-off-by: snowapril --- vm/src/pyobject.rs | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/vm/src/pyobject.rs b/vm/src/pyobject.rs index d7cff5d60..0d78ba471 100644 --- a/vm/src/pyobject.rs +++ b/vm/src/pyobject.rs @@ -12,9 +12,9 @@ use crate::{ builtinfunc::{PyBuiltinFunction, PyBuiltinMethod, PyNativeFuncDef}, bytes, getset::{IntoPyGetterFunc, IntoPySetterFunc, PyGetSet}, - object, pystr, PyBaseExceptionRef, PyBoundMethod, PyDict, PyDictRef, PyEllipsis, PyFloat, - PyFrozenSet, PyGenericAlias, PyInt, PyIntRef, PyList, PyListRef, PyNone, PyNotImplemented, - PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef, + object, pystr, PyBaseException, PyBaseExceptionRef, PyBoundMethod, PyDict, PyDictRef, + PyEllipsis, PyFloat, PyFrozenSet, PyGenericAlias, PyInt, PyIntRef, PyList, PyListRef, + PyNone, PyNotImplemented, PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef, }, dictdatatype::Dict, exceptions, @@ -242,6 +242,30 @@ impl PyContext { .unwrap() } + pub fn new_exception_type( + &self, + module: &str, + name: &str, + bases: Option>, + ) -> PyTypeRef { + let bases = if let Some(bases) = bases { + bases + } else { + vec![self.exceptions.exception_type.clone()] + }; + let mut attrs = PyAttributes::default(); + attrs.insert("__module__".to_string(), self.new_str(module).into()); + + PyType::new_ref( + name, + bases, + attrs, + PyBaseException::make_slots(), + self.types.type_type.clone(), + ) + .unwrap() + } + #[inline] pub fn make_funcdef(&self, name: impl Into, f: F) -> PyNativeFuncDef where