1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
// Copyright (c) 2017-present PyO3 Project and Contributors

//! Context manager api
//! Trait and support implementation for context manager api
//!

use crate::class::methods::PyMethodDef;
use crate::err::PyResult;
use crate::type_object::PyTypeInfo;
use crate::PyObject;

/// Context manager interface
#[allow(unused_variables)]
pub trait PyContextProtocol<'p>: PyTypeInfo {
    fn __enter__(&'p mut self) -> Self::Result
    where
        Self: PyContextEnterProtocol<'p>,
    {
        unimplemented!()
    }

    fn __exit__(
        &'p mut self,
        exc_type: Option<Self::ExcType>,
        exc_value: Option<Self::ExcValue>,
        traceback: Option<Self::Traceback>,
    ) -> Self::Result
    where
        Self: PyContextExitProtocol<'p>,
    {
        unimplemented!()
    }
}

pub trait PyContextEnterProtocol<'p>: PyContextProtocol<'p> {
    type Success: crate::IntoPy<PyObject>;
    type Result: Into<PyResult<Self::Success>>;
}

pub trait PyContextExitProtocol<'p>: PyContextProtocol<'p> {
    type ExcType: crate::FromPyObject<'p>;
    type ExcValue: crate::FromPyObject<'p>;
    type Traceback: crate::FromPyObject<'p>;
    type Success: crate::IntoPy<PyObject>;
    type Result: Into<PyResult<Self::Success>>;
}

#[doc(hidden)]
pub trait PyContextProtocolImpl {
    fn methods() -> Vec<PyMethodDef>;
}

impl<T> PyContextProtocolImpl for T {
    default fn methods() -> Vec<PyMethodDef> {
        Vec::new()
    }
}

impl<'p, T> PyContextProtocolImpl for T
where
    T: PyContextProtocol<'p>,
{
    #[inline]
    fn methods() -> Vec<PyMethodDef> {
        let mut methods = Vec::new();

        if let Some(def) = <Self as PyContextEnterProtocolImpl>::__enter__() {
            methods.push(def)
        }
        if let Some(def) = <Self as PyContextExitProtocolImpl>::__exit__() {
            methods.push(def)
        }

        methods
    }
}

#[doc(hidden)]
pub trait PyContextEnterProtocolImpl {
    fn __enter__() -> Option<PyMethodDef>;
}

impl<'p, T> PyContextEnterProtocolImpl for T
where
    T: PyContextProtocol<'p>,
{
    default fn __enter__() -> Option<PyMethodDef> {
        None
    }
}

#[doc(hidden)]
pub trait PyContextExitProtocolImpl {
    fn __exit__() -> Option<PyMethodDef>;
}

impl<'p, T> PyContextExitProtocolImpl for T
where
    T: PyContextProtocol<'p>,
{
    default fn __exit__() -> Option<PyMethodDef> {
        None
    }
}