summaryrefslogtreecommitdiff
path: root/src/zope/proxy/_zope_proxy_proxy.c
blob: d2cc20bf47a750d218463fe6203d841a36e58499 (plain)
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
/*############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
############################################################################*/

/*
 *   This file is also used as a really extensive macro in
 *   ../container/_zope_container_contained.c.  If you need to
 *   change this file, you need to "svn copy" it to ../container/.
 *
 *   This approach is taken to allow the sources for the two packages
 *   to be compilable when the relative locations of these aren't
 *   related in the same way as they are in a checkout.
 *
 *   This will be revisited in the future, but works for now.
 */

#include "Python.h"
#include "modsupport.h"

#define PROXY_MODULE
#include "proxy.h"

static PyTypeObject ProxyType;

#define Proxy_Check(wrapper)   (PyObject_TypeCheck((wrapper), &ProxyType))

static PyObject *
empty_tuple = NULL;


#define MOD_ERROR_VAL NULL

#define MOD_SUCCESS_VAL(val) val

#define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)

#define MOD_DEF(ob, name, doc, methods) \
        static struct PyModuleDef moduledef = { \
          PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
        ob = PyModule_Create(&moduledef);



/*
 *   Slot methods.
 */

static PyObject *
wrap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *result = NULL;
    PyObject *object;

    if (PyArg_UnpackTuple(args, "__new__", 1, 1, &object)) {
        if (kwds != NULL && PyDict_Size(kwds) != 0) {
            PyErr_SetString(PyExc_TypeError,
                            "proxy.__new__ does not accept keyword args");
            return NULL;
        }
        result = PyType_GenericNew(type, args, kwds);
        if (result != NULL) {
            ProxyObject *wrapper = (ProxyObject *) result;
            Py_INCREF(object);
            wrapper->proxy_object = object;
        }
    }
    return result;
}

static int
wrap_init(PyObject *self, PyObject *args, PyObject *kwds)
{
    int result = -1;
    PyObject *object;

    if (PyArg_UnpackTuple(args, "__init__", 1, 1, &object)) {
        ProxyObject *wrapper = (ProxyObject *)self;
        if (kwds != NULL && PyDict_Size(kwds) != 0) {
            PyErr_SetString(PyExc_TypeError,
                            "proxy.__init__ does not accept keyword args");
            return -1;
        }
        /* If the object in this proxy is not the one we
         * received in args, replace it with the new one.
         */
        if (wrapper->proxy_object != object) {
            PyObject *temp = wrapper->proxy_object;
            Py_INCREF(object);
            wrapper->proxy_object = object;
            Py_DECREF(temp);
        }
        result = 0;
    }
    return result;
}

static int
wrap_traverse(PyObject *self, visitproc visit, void *arg)
{
    PyObject *ob = Proxy_GET_OBJECT(self);
    if (ob != NULL)
        return visit(ob, arg);
    else
        return 0;
}

static int
wrap_clear(PyObject *self)
{
    ProxyObject *proxy = (ProxyObject *)self;
    PyObject *temp = proxy->proxy_object;

    if (temp != NULL) {
        proxy->proxy_object = NULL;
        Py_DECREF(temp);
    }
    return 0;
}

static PyObject *
wrap_richcompare(PyObject* self, PyObject* other, int op)
{
    if (Proxy_Check(self)) {
        self = Proxy_GET_OBJECT(self);
    }
    else {
        other = Proxy_GET_OBJECT(other);
    }
    return PyObject_RichCompare(self, other, op);
}

static PyObject *
wrap_iter(PyObject *self)
{
    return PyObject_GetIter(Proxy_GET_OBJECT(self));
}

static PyObject *
wrap_iternext(PyObject *self)
{
    return PyIter_Next(Proxy_GET_OBJECT(self));
}

static void
wrap_dealloc(PyObject *self)
{
    PyObject_GC_UnTrack(self);
    (void) wrap_clear(self);
    self->ob_type->tp_free(self);
}

/* A variant of _PyType_Lookup that doesn't look in ProxyType.
 *
 * If argument search_wrappertype is nonzero, we can look in WrapperType.
 */
