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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/*! Python `attribute` descriptor class. (PyGetSet)

*/
use super::objtype::PyClassRef;
use crate::function::{OptionalArg, OwnedParam, RefParam};
use crate::pyobject::{
    IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
};
use crate::slots::SlotDescriptor;
use crate::vm::VirtualMachine;

pub type PyGetterFunc = Box<dyn Fn(&VirtualMachine, PyObjectRef) -> PyResult>;
pub type PySetterFunc = Box<dyn Fn(&VirtualMachine, PyObjectRef, PyObjectRef) -> PyResult<()>>;

pub trait IntoPyGetterFunc<T> {
    fn into_getter(self) -> PyGetterFunc;
}

impl<F, T, R> IntoPyGetterFunc<(OwnedParam<T>, R, VirtualMachine)> for F
where
    F: Fn(T, &VirtualMachine) -> R + 'static,
    T: TryFromObject,
    R: IntoPyObject,
{
    fn into_getter(self) -> PyGetterFunc {
        Box::new(move |vm, obj| {
            let obj = T::try_from_object(vm, obj)?;
            (self)(obj, vm).into_pyobject(vm)
        })
    }
}

impl<F, S, R> IntoPyGetterFunc<(RefParam<S>, R, VirtualMachine)> for F
where
    F: Fn(&S, &VirtualMachine) -> R + 'static,
    S: PyValue,
    R: IntoPyObject,
{
    fn into_getter(self) -> PyGetterFunc {
        Box::new(move |vm, obj| {
            let zelf = PyRef::<S>::try_from_object(vm, obj)?;
            (self)(&zelf, vm).into_pyobject(vm)
        })
    }
}

impl<F, T, R> IntoPyGetterFunc<(OwnedParam<T>, R)> for F
where
    F: Fn(T) -> R + 'static,
    T: TryFromObject,
    R: IntoPyObject,
{
    fn into_getter(self) -> PyGetterFunc {
        IntoPyGetterFunc::into_getter(move |obj, _vm: &VirtualMachine| (self)(obj))
    }
}

impl<F, S, R> IntoPyGetterFunc<(RefParam<S>, R)> for F
where
    F: Fn(&S) -> R + 'static,
    S: PyValue,
    R: IntoPyObject,
{
    fn into_getter(self) -> PyGetterFunc {
        IntoPyGetterFunc::into_getter(move |zelf: &S, _vm: &VirtualMachine| (self)(zelf))
    }
}

pub trait IntoPyNoResult {
    fn into_noresult(self) -> PyResult<()>;
}

impl IntoPyNoResult for () {
    fn into_noresult(self) -> PyResult<()> {
        Ok(())
    }
}

impl IntoPyNoResult for PyResult<()> {
    fn into_noresult(self) -> PyResult<()> {
        self
    }
}

pub trait IntoPySetterFunc<T> {
    fn into_setter(self) -> PySetterFunc;
}

impl<F, T, V, R> IntoPySetterFunc<(OwnedParam<T>, V, R, VirtualMachine)> for F
where
    F: Fn(T, V, &VirtualMachine) -> R + 'static,
    T: TryFromObject,
    V: TryFromObject,
    R: IntoPyNoResult,
{
    fn into_setter(self) -> PySetterFunc {
        Box::new(move |vm, obj, value| {
            let obj = T::try_from_object(vm, obj)?;
            let value = V::try_from_object(vm, value)?;
            (self)(obj, value, vm).into_noresult()
        })
    }
}

impl<F, S, V, R> IntoPySetterFunc<(RefParam<S>, V, R, VirtualMachine)> for F
where
    F: Fn(&S, V, &VirtualMachine) -> R + 'static,
    S: PyValue,
    V: TryFromObject,
    R: IntoPyNoResult,
{
    fn into_setter(self) -> PySetterFunc {
        Box::new(move |vm, obj, value| {
            let zelf = PyRef::<S>::try_from_object(vm, obj)?;
            let value = V::try_from_object(vm, value)?;
            (self)(&zelf, value, vm).into_noresult()
        })
    }
}

impl<F, T, V, R> IntoPySetterFunc<(OwnedParam<T>, V, R)> for F
where
    F: Fn(T, V) -> R + 'static,
    T: TryFromObject,
    V: TryFromObject,
    R: IntoPyNoResult,
{
    fn into_setter(self) -> PySetterFunc {
        IntoPySetterFunc::into_setter(move |obj, v, _vm: &VirtualMachine| (self)(obj, v))
    }
}

impl<F, S, V, R> IntoPySetterFunc<(RefParam<S>, V, R)> for F
where
    F: Fn(&S, V) -> R + 'static,
    S: PyValue,
    V: TryFromObject,
    R: IntoPyNoResult,
{
    fn into_setter(self) -> PySetterFunc {
        IntoPySetterFunc::into_setter(move |zelf: &S, v, _vm: &VirtualMachine| (self)(zelf, v))
    }
}

#[pyclass]
pub struct PyGetSet {
    name: String,
    getter: Option<PyGetterFunc>,
    setter: Option<PySetterFunc>,
    // doc: Option<String>,
}

impl std::fmt::Debug for PyGetSet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "PyGetSet {{ name: {}, getter: {}, setter: {} }}",
            self.name,
            if self.getter.is_some() {
                "Some"
            } else {
                "None"
            },
            if self.setter.is_some() {
                "Some"
            } else {
                "None"
            },
        )
    }
}

impl PyValue for PyGetSet {
    fn class(vm: &VirtualMachine) -> PyClassRef {
        vm.ctx.getset_type()
    }
}

pub type PyGetSetRef = PyRef<PyGetSet>;

impl SlotDescriptor for PyGetSet {
    fn descr_get(
        vm: &VirtualMachine,
        zelf: PyObjectRef,
        obj: Option<PyObjectRef>,
        _cls: OptionalArg<PyObjectRef>,
    ) -> PyResult {
        let (zelf, obj) = match Self::_check(zelf, obj, vm) {
            Ok(obj) => obj,
            Err(result) => return result,
        };
        if let Some(ref f) = zelf.getter {
            f(vm, obj)
        } else {
            Err(vm.new_attribute_error(format!(
                "attribute '{}' of '{}' objects is not readable",
                zelf.name,
                Self::class(vm).name
            )))
        }
    }
}

impl PyGetSet {
    pub fn with_get<G, X>(name: String, getter: G) -> Self
    where
        G: IntoPyGetterFunc<X>,
    {
        Self {
            name,
            getter: Some(getter.into_getter()),
            setter: None,
        }
    }

    pub fn with_get_set<G, S, X, Y>(name: String, getter: G, setter: S) -> Self
    where
        G: IntoPyGetterFunc<X>,
        S: IntoPySetterFunc<Y>,
    {
        Self {
            name,
            getter: Some(getter.into_getter()),
            setter: Some(setter.into_setter()),
        }
    }
}

#[pyimpl(with(SlotDescriptor))]
impl PyGetSet {
    // Descriptor methods

    #[pymethod(magic)]
    fn set(&self, obj: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
        if let Some(ref f) = self.setter {
            f(vm, obj, value)
        } else {
            Err(vm.new_attribute_error(format!(
                "attribute '{}' of '{}' objects is not writable",
                self.name,
                Self::class(vm).name
            )))
        }
    }
}

pub(crate) fn init(context: &PyContext) {
    PyGetSet::extend_class(context, &context.types.getset_type);
}