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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
// Copyright (c) 2017-present PyO3 Project and Contributors

//! Basic Python Object customization
//!
//! Check [python c-api information](https://docs.python.org/3/reference/datamodel.html#basic-customization)
//! for more information.
//!
//! Parts of the documentation are copied from the respective methods from the
//! [typeobj docs](https://docs.python.org/3/c-api/typeobj.html)

use crate::callback::{BoolCallbackConverter, HashConverter, PyObjectCallbackConverter};
use crate::class::methods::PyMethodDef;
use crate::err::{PyErr, PyResult};
use crate::ffi;
use crate::objectprotocol::ObjectProtocol;
use crate::type_object::PyTypeInfo;
use crate::types::PyAny;
use crate::FromPyObject;
use crate::IntoPyPointer;
use crate::Python;
use crate::{exceptions, IntoPy, PyObject};
use std::os::raw::c_int;
use std::ptr;

/// Operators for the __richcmp__ method
#[derive(Debug)]
pub enum CompareOp {
    Lt = ffi::Py_LT as isize,
    Le = ffi::Py_LE as isize,
    Eq = ffi::Py_EQ as isize,
    Ne = ffi::Py_NE as isize,
    Gt = ffi::Py_GT as isize,
    Ge = ffi::Py_GE as isize,
}

/// Basic python class customization
#[allow(unused_variables)]
pub trait PyObjectProtocol<'p>: PyTypeInfo {
    fn __getattr__(&'p self, name: Self::Name) -> Self::Result
    where
        Self: PyObjectGetAttrProtocol<'p>,
    {
        unimplemented!()
    }

    fn __setattr__(&'p mut self, name: Self::Name, value: Self::Value) -> Self::Result
    where
        Self: PyObjectSetAttrProtocol<'p>,
    {
        unimplemented!()
    }

    fn __delattr__(&'p mut self, name: Self::Name) -> Self::Result
    where
        Self: PyObjectDelAttrProtocol<'p>,
    {
        unimplemented!()
    }

    fn __str__(&'p self) -> Self::Result
    where
        Self: PyObjectStrProtocol<'p>,
    {
        unimplemented!()
    }

    fn __repr__(&'p self) -> Self::Result
    where
        Self: PyObjectReprProtocol<'p>,
    {
        unimplemented!()
    }

    fn __format__(&'p self, format_spec: Self::Format) -> Self::Result
    where
        Self: PyObjectFormatProtocol<'p>,
    {
        unimplemented!()
    }

    fn __hash__(&'p self) -> Self::Result
    where
        Self: PyObjectHashProtocol<'p>,
    {
        unimplemented!()
    }

    fn __bool__(&'p self) -> Self::Result
    where
        Self: PyObjectBoolProtocol<'p>,
    {
        unimplemented!()
    }

    fn __bytes__(&'p self) -> Self::Result
    where
        Self: PyObjectBytesProtocol<'p>,
    {
        unimplemented!()
    }

    fn __richcmp__(&'p self, other: Self::Other, op: CompareOp) -> Self::Result
    where
        Self: PyObjectRichcmpProtocol<'p>,
    {
        unimplemented!()
    }
}

pub trait PyObjectGetAttrProtocol<'p>: PyObjectProtocol<'p> {
    type Name: FromPyObject<'p>;
    type Success: IntoPy<PyObject>;
    type Result: Into<PyResult<Self::Success>>;
}
pub trait PyObjectSetAttrProtocol<'p>: PyObjectProtocol<'p> {
    type Name: FromPyObject<'p>;
    type Value: FromPyObject<'p>;
    type Result: Into<PyResult<()>>;
}
pub trait PyObjectDelAttrProtocol<'p>: PyObjectProtocol<'p> {
    type Name: FromPyObject<'p>;
    type Result: Into<PyResult<()>>;
}
pub trait PyObjectStrProtocol<'p>: PyObjectProtocol<'p> {
    type Success: IntoPy<PyObject>;
    type Result: Into<PyResult<Self::Success>>;
}
pub trait PyObjectReprProtocol<'p>: PyObjectProtocol<'p> {
    type Success: IntoPy<PyObject>;
    type Result: Into<PyResult<Self::Success>>;
}
pub trait PyObjectFormatProtocol<'p>: PyObjectProtocol<'p> {
    type Format: FromPyObject<'p>;
    type Success: IntoPy<PyObject>;
    type Result: Into<PyResult<Self::Success>>;
}
pub trait PyObjectHashProtocol<'p>: PyObjectProtocol<'p> {
    type Result: Into<PyResult<isize>>;
}
pub trait PyObjectBoolProtocol<'p>: PyObjectProtocol<'p> {
    type Result: Into<PyResult<bool>>;
}
pub trait PyObjectBytesProtocol<'p>: PyObjectProtocol<'p> {
    type Success: IntoPy<PyObject>;
    type Result: Into<PyResult<Self::Success>>;
}
pub trait PyObjectRichcmpProtocol<'p>: PyObjectProtocol<'p> {
    type Other: FromPyObject<'p>;
    type Success: IntoPy<PyObject>;
    type Result: Into<PyResult<Self::Success>>;
}

#[doc(hidden)]
pub trait PyObjectProtocolImpl {
    fn methods() -> Vec<PyMethodDef>;
    fn tp_as_object(_type_object: &mut ffi::PyTypeObject);
    fn nb_bool_fn() -> Option<ffi::inquiry>;
}

impl<T> PyObjectProtocolImpl for T {
    default fn methods() -> Vec<PyMethodDef> {
        Vec::new()
    }
    default fn tp_as_object(_type_object: &mut ffi::PyTypeObject) {}
    default fn nb_bool_fn() -> Option<ffi::inquiry> {
        None
    }
}

impl<'p, T> PyObjectProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    fn methods() -> Vec<PyMethodDef> {
        let mut methods = Vec::new();

        if let Some(def) = <Self as FormatProtocolImpl>::__format__() {
            methods.push(def)
        }
        if let Some(def) = <Self as BytesProtocolImpl>::__bytes__() {
            methods.push(def)
        }
        if let Some(def) = <Self as UnicodeProtocolImpl>::__unicode__() {
            methods.push(def)
        }
        methods
    }
    fn tp_as_object(type_object: &mut ffi::PyTypeObject) {
        type_object.tp_str = Self::tp_str();
        type_object.tp_repr = Self::tp_repr();
        type_object.tp_hash = Self::tp_hash();
        type_object.tp_getattro = Self::tp_getattro();
        type_object.tp_richcompare = Self::tp_richcompare();
        type_object.tp_setattro = tp_setattro_impl::tp_setattro::<Self>();
    }
    fn nb_bool_fn() -> Option<ffi::inquiry> {
        Self::nb_bool()
    }
}

trait GetAttrProtocolImpl {
    fn tp_getattro() -> Option<ffi::binaryfunc>;
}

impl<'p, T> GetAttrProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn tp_getattro() -> Option<ffi::binaryfunc> {
        None
    }
}

impl<T> GetAttrProtocolImpl for T
where
    T: for<'p> PyObjectGetAttrProtocol<'p>,
{
    fn tp_getattro() -> Option<ffi::binaryfunc> {
        #[allow(unused_mut)]
        unsafe extern "C" fn wrap<T>(
            slf: *mut ffi::PyObject,
            arg: *mut ffi::PyObject,
        ) -> *mut ffi::PyObject
        where
            T: for<'p> PyObjectGetAttrProtocol<'p>,
        {
            let py = Python::assume_gil_acquired();
            let _pool = crate::GILPool::new(py);

            // Behave like python's __getattr__ (as opposed to __getattribute__) and check
            // for existing fields and methods first
            let existing = ffi::PyObject_GenericGetAttr(slf, arg);
            if existing.is_null() {
                // PyObject_HasAttr also tries to get an object and clears the error if it fails
                ffi::PyErr_Clear();
            } else {
                return existing;
            }

            let slf = py.mut_from_borrowed_ptr::<T>(slf);
            let arg = py.from_borrowed_ptr::<crate::types::PyAny>(arg);

            let result = match arg.extract() {
                Ok(arg) => slf.__getattr__(arg).into(),
                Err(e) => Err(e),
            };
            crate::callback::cb_convert(PyObjectCallbackConverter, py, result)
        }
        Some(wrap::<T>)
    }
}

/// An object may support setting attributes (by implementing PyObjectSetAttrProtocol)
/// and may support deleting attributes (by implementing PyObjectDelAttrProtocol)
/// and we need to generate a single extern c function that supports only setting, only deleting
/// or both, and return None in case none of the two is supported.
mod tp_setattro_impl {
    use super::*;

    /// setattrofunc PyTypeObject.tp_setattro
    ///
    /// An optional pointer to the function for setting and deleting attributes.
    ///
    /// The signature is the same as for PyObject_SetAttr(), but setting v to NULL to delete an
    /// attribute must be supported. It is usually convenient to set this field to
    /// PyObject_GenericSetAttr(), which implements the normal way of setting object attributes.
    pub(super) fn tp_setattro<'p, T: PyObjectProtocol<'p>>() -> Option<ffi::setattrofunc> {
        if let Some(set_del) = T::set_del_attr() {
            Some(set_del)
        } else if let Some(set) = T::set_attr() {
            Some(set)
        } else if let Some(del) = T::del_attr() {
            Some(del)
        } else {
            None
        }
    }

    trait SetAttr {
        fn set_attr() -> Option<ffi::setattrofunc>;
    }

    impl<'p, T: PyObjectProtocol<'p>> SetAttr for T {
        default fn set_attr() -> Option<ffi::setattrofunc> {
            None
        }
    }

    impl<T> SetAttr for T
    where
        T: for<'p> PyObjectSetAttrProtocol<'p>,
    {
        fn set_attr() -> Option<ffi::setattrofunc> {
            py_func_set!(PyObjectSetAttrProtocol, T, __setattr__)
        }
    }

    trait DelAttr {
        fn del_attr() -> Option<ffi::setattrofunc>;
    }

    impl<'p, T> DelAttr for T
    where
        T: PyObjectProtocol<'p>,
    {
        default fn del_attr() -> Option<ffi::setattrofunc> {
            None
        }
    }

    impl<T> DelAttr for T
    where
        T: for<'p> PyObjectDelAttrProtocol<'p>,
    {
        fn del_attr() -> Option<ffi::setattrofunc> {
            py_func_del!(PyObjectDelAttrProtocol, T, __delattr__)
        }
    }

    trait SetDelAttr {
        fn set_del_attr() -> Option<ffi::setattrofunc>;
    }

    impl<'p, T> SetDelAttr for T
    where
        T: PyObjectProtocol<'p>,
    {
        default fn set_del_attr() -> Option<ffi::setattrofunc> {
            None
        }
    }

    impl<T> SetDelAttr for T
    where
        T: for<'p> PyObjectSetAttrProtocol<'p> + for<'p> PyObjectDelAttrProtocol<'p>,
    {
        fn set_del_attr() -> Option<ffi::setattrofunc> {
            py_func_set_del!(
                PyObjectSetAttrProtocol,
                PyObjectDelAttrProtocol,
                T,
                __setattr__,
                __delattr__
            )
        }
    }
}

trait StrProtocolImpl {
    fn tp_str() -> Option<ffi::unaryfunc>;
}
impl<'p, T> StrProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn tp_str() -> Option<ffi::unaryfunc> {
        None
    }
}
impl<T> StrProtocolImpl for T
where
    T: for<'p> PyObjectStrProtocol<'p>,
{
    fn tp_str() -> Option<ffi::unaryfunc> {
        py_unary_func!(
            PyObjectStrProtocol,
            T::__str__,
            <T as PyObjectStrProtocol>::Success,
            PyObjectCallbackConverter
        )
    }
}

trait ReprProtocolImpl {
    fn tp_repr() -> Option<ffi::unaryfunc>;
}
impl<'p, T> ReprProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn tp_repr() -> Option<ffi::unaryfunc> {
        None
    }
}
impl<T> ReprProtocolImpl for T
where
    T: for<'p> PyObjectReprProtocol<'p>,
{
    fn tp_repr() -> Option<ffi::unaryfunc> {
        py_unary_func!(
            PyObjectReprProtocol,
            T::__repr__,
            T::Success,
            PyObjectCallbackConverter
        )
    }
}

#[doc(hidden)]
pub trait FormatProtocolImpl {
    fn __format__() -> Option<PyMethodDef>;
}
impl<'p, T> FormatProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn __format__() -> Option<PyMethodDef> {
        None
    }
}

#[doc(hidden)]
pub trait BytesProtocolImpl {
    fn __bytes__() -> Option<PyMethodDef>;
}
impl<'p, T> BytesProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn __bytes__() -> Option<PyMethodDef> {
        None
    }
}

#[doc(hidden)]
pub trait UnicodeProtocolImpl {
    fn __unicode__() -> Option<PyMethodDef>;
}
impl<'p, T> UnicodeProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn __unicode__() -> Option<PyMethodDef> {
        None
    }
}

trait HashProtocolImpl {
    fn tp_hash() -> Option<ffi::hashfunc>;
}
impl<'p, T> HashProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn tp_hash() -> Option<ffi::hashfunc> {
        None
    }
}
impl<T> HashProtocolImpl for T
where
    T: for<'p> PyObjectHashProtocol<'p>,
{
    fn tp_hash() -> Option<ffi::hashfunc> {
        py_unary_func!(
            PyObjectHashProtocol,
            T::__hash__,
            isize,
            HashConverter,
            ffi::Py_hash_t
        )
    }
}

trait BoolProtocolImpl {
    fn nb_bool() -> Option<ffi::inquiry>;
}
impl<'p, T> BoolProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn nb_bool() -> Option<ffi::inquiry> {
        None
    }
}
impl<T> BoolProtocolImpl for T
where
    T: for<'p> PyObjectBoolProtocol<'p>,
{
    fn nb_bool() -> Option<ffi::inquiry> {
        py_unary_func!(
            PyObjectBoolProtocol,
            T::__bool__,
            bool,
            BoolCallbackConverter,
            c_int
        )
    }
}

trait RichcmpProtocolImpl {
    fn tp_richcompare() -> Option<ffi::richcmpfunc>;
}
impl<'p, T> RichcmpProtocolImpl for T
where
    T: PyObjectProtocol<'p>,
{
    default fn tp_richcompare() -> Option<ffi::richcmpfunc> {
        None
    }
}
impl<T> RichcmpProtocolImpl for T
where
    T: for<'p> PyObjectRichcmpProtocol<'p>,
{
    fn tp_richcompare() -> Option<ffi::richcmpfunc> {
        unsafe extern "C" fn wrap<T>(
            slf: *mut ffi::PyObject,
            arg: *mut ffi::PyObject,
            op: c_int,
        ) -> *mut ffi::PyObject
        where
            T: for<'p> PyObjectRichcmpProtocol<'p>,
        {
            let py = Python::assume_gil_acquired();
            let _pool = crate::GILPool::new(py);
            let slf = py.from_borrowed_ptr::<T>(slf);
            let arg = py.from_borrowed_ptr::<PyAny>(arg);

            let res = match extract_op(op) {
                Ok(op) => match arg.extract() {
                    Ok(arg) => slf.__richcmp__(arg, op).into(),
                    Err(e) => Err(e),
                },
                Err(e) => Err(e),
            };
            match res {
                Ok(val) => val.into_py(py).into_ptr(),
                Err(e) => {
                    e.restore(py);
                    ptr::null_mut()
                }
            }
        }
        Some(wrap::<T>)
    }
}

fn extract_op(op: c_int) -> PyResult<CompareOp> {
    match op {
        ffi::Py_LT => Ok(CompareOp::Lt),
        ffi::Py_LE => Ok(CompareOp::Le),
        ffi::Py_EQ => Ok(CompareOp::Eq),
        ffi::Py_NE => Ok(CompareOp::Ne),
        ffi::Py_GT => Ok(CompareOp::Gt),
        ffi::Py_GE => Ok(CompareOp::Ge),
        _ => Err(PyErr::new::<exceptions::ValueError, _>(
            "tp_richcompare called with invalid comparison operator",
        )),
    }
}