Skip to content

Commit

Permalink
feature gate HasPyGilRef completely
Browse files Browse the repository at this point in the history
  • Loading branch information
Icxolu committed May 12, 2024
1 parent 93aef75 commit 2b83471
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 7 deletions.
6 changes: 3 additions & 3 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::err::{self, PyErr, PyResult};
use crate::impl_::pycell::PyClassObject;
use crate::pycell::{PyBorrowError, PyBorrowMutError};
use crate::pyclass::boolean_struct::{False, True};
#[cfg(feature = "gil-refs")]
use crate::type_object::HasPyGilRef;
use crate::types::{any::PyAnyMethods, string::PyStringMethods, typeobject::PyTypeMethods};
use crate::types::{DerefToPyAny, PyDict, PyString, PyTuple};
Expand Down Expand Up @@ -667,11 +668,11 @@ impl<'a, 'py, T> From<&'a Bound<'py, T>> for Borrowed<'a, 'py, T> {
}
}

#[cfg(feature = "gil-refs")]
impl<'py, T> Borrowed<'py, 'py, T>
where
T: HasPyGilRef,
{
#[cfg(feature = "gil-refs")]
pub(crate) fn into_gil_ref(self) -> &'py T::AsRefTarget {
// Safety: self is a borrow over `'py`.
#[allow(deprecated)]
Expand Down Expand Up @@ -954,6 +955,7 @@ where
}
}

#[cfg(feature = "gil-refs")]
impl<T> Py<T>
where
T: HasPyGilRef,
Expand Down Expand Up @@ -1001,7 +1003,6 @@ where
/// assert!(my_class_cell.try_borrow().is_ok());
/// });
/// ```
#[cfg(feature = "gil-refs")]
#[deprecated(
since = "0.21.0",
note = "use `obj.bind(py)` instead of `obj.as_ref(py)`"
Expand Down Expand Up @@ -1054,7 +1055,6 @@ where
/// obj.into_ref(py)
/// }
/// ```
#[cfg(feature = "gil-refs")]
#[deprecated(
since = "0.21.0",
note = "use `obj.into_bound(py)` instead of `obj.into_ref(py)`"
Expand Down
73 changes: 69 additions & 4 deletions src/type_object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ pub trait PySizedLayout<T>: PyLayout<T> + Sized {}
///
/// - `Py<Self>::as_ref` will hand out references to `Self::AsRefTarget`.
/// - `Self::AsRefTarget` must have the same layout as `UnsafeCell<ffi::PyAny>`.
#[cfg(feature = "gil-refs")]
pub unsafe trait HasPyGilRef {
/// Utility type to make Py::as_ref work.
#[cfg(feature = "gil-refs")]
type AsRefTarget: PyNativeType;
}

Expand All @@ -45,9 +45,6 @@ where
type AsRefTarget = Self;
}

#[cfg(not(feature = "gil-refs"))]
unsafe impl<T> HasPyGilRef for T {}

/// Python type information.
/// All Python native types (e.g., `PyDict`) and `#[pyclass]` structs implement this trait.
///
Expand All @@ -61,6 +58,7 @@ unsafe impl<T> HasPyGilRef for T {}
///
/// Implementations must provide an implementation for `type_object_raw` which infallibly produces a
/// non-null pointer to the corresponding Python type object.
#[cfg(feature = "gil-refs")]
pub unsafe trait PyTypeInfo: Sized + HasPyGilRef {
/// Class name.
const NAME: &'static str;
Expand Down Expand Up @@ -139,7 +137,62 @@ pub unsafe trait PyTypeInfo: Sized + HasPyGilRef {
}
}

/// Python type information.
/// All Python native types (e.g., `PyDict`) and `#[pyclass]` structs implement this trait.
///
/// This trait is marked unsafe because:
/// - specifying the incorrect layout can lead to memory errors
/// - the return value of type_object must always point to the same PyTypeObject instance
///
/// It is safely implemented by the `pyclass` macro.
///
/// # Safety
///
/// Implementations must provide an implementation for `type_object_raw` which infallibly produces a
/// non-null pointer to the corresponding Python type object.
#[cfg(not(feature = "gil-refs"))]
pub unsafe trait PyTypeInfo: Sized {
/// Class name.
const NAME: &'static str;

/// Module name, if any.
const MODULE: Option<&'static str>;

/// Returns the PyTypeObject instance for this type.
fn type_object_raw(py: Python<'_>) -> *mut ffi::PyTypeObject;

/// Returns the safe abstraction over the type object.
#[inline]
fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType> {
// Making the borrowed object `Bound` is necessary for soundness reasons. It's an extreme
// edge case, but arbitrary Python code _could_ change the __class__ of an object and cause
// the type object to be freed.
//
// By making `Bound` we assume ownership which is then safe against races.
unsafe {
Self::type_object_raw(py)
.cast::<ffi::PyObject>()
.assume_borrowed_unchecked(py)
.to_owned()
.downcast_into_unchecked()
}
}

/// Checks if `object` is an instance of this type or a subclass of this type.
#[inline]
fn is_type_of_bound(object: &Bound<'_, PyAny>) -> bool {
unsafe { ffi::PyObject_TypeCheck(object.as_ptr(), Self::type_object_raw(object.py())) != 0 }
}

/// Checks if `object` is an instance of this type.
#[inline]
fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool {
unsafe { ffi::Py_TYPE(object.as_ptr()) == Self::type_object_raw(object.py()) }
}
}

/// Implemented by types which can be used as a concrete Python type inside `Py<T>` smart pointers.
#[cfg(feature = "gil-refs")]
pub trait PyTypeCheck: HasPyGilRef {
/// Name of self. This is used in error messages, for example.
const NAME: &'static str;
Expand All @@ -150,6 +203,18 @@ pub trait PyTypeCheck: HasPyGilRef {
fn type_check(object: &Bound<'_, PyAny>) -> bool;
}

/// Implemented by types which can be used as a concrete Python type inside `Py<T>` smart pointers.
#[cfg(not(feature = "gil-refs"))]
pub trait PyTypeCheck {
/// Name of self. This is used in error messages, for example.
const NAME: &'static str;

/// Checks if `object` is an instance of `Self`, which may include a subtype.
///
/// This should be equivalent to the Python expression `isinstance(object, Self)`.
fn type_check(object: &Bound<'_, PyAny>) -> bool;
}

impl<T> PyTypeCheck for T
where
T: PyTypeInfo,
Expand Down

0 comments on commit 2b83471

Please sign in to comment.