PyObject *
WrapperType_Lookup(PyTypeObject *type, PyObject *name)
{
    int i, n;
    PyObject *mro, *res, *base, *dict;

    /* Look in tp_dict of types in MRO */
    mro = type->tp_mro;

    /* If mro is NULL, the type is either not yet initialized
       by PyType_Ready(), or already cleared by type_clear().
       Either way the safest thing to do is to return NULL. */
    if (mro == NULL)
        return NULL;

    assert(PyTuple_Check(mro));

    n = PyTuple_GET_SIZE(mro)
      - 1; /* We don't want to look at the last item, which is object. */

    for (i = 0; i < n; i++) {
        base = PyTuple_GET_ITEM(mro, i);

        if (((PyTypeObject *)base) != &ProxyType) {
            assert(PyType_Check(base));
            dict = ((PyTypeObject *)base)->tp_dict;
            assert(dict && PyDict_Check(dict));
            res = PyDict_GetItem(dict, name);
            if (res != NULL)
                return res;
        }
    }
    return NULL;
}


static PyObject *
wrap_getattro(PyObject *self, PyObject *name)
{
    PyObject *wrapped;
    PyObject *descriptor;
    PyObject *res = NULL;
    const char *name_as_string;
    int maybe_special_name;

    name_as_string = PyUnicode_AsUTF8(name);

    if (name_as_string == NULL) {
        return NULL;
    }

    wrapped = Proxy_GET_OBJECT(self);
    if (wrapped == NULL) {
        PyErr_Format(PyExc_RuntimeError,
            "object is NULL; requested to get attribute '%s'",
            name_as_string);
        goto finally;
    }

    maybe_special_name = name_as_string[0] == '_' && name_as_string[1] == '_';

    if (!(maybe_special_name
          && (strcmp(name_as_string, "__class__") == 0
              || strcmp(name_as_string, "__module__") == 0))) {

        descriptor = WrapperType_Lookup(self->ob_type, name);

        if (descriptor != NULL) {
            if (descriptor->ob_type->tp_descr_get != NULL
            ){
              if (descriptor->ob_type->tp_descr_set == NULL)
                {
                  res = PyObject_GetAttr(wrapped, name);
                  if (res != NULL)
                    goto finally;
                  if (PyErr_ExceptionMatches(PyExc_AttributeError))
                    PyErr_Clear();
                  else
                    goto finally;
                }

                res = descriptor->ob_type->tp_descr_get(
                        descriptor,
                        self,
                        (PyObject *)self->ob_type);
            }
            else
            {
                Py_INCREF(descriptor);
                res = descriptor;
            }

            goto finally;
        }
    }
    res = PyObject_GetAttr(wrapped, name);

finally:
    return res;
}

static int
wrap_setattro(PyObject *self, PyObject *name, PyObject *value)
{
    PyObject *wrapped;
    PyObject *descriptor;
    const char *name_as_string;
    int res = -1;

    name_as_string = PyUnicode_AsUTF8(name);

    if (name_as_string == NULL) {
        goto finally;
    }

    descriptor = WrapperType_Lookup(self->ob_type, name);

    if (descriptor != NULL
        && descriptor->ob_type->tp_descr_set != NULL)
      {
        res = descriptor->ob_type->tp_descr_set(descriptor, self, value);
        goto finally;
      }

    wrapped = Proxy_GET_OBJECT(self);
    if (wrapped == NULL) {
        PyErr_Format(PyExc_RuntimeError,
            "object is NULL; requested to set attribute '%s'",
            name_as_string);
        goto finally;
    }
    res = PyObject_SetAttr(wrapped, name, value);

finally:
    return res;
}

static PyObject *
wrap_str(PyObject *wrapper) {
    return PyObject_Str(Proxy_GET_OBJECT(wrapper));
}

static PyObject *
wrap_repr(PyObject *wrapper)
{
    return PyObject_Repr(Proxy_GET_OBJECT(wrapper));
}

static long
wrap_hash(PyObject *self)
{
    return PyObject_Hash(Proxy_GET_OBJECT(self));
}

static PyObject *
wrap_call(PyObject *self, PyObject *args, PyObject *kw)
{
    if (kw)
        return PyEval_CallObjectWithKeywords(Proxy_GET_OBJECT(self),
                                             args, kw);
    else
        return PyObject_CallObject(Proxy_GET_OBJECT(self), args);
}

/*
 * Number methods.
 */

static PyObject *
call_int(PyObject *self)
{
    return PyNumber_Long(self);
}


static PyObject *
call_index(PyObject *self)
{
    return PyNumber_Index(self);
}

static PyObject *
call_float(PyObject *self)
{
   return PyNumber_Float(self);
}

static PyObject *
call_ipow(PyObject *self, PyObject *other)
{
    /* PyNumber_InPlacePower has three args.  How silly. :-) */
    return PyNumber_InPlacePower(self, other, Py_None);
}


typedef PyObject *(*function1)(PyObject *);

static PyObject *
check1(ProxyObject *self, char *opname, function1 operation)
{
    PyObject *result = NULL;

    result = operation(Proxy_GET_OBJECT(self));
#if 0
    if (result != NULL)
        /* ??? create proxy for result? */
        ;
#endif
    return result;
}

static PyObject *
check2(PyObject *self, PyObject *other,
       char *opname, char *ropname, binaryfunc operation)
{
    PyObject *result = NULL;
    PyObject *object;

    if (Proxy_Check(self)) {
        object = Proxy_GET_OBJECT(self);
        result = operation(object, other);
    }
    else if (Proxy_Check(other)) {
        object = Proxy_GET_OBJECT(other);
        result = operation(self, object);
    }
    else {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }
#if 0
    if (result != NULL)
        /* ??? create proxy for result? */
        ;
#endif
    return result;
}

static PyObject *
check2i(ProxyObject *self, PyObject *other,
        char *opname, binaryfunc operation)
{
        PyObject *result = NULL;
        PyObject *object = Proxy_GET_OBJECT(self);

        result = operation(object, other);
        if (result == object) {
            /* If the operation was really carried out inplace,
               don't create a new proxy, but use the old one. */
            Py_INCREF(self);
            Py_DECREF(object);
            result = (PyObject *)self;
        }
#if 0
        else if (result != NULL)
            /* ??? create proxy for result? */
            ;
#endif
        return result;
}

#define UNOP(NAME, CALL) \
        static PyObject *wrap_##NAME(PyObject *self) \
        { return check1((ProxyObject *)self, "__"#NAME"__", CALL); }

#define BINOP(NAME, CALL) \
        static PyObject *wrap_##NAME(PyObject *self, PyObject *other) \
        { return check2(self, other, "__"#NAME"__", "__r"#NAME"__", CALL); }

#define INPLACE(NAME, CALL) \
        static PyObject *wrap_i##NAME(PyObject *self, PyObject *other) \
        { return check2i((ProxyObject *)self, other, "__i"#NAME"__", CALL); }

BINOP(add, PyNumber_Add)
BINOP(sub, PyNumber_Subtract)
BINOP(mul, PyNumber_Multiply)
BINOP(mod, PyNumber_Remainder)
BINOP(divmod, PyNumber_Divmod)

static PyObject *
wrap_pow(PyObject *self, PyObject *other, PyObject *modulus)
{
    PyObject *result = NULL;
    PyObject *object;

    if (Proxy_Check(self)) {
        object = Proxy_GET_OBJECT(self);
        result = PyNumber_Power(object, other, modulus);
    }
    else if (Proxy_Check(other)) {
        object = Proxy_GET_OBJECT(other);
        result = PyNumber_Power(self, object, modulus);
    }
    else if (modulus != NULL && Proxy_Check(modulus)) {
        object = Proxy_GET_OBJECT(modulus);
        result = PyNumber_Power(self, other, modulus);
    }
    else {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }
    return result;
}

BINOP(lshift, PyNumber_Lshift)
BINOP(rshift, PyNumber_Rshift)
BINOP(and, PyNumber_And)
BINOP(xor, PyNumber_Xor)
BINOP(or, PyNumber_Or)

UNOP(neg, PyNumber_Negative)
UNOP(pos, PyNumber_Positive)
UNOP(abs, PyNumber_Absolute)
UNOP(invert, PyNumber_Invert)

UNOP(int, call_int)
UNOP(float, call_float)

INPLACE(add, PyNumber_InPlaceAdd)
INPLACE(sub, PyNumber_InPlaceSubtract)
INPLACE(mul, PyNumber_InPlaceMultiply)
INPLACE(mod, PyNumber_InPlaceRemainder)
INPLACE(pow, call_ipow)
INPLACE(lshift, PyNumber_InPlaceLshift)
INPLACE(rshift, PyNumber_InPlaceRshift)
INPLACE(and, PyNumber_InPlaceAnd)
INPLACE(xor, PyNumber_InPlaceXor)
INPLACE(or, PyNumber_InPlaceOr)

BINOP(floordiv, PyNumber_FloorDivide)
BINOP(truediv, PyNumber_TrueDivide)
INPLACE(floordiv, PyNumber_InPlaceFloorDivide)
INPLACE(truediv, PyNumber_InPlaceTrueDivide)
UNOP(index, call_index)


static int
wrap_nonzero(PyObject *self)
{
    return PyObject_IsTrue(Proxy_GET_OBJECT(self));
}

/*
 *   Sequence methods
 */

static Py_ssize_t
wrap_length(PyObject *self)
{
    return PyObject_Length(Proxy_GET_OBJECT(self));
}

static PyObject *
wrap_slice(PyObject *self, Py_ssize_t start, Py_ssize_t end)
{
    /*
     * Note that we have arrived here through PySequence_GetSlice
     * once already, which on Python 2 adjusted indices. We can't call
     * PySequence_GetSlice again or they will be wrong. So we directly
     * call the slice method the type provides.
     */
    PyObject *obj = Proxy_GET_OBJECT(self);
	return PySequence_GetSlice(obj, start, end);
}

static int
wrap_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
{
    PyObject *obj = Proxy_GET_OBJECT(self);
    if (PyList_Check(obj)) {
        return PyList_SetSlice(obj, i, j, value);
    }
    else {
        return PySequence_SetSlice(obj, i, j, value);
    }
}

static int
wrap_contains(PyObject *self, PyObject *value)
{
    return PySequence_Contains(Proxy_GET_OBJECT(self), value);
}

/*
 *   Mapping methods
 */

static PyObject *
wrap_getitem(PyObject *wrapper, PyObject *v) {
    return PyObject_GetItem(Proxy_GET_OBJECT(wrapper), v);
}

static int
wrap_setitem(PyObject *self, PyObject *key, PyObject *value)
{
    if (value == NULL)
        return PyObject_DelItem(Proxy_GET_OBJECT(self), key);
    else
        return PyObject_SetItem(Proxy_GET_OBJECT(self), key, value);
}

/*
 *   Normal methods
 */

static char
reduce__doc__[] =
"__reduce__()\n"
"Raise an exception; this prevents proxies from being picklable by\n"
"default, even if the underlying object is picklable.";

static PyObject *
wrap_reduce(PyObject *self)
{
    PyObject *pickle_error = NULL;
    PyObject *pickle = PyImport_ImportModule("pickle");

    if (pickle == NULL)
        PyErr_Clear();
    else {
        pickle_error = PyObject_GetAttrString(pickle, "PicklingError");
        if (pickle_error == NULL)
            PyErr_Clear();
    }
    if (pickle_error == NULL) {
        pickle_error = PyExc_RuntimeError;
        Py_INCREF(pickle_error);
    }
    PyErr_SetString(pickle_error,
                    "proxy instances cannot be pickled");
    Py_DECREF(pickle_error);
    return NULL;
}

static PyNumberMethods
wrap_as_number = {
    wrap_add,                               /* nb_add */
    wrap_sub,                               /* nb_subtract */
    wrap_mul,                               /* nb_multiply */
    wrap_mod,                               /* nb_remainder */
    wrap_divmod,                            /* nb_divmod */
    wrap_pow,                               /* nb_power */
    wrap_neg,                               /* nb_negative */
    wrap_pos,                               /* nb_positive */
    wrap_abs,                               /* nb_absolute */
    wrap_nonzero,                           /* nb_nonzero */
    wrap_invert,                            /* nb_invert */
    wrap_lshift,                            /* nb_lshift */
    wrap_rshift,                            /* nb_rshift */
    wrap_and,                               /* nb_and */
    wrap_xor,                               /* nb_xor */
    wrap_or,                                /* nb_or */
    wrap_int,                               /* nb_int */
    0,                                      /* formerly known as nb_long */
    wrap_float,                             /* nb_float */

    /* Added in release 2.0 */
    /* These require the Py_TPFLAGS_HAVE_INPLACEOPS flag */
    wrap_iadd,                              /* nb_inplace_add */
    wrap_isub,                              /* nb_inplace_subtract */
    wrap_imul,                              /* nb_inplace_multiply */
    wrap_imod,                              /* nb_inplace_remainder */
    (ternaryfunc)wrap_ipow,                 /* nb_inplace_power */
    wrap_ilshift,                           /* nb_inplace_lshift */
    wrap_irshift,                           /* nb_inplace_rshift */
    wrap_iand,                              /* nb_inplace_and */
    wrap_ixor,                              /* nb_inplace_xor */
    wrap_ior,                               /* nb_inplace_or */

    /* Added in release 2.2 */
    /* These require the Py_TPFLAGS_HAVE_CLASS flag */
    wrap_floordiv,                          /* nb_floor_divide */
    wrap_truediv,                           /* nb_true_divide */
    wrap_ifloordiv,                         /* nb_inplace_floor_divide */
    wrap_itruediv,                          /* nb_inplace_true_divide */
    wrap_index,                             /* nb_index */
};

static PySequenceMethods
wrap_as_sequence = {
    wrap_length,                            /* sq_length */
    0,                                      /* sq_concat */
    0,                                      /* sq_repeat */
    0,                                      /* sq_item */
    wrap_slice,                             /* sq_slice */
    0,                                      /* sq_ass_item */
    wrap_ass_slice,                         /* sq_ass_slice */
    wrap_contains,                          /* sq_contains */
};

static PyMappingMethods
wrap_as_mapping = {
    wrap_length,                            /* mp_length */
    wrap_getitem,                           /* mp_subscript */
    wrap_setitem,                           /* mp_ass_subscript */
};

static PyMethodDef
wrap_methods[] = {
    {"__reduce__", (PyCFunction)wrap_reduce, METH_NOARGS, reduce__doc__},
    {NULL, NULL},
};

/*
 * Note that the numeric methods are not supported.  This is primarily
 * because of the way coercion-less operations are performed with
 * new-style numbers; since we can't tell which side of the operation
 * is 'self', we can't ensure we'd unwrap the right thing to perform
 * the actual operation.  We also can't afford to just unwrap both
 * sides the way weakrefs do, since we don't know what semantics will
 * be associated with the wrapper itself.
 */


static PyTypeObject
ProxyType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "zope.proxy.ProxyBase",
    sizeof(ProxyObject),
    0,
    wrap_dealloc,                           /* tp_dealloc */
    0,                                      /* reserved 3.0--3.7; tp_vectorcall_offset 3.8+ */
    0,                                      /* tp_getattr */
    0,                                      /* tp_setattr */
    0,                                      /* tp_reserved */
    wrap_repr,                              /* tp_repr */
    &wrap_as_number,                        /* tp_as_number */
    &wrap_as_sequence,                      /* tp_as_sequence */
    &wrap_as_mapping,                       /* tp_as_mapping */
    wrap_hash,                              /* tp_hash */
    wrap_call,                              /* tp_call */
    wrap_str,                               /* tp_str */
    wrap_getattro,                          /* tp_getattro */
    wrap_setattro,                          /* tp_setattro */
    0,                                      /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT |
    Py_TPFLAGS_HAVE_GC |
    Py_TPFLAGS_BASETYPE,                    /* tp_flags */
    0,                                      /* tp_doc */
    wrap_traverse,                          /* tp_traverse */
    wrap_clear,                             /* tp_clear */
    wrap_richcompare,                       /* tp_richcompare */
    0,                                      /* tp_weaklistoffset */
    wrap_iter,                              /* tp_iter */
    wrap_iternext,                          /* tp_iternext */
    wrap_methods,                           /* tp_methods */
    0,                                      /* tp_members */
    0,                                      /* tp_getset */
    0,                                      /* tp_base */
    0,                                      /* tp_dict */
    0,                                      /* tp_descr_get */
    0,                                      /* tp_descr_set */
    0,                                      /* tp_dictoffset */
    wrap_init,                              /* tp_init */
    0,                                      /* tp_alloc */
    wrap_new,                               /* tp_new */
    0, /*PyObject_GC_Del,*/                 /* tp_free */
};

static PyObject *
create_proxy(PyObject *object)
{
    PyObject *result = NULL;
    PyObject *args;

    args = PyTuple_New(1);
    if (args != NULL) {
        Py_INCREF(object);
        PyTuple_SET_ITEM(args, 0, object);
        result = PyObject_CallObject((PyObject *)&ProxyType, args);
        Py_DECREF(args);
    }
    return result;
}

static int
api_check(PyObject *obj)
{
    return obj ? Proxy_Check(obj) : 0;
}

static PyObject *
api_create(PyObject *object)
{
    if (object == NULL) {
        PyErr_SetString(PyExc_ValueError,
                        "cannot create proxy around NULL");
        return NULL;
    }
    return create_proxy(object);
}

static PyObject *
api_getobject(PyObject *proxy)
{
    if (proxy == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "cannot pass NULL to ProxyAPI.getobject()");
        return NULL;
    }
    if (Proxy_Check(proxy))
        return Proxy_GET_OBJECT(proxy);
    else {
        PyErr_Format(PyExc_TypeError, "expected proxy object, got %s",
                     proxy->ob_type->tp_name);
        return NULL;
    }
}

static ProxyInterface
wrapper_capi = {
    &ProxyType,
    api_check,
    api_create,
    api_getobject,
};

static PyObject *api_object = NULL;


static char
getobject__doc__[] =
"getProxiedObject(proxy) --> object\n"
"\n"
"Get the underlying object for proxy, or the object itself, if it is\n"
"not a proxy.";

static PyObject *
wrapper_getobject(PyObject *unused, PyObject *obj)
{
  if (Proxy_Check(obj))
    obj = Proxy_GET_OBJECT(obj);

  if (obj == NULL)
    obj = Py_None;

  Py_INCREF(obj);
  return obj;
}

static char
setobject__doc__[] =
"setProxiedObject(proxy, object) --> object\n"
"\n"
"Set the underlying object for proxy, returning the old proxied object.\n"
"Raises TypeError if proxy is not a proxy.\n";

static PyObject *
wrapper_setobject(PyObject *unused, PyObject *args)
{
  PyObject *proxy;
  PyObject *object;
  PyObject *result = NULL;
  if (PyArg_ParseTuple(args, "O!O:setProxiedObject",
                       &ProxyType, &proxy, &object)) {
    result = Proxy_GET_OBJECT(proxy);
    Py_INCREF(object);
    ((ProxyObject *) proxy)->proxy_object = object;
  }
  return result;
}

static char
isProxy__doc__[] =
"Check whether the given object is a proxy\n"
"\n"
"If proxytype is not None, checkes whether the object is\n"
"proxied by the given proxytype.\n"
;

static PyObject *
wrapper_isProxy(PyObject *unused, PyObject *args)
{
  PyObject *obj, *result;
  PyTypeObject *proxytype=&ProxyType;

  if (! PyArg_ParseTuple(args, "O|O!:isProxy",
                         &obj, &PyType_Type, &proxytype)
      )
    return NULL;

  while (obj && Proxy_Check(obj))
  {
    if (PyObject_TypeCheck(obj, proxytype))
      {
        result = Py_True;
        Py_INCREF(result);
        return result;
      }
    obj = Proxy_GET_OBJECT(obj);
  }
  result = Py_False;
  Py_INCREF(result);
  return result;
}

static char
removeAllProxies__doc__[] =
"removeAllProxies(proxy) --> object\n"
"\n"
"Get the proxied object with no proxies\n"
"\n"
"If obj is not a proxied object, return obj.\n"
"\n"
"The returned object has no proxies.\n"
;

static PyObject *
wrapper_removeAllProxies(PyObject *unused, PyObject *obj)
{
  while (obj && Proxy_Check(obj))
    obj = Proxy_GET_OBJECT(obj);

  if (obj == NULL)
    obj = Py_None;

  Py_INCREF(obj);
  return obj;
}

static char
sameProxiedObjects__doc__[] =
"Check whether two objects are the same or proxies of the same object";

static PyObject *
wrapper_sameProxiedObjects(PyObject *unused, PyObject *args)
{
  PyObject *ob1, *ob2;

  if (! PyArg_ParseTuple(args, "OO:sameProxiedObjects", &ob1, &ob2))
    return NULL;

  while (ob1 && Proxy_Check(ob1))
    ob1 = Proxy_GET_OBJECT(ob1);

  while (ob2 && Proxy_Check(ob2))
    ob2 = Proxy_GET_OBJECT(ob2);

  if (ob1 == ob2)
    ob1 = Py_True;
  else
    ob1 = Py_False;

  Py_INCREF(ob1);
  return ob1;
}


static char
queryProxy__doc__[] =
"Look for a proxy of the given type around the object\n"
"\n"
"If no such proxy can be found, return the default.\n"
;

static PyObject *
wrapper_queryProxy(PyObject *unused, PyObject *args)
{
  PyObject *obj, *result=Py_None;
  PyTypeObject *proxytype=&ProxyType;

  if (! PyArg_ParseTuple(args, "O|O!O:queryProxy",
                         &obj, &PyType_Type, &proxytype, &result)
      )
    return NULL;

  while (obj && Proxy_Check(obj))
  {
    if (PyObject_TypeCheck(obj, proxytype))
      {
        Py_INCREF(obj);
        return obj;
      }
    obj = Proxy_GET_OBJECT(obj);
  }

  Py_INCREF(result);
  return result;
}

static char
queryInnerProxy__doc__[] =
"Look for the inner-most proxy of the given type around the object\n"
"\n"
"If no such proxy can be found, return the default.\n"
"\n"
"If there is such a proxy, return the inner-most one.\n"
;

static PyObject *
wrapper_queryInnerProxy(PyObject *unused, PyObject *args)
{
  PyObject *obj, *result=Py_None;
  PyTypeObject *proxytype=&ProxyType;

  if (! PyArg_ParseTuple(args, "O|O!O:queryInnerProxy",
                         &obj, &PyType_Type, &proxytype, &result)
      )
    return NULL;

  while (obj && Proxy_Check(obj))
  {
    if (PyObject_TypeCheck(obj, proxytype))
      result = obj;
    obj = Proxy_GET_OBJECT(obj);
  }

  Py_INCREF(result);
  return result;
}

/* Module initialization */

static char
module___doc__[] =
"Association between an object, a context object, and a dictionary.\n\
\n\
The context object and dictionary give additional context information\n\
associated with a reference to the basic object.  The wrapper objects\n\
act as proxies for the original object.";


static PyMethodDef
module_functions[] = {
    {"getProxiedObject", wrapper_getobject, METH_O, getobject__doc__},
    {"setProxiedObject", wrapper_setobject, METH_VARARGS, setobject__doc__},
    {"isProxy", wrapper_isProxy, METH_VARARGS, isProxy__doc__},
    {"sameProxiedObjects", wrapper_sameProxiedObjects, METH_VARARGS,
     sameProxiedObjects__doc__},
    {"queryProxy", wrapper_queryProxy, METH_VARARGS, queryProxy__doc__},
    {"queryInnerProxy", wrapper_queryInnerProxy, METH_VARARGS,
     queryInnerProxy__doc__},
    {"removeAllProxies", wrapper_removeAllProxies, METH_O,
     removeAllProxies__doc__},
    {NULL}
};

MOD_INIT(_zope_proxy_proxy)
{
    PyObject *m;

    MOD_DEF(m, "_zope_proxy_proxy", module___doc__, module_functions)

    if (m == NULL)
        return MOD_ERROR_VAL;

    if (empty_tuple == NULL)
        empty_tuple = PyTuple_New(0);

    ProxyType.tp_free = PyObject_GC_Del;

    if (PyType_Ready(&ProxyType) < 0)
        return MOD_ERROR_VAL;

    Py_INCREF(&ProxyType);
    PyModule_AddObject(m, "ProxyBase", (PyObject *)&ProxyType);

    if (api_object == NULL) {
        api_object = PyCapsule_New(&wrapper_capi, NULL, NULL);
        if (api_object == NULL)
        return MOD_ERROR_VAL;
    }
    Py_INCREF(api_object);
    PyModule_AddObject(m, "_CAPI", api_object);

    return MOD_SUCCESS_VAL(m);

}