- Notifications
You must be signed in to change notification settings - Fork 31.8k
/
Copy pathobject.c
2518 lines (2238 loc) · 68.6 KB
/
object.c
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
/* Generic object operations; and implementation of None (NoObject) */
#include"Python.h"
#include"frameobject.h"
#ifdef__cplusplus
extern"C" {
#endif
#ifdefPy_REF_DEBUG
Py_ssize_t_Py_RefTotal;
Py_ssize_t
_Py_GetRefTotal(void)
{
PyObject*o;
Py_ssize_ttotal=_Py_RefTotal;
/* ignore the references to the dummy object of the dicts and sets
because they are not reliable and not useful (now that the
hash table code is well-tested) */
o=_PyDict_Dummy();
if (o!=NULL)
total-=o->ob_refcnt;
o=_PySet_Dummy();
if (o!=NULL)
total-=o->ob_refcnt;
returntotal;
}
#endif/* Py_REF_DEBUG */
intPy_DivisionWarningFlag;
intPy_Py3kWarningFlag;
/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
These are used by the individual routines for object creation.
Do not call them otherwise, they do not initialize the object! */
#ifdefPy_TRACE_REFS
/* Head of circular doubly-linked list of all objects. These are linked
* together via the _ob_prev and _ob_next members of a PyObject, which
* exist only in a Py_TRACE_REFS build.
*/
staticPyObjectrefchain= {&refchain, &refchain};
/* Insert op at the front of the list of all objects. If force is true,
* op is added even if _ob_prev and _ob_next are non-NULL already. If
* force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
* force should be true if and only if op points to freshly allocated,
* uninitialized memory, or you've unlinked op from the list and are
* relinking it into the front.
* Note that objects are normally added to the list via _Py_NewReference,
* which is called by PyObject_Init. Not all objects are initialized that
* way, though; exceptions include statically allocated type objects, and
* statically allocated singletons (like Py_True and Py_None).
*/
void
_Py_AddToAllObjects(PyObject*op, intforce)
{
#ifdefPy_DEBUG
if (!force) {
/* If it's initialized memory, op must be in or out of
* the list unambiguously.
*/
assert((op->_ob_prev==NULL) == (op->_ob_next==NULL));
}
#endif
if (force||op->_ob_prev==NULL) {
op->_ob_next=refchain._ob_next;
op->_ob_prev=&refchain;
refchain._ob_next->_ob_prev=op;
refchain._ob_next=op;
}
}
#endif/* Py_TRACE_REFS */
#ifdefCOUNT_ALLOCS
staticPyTypeObject*type_list;
/* All types are added to type_list, at least when
they get one object created. That makes them
immortal, which unfortunately contributes to
garbage itself. If unlist_types_without_objects
is set, they will be removed from the type_list
once the last object is deallocated. */
staticintunlist_types_without_objects;
externPy_ssize_ttuple_zero_allocs, fast_tuple_allocs;
externPy_ssize_tquick_int_allocs, quick_neg_int_allocs;
externPy_ssize_tnull_strings, one_strings;
void
dump_counts(FILE*f)
{
PyTypeObject*tp;
for (tp=type_list; tp; tp=tp->tp_next)
fprintf(f, "%s alloc'd: %"PY_FORMAT_SIZE_T"d, "
"freed: %"PY_FORMAT_SIZE_T"d, "
"max in use: %"PY_FORMAT_SIZE_T"d\n",
tp->tp_name, tp->tp_allocs, tp->tp_frees,
tp->tp_maxalloc);
fprintf(f, "fast tuple allocs: %"PY_FORMAT_SIZE_T"d, "
"empty: %"PY_FORMAT_SIZE_T"d\n",
fast_tuple_allocs, tuple_zero_allocs);
fprintf(f, "fast int allocs: pos: %"PY_FORMAT_SIZE_T"d, "
"neg: %"PY_FORMAT_SIZE_T"d\n",
quick_int_allocs, quick_neg_int_allocs);
fprintf(f, "null strings: %"PY_FORMAT_SIZE_T"d, "
"1-strings: %"PY_FORMAT_SIZE_T"d\n",
null_strings, one_strings);
}
PyObject*
get_counts(void)
{
PyTypeObject*tp;
PyObject*result;
PyObject*v;
result=PyList_New(0);
if (result==NULL)
returnNULL;
for (tp=type_list; tp; tp=tp->tp_next) {
v=Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
tp->tp_frees, tp->tp_maxalloc);
if (v==NULL) {
Py_DECREF(result);
returnNULL;
}
if (PyList_Append(result, v) <0) {
Py_DECREF(v);
Py_DECREF(result);
returnNULL;
}
Py_DECREF(v);
}
returnresult;
}
void
inc_count(PyTypeObject*tp)
{
if (tp->tp_next==NULL&&tp->tp_prev==NULL) {
/* first time; insert in linked list */
if (tp->tp_next!=NULL) /* sanity check */
Py_FatalError("XXX inc_count sanity check");
if (type_list)
type_list->tp_prev=tp;
tp->tp_next=type_list;
/* Note that as of Python 2.2, heap-allocated type objects
* can go away, but this code requires that they stay alive
* until program exit. That's why we're careful with
* refcounts here. type_list gets a new reference to tp,
* while ownership of the reference type_list used to hold
* (if any) was transferred to tp->tp_next in the line above.
* tp is thus effectively immortal after this.
*/
Py_INCREF(tp);
type_list=tp;
#ifdefPy_TRACE_REFS
/* Also insert in the doubly-linked list of all objects,
* if not already there.
*/
_Py_AddToAllObjects((PyObject*)tp, 0);
#endif
}
tp->tp_allocs++;
if (tp->tp_allocs-tp->tp_frees>tp->tp_maxalloc)
tp->tp_maxalloc=tp->tp_allocs-tp->tp_frees;
}
voiddec_count(PyTypeObject*tp)
{
tp->tp_frees++;
if (unlist_types_without_objects&&
tp->tp_allocs==tp->tp_frees) {
/* unlink the type from type_list */
if (tp->tp_prev)
tp->tp_prev->tp_next=tp->tp_next;
else
type_list=tp->tp_next;
if (tp->tp_next)
tp->tp_next->tp_prev=tp->tp_prev;
tp->tp_next=tp->tp_prev=NULL;
Py_DECREF(tp);
}
}
#endif
#ifdefPy_REF_DEBUG
/* Log a fatal error; doesn't return. */
void
_Py_NegativeRefcount(constchar*fname, intlineno, PyObject*op)
{
charbuf[300];
PyOS_snprintf(buf, sizeof(buf),
"%s:%i object at %p has negative ref count "
"%"PY_FORMAT_SIZE_T"d",
fname, lineno, op, op->ob_refcnt);
Py_FatalError(buf);
}
#endif/* Py_REF_DEBUG */
void
Py_IncRef(PyObject*o)
{
Py_XINCREF(o);
}
void
Py_DecRef(PyObject*o)
{
Py_XDECREF(o);
}
PyObject*
PyObject_Init(PyObject*op, PyTypeObject*tp)
{
if (op==NULL)
returnPyErr_NoMemory();
/* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Py_TYPE(op) =tp;
_Py_NewReference(op);
returnop;
}
PyVarObject*
PyObject_InitVar(PyVarObject*op, PyTypeObject*tp, Py_ssize_tsize)
{
if (op==NULL)
return (PyVarObject*) PyErr_NoMemory();
/* Any changes should be reflected in PyObject_INIT_VAR */
op->ob_size=size;
Py_TYPE(op) =tp;
_Py_NewReference((PyObject*)op);
returnop;
}
PyObject*
_PyObject_New(PyTypeObject*tp)
{
PyObject*op;
op= (PyObject*) PyObject_MALLOC(_PyObject_SIZE(tp));
if (op==NULL)
returnPyErr_NoMemory();
returnPyObject_INIT(op, tp);
}
PyVarObject*
_PyObject_NewVar(PyTypeObject*tp, Py_ssize_tnitems)
{
PyVarObject*op;
constsize_tsize=_PyObject_VAR_SIZE(tp, nitems);
op= (PyVarObject*) PyObject_MALLOC(size);
if (op==NULL)
return (PyVarObject*)PyErr_NoMemory();
returnPyObject_INIT_VAR(op, tp, nitems);
}
/* for binary compatibility with 2.2 */
#undef _PyObject_Del
void
_PyObject_Del(PyObject*op)
{
PyObject_FREE(op);
}
/* Implementation of PyObject_Print with recursion checking */
staticint
internal_print(PyObject*op, FILE*fp, intflags, intnesting)
{
intret=0;
if (nesting>10) {
PyErr_SetString(PyExc_RuntimeError, "print recursion");
return-1;
}
if (PyErr_CheckSignals())
return-1;
#ifdefUSE_STACKCHECK
if (PyOS_CheckStack()) {
PyErr_SetString(PyExc_MemoryError, "stack overflow");
return-1;
}
#endif
clearerr(fp); /* Clear any previous error condition */
if (op==NULL) {
Py_BEGIN_ALLOW_THREADS
fprintf(fp, "<nil>");
Py_END_ALLOW_THREADS
}
else {
if (op->ob_refcnt <= 0)
/* XXX(twouters) cast refcount to long until %zd is
universally available */
Py_BEGIN_ALLOW_THREADS
fprintf(fp, "<refcnt %ld at %p>",
(long)op->ob_refcnt, op);
Py_END_ALLOW_THREADS
elseif (Py_TYPE(op)->tp_print== NULL) {
PyObject*s;
if (flags&Py_PRINT_RAW)
s=PyObject_Str(op);
else
s=PyObject_Repr(op);
if (s==NULL)
ret=-1;
else {
ret=internal_print(s, fp, Py_PRINT_RAW,
nesting+1);
}
Py_XDECREF(s);
}
else
ret= (*Py_TYPE(op)->tp_print)(op, fp, flags);
}
if (ret==0) {
if (ferror(fp)) {
PyErr_SetFromErrno(PyExc_IOError);
clearerr(fp);
ret=-1;
}
}
returnret;
}
int
PyObject_Print(PyObject*op, FILE*fp, intflags)
{
returninternal_print(op, fp, flags, 0);
}
/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
void_PyObject_Dump(PyObject*op)
{
if (op==NULL)
fprintf(stderr, "NULL\n");
else {
#ifdefWITH_THREAD
PyGILState_STATEgil;
#endif
fprintf(stderr, "object : ");
#ifdefWITH_THREAD
gil=PyGILState_Ensure();
#endif
(void)PyObject_Print(op, stderr, 0);
#ifdefWITH_THREAD
PyGILState_Release(gil);
#endif
/* XXX(twouters) cast refcount to long until %zd is
universally available */
fprintf(stderr, "\n"
"type : %s\n"
"refcount: %ld\n"
"address : %p\n",
Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
(long)op->ob_refcnt,
op);
}
}
PyObject*
PyObject_Repr(PyObject*v)
{
if (PyErr_CheckSignals())
returnNULL;
#ifdefUSE_STACKCHECK
if (PyOS_CheckStack()) {
PyErr_SetString(PyExc_MemoryError, "stack overflow");
returnNULL;
}
#endif
if (v==NULL)
returnPyString_FromString("<NULL>");
elseif (Py_TYPE(v)->tp_repr==NULL)
returnPyString_FromFormat("<%s object at %p>",
Py_TYPE(v)->tp_name, v);
else {
PyObject*res;
/* It is possible for a type to have a tp_repr representation that
loops infinitely. */
if (Py_EnterRecursiveCall(" while getting the repr of an object"))
returnNULL;
res= (*Py_TYPE(v)->tp_repr)(v);
Py_LeaveRecursiveCall();
if (res==NULL)
returnNULL;
#ifdefPy_USING_UNICODE
if (PyUnicode_Check(res)) {
PyObject*str;
str=PyUnicode_AsEncodedString(res, NULL, NULL);
Py_DECREF(res);
if (str)
res=str;
else
returnNULL;
}
#endif
if (!PyString_Check(res)) {
PyErr_Format(PyExc_TypeError,
"__repr__ returned non-string (type %.200s)",
Py_TYPE(res)->tp_name);
Py_DECREF(res);
returnNULL;
}
returnres;
}
}
PyObject*
_PyObject_Str(PyObject*v)
{
PyObject*res;
inttype_ok;
if (v==NULL)
returnPyString_FromString("<NULL>");
if (PyString_CheckExact(v)) {
Py_INCREF(v);
returnv;
}
#ifdefPy_USING_UNICODE
if (PyUnicode_CheckExact(v)) {
Py_INCREF(v);
returnv;
}
#endif
if (Py_TYPE(v)->tp_str==NULL)
returnPyObject_Repr(v);
/* It is possible for a type to have a tp_str representation that loops
infinitely. */
if (Py_EnterRecursiveCall(" while getting the str of an object"))
returnNULL;
res= (*Py_TYPE(v)->tp_str)(v);
Py_LeaveRecursiveCall();
if (res==NULL)
returnNULL;
type_ok=PyString_Check(res);
#ifdefPy_USING_UNICODE
type_ok=type_ok||PyUnicode_Check(res);
#endif
if (!type_ok) {
PyErr_Format(PyExc_TypeError,
"__str__ returned non-string (type %.200s)",
Py_TYPE(res)->tp_name);
Py_DECREF(res);
returnNULL;
}
returnres;
}
PyObject*
PyObject_Str(PyObject*v)
{
PyObject*res=_PyObject_Str(v);
if (res==NULL)
returnNULL;
#ifdefPy_USING_UNICODE
if (PyUnicode_Check(res)) {
PyObject*str;
str=PyUnicode_AsEncodedString(res, NULL, NULL);
Py_DECREF(res);
if (str)
res=str;
else
returnNULL;
}
#endif
assert(PyString_Check(res));
returnres;
}
#ifdefPy_USING_UNICODE
PyObject*
PyObject_Unicode(PyObject*v)
{
PyObject*res;
PyObject*func;
PyObject*str;
intunicode_method_found=0;
staticPyObject*unicodestr=NULL;
if (v==NULL) {
res=PyString_FromString("<NULL>");
if (res==NULL)
returnNULL;
str=PyUnicode_FromEncodedObject(res, NULL, "strict");
Py_DECREF(res);
returnstr;
} elseif (PyUnicode_CheckExact(v)) {
Py_INCREF(v);
returnv;
}
if (PyInstance_Check(v)) {
/* We're an instance of a classic class */
/* Try __unicode__ from the instance -- alas we have no type */
if (!unicodestr) {
unicodestr=PyString_InternFromString("__unicode__");
if (!unicodestr)
returnNULL;
}
func=PyObject_GetAttr(v, unicodestr);
if (func!=NULL) {
unicode_method_found=1;
res=PyObject_CallFunctionObjArgs(func, NULL);
Py_DECREF(func);
}
else {
PyErr_Clear();
}
}
else {
/* Not a classic class instance, try __unicode__. */
func=_PyObject_LookupSpecial(v, "__unicode__", &unicodestr);
if (func!=NULL) {
unicode_method_found=1;
res=PyObject_CallFunctionObjArgs(func, NULL);
Py_DECREF(func);
}
elseif (PyErr_Occurred())
returnNULL;
}
/* Didn't find __unicode__ */
if (!unicode_method_found) {
if (PyUnicode_Check(v)) {
/* For a Unicode subtype that's didn't overwrite __unicode__,
return a true Unicode object with the same data. */
returnPyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
PyUnicode_GET_SIZE(v));
}
if (PyString_CheckExact(v)) {
Py_INCREF(v);
res=v;
}
else {
if (Py_TYPE(v)->tp_str!=NULL)
res= (*Py_TYPE(v)->tp_str)(v);
else
res=PyObject_Repr(v);
}
}
if (res==NULL)
returnNULL;
if (!PyUnicode_Check(res)) {
str=PyUnicode_FromEncodedObject(res, NULL, "strict");
Py_DECREF(res);
res=str;
}
returnres;
}
#endif
/* Helper to warn about deprecated tp_compare return values. Return:
-2 for an exception;
-1 if v < w;
0 if v == w;
1 if v > w.
(This function cannot return 2.)
*/
staticint
adjust_tp_compare(intc)
{
if (PyErr_Occurred()) {
if (c!=-1&&c!=-2) {
PyObject*t, *v, *tb;
PyErr_Fetch(&t, &v, &tb);
if (PyErr_Warn(PyExc_RuntimeWarning,
"tp_compare didn't return -1 or -2 "
"for exception") <0) {
Py_XDECREF(t);
Py_XDECREF(v);
Py_XDECREF(tb);
}
else
PyErr_Restore(t, v, tb);
}
return-2;
}
elseif (c<-1||c>1) {
if (PyErr_Warn(PyExc_RuntimeWarning,
"tp_compare didn't return -1, 0 or 1") <0)
return-2;
else
returnc<-1 ? -1 : 1;
}
else {
assert(c >= -1&&c <= 1);
returnc;
}
}
/* Macro to get the tp_richcompare field of a type if defined */
#defineRICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
? (t)->tp_richcompare : NULL)
/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
int_Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
/* Try a genuine rich comparison, returning an object. Return:
NULL for exception;
NotImplemented if this particular rich comparison is not implemented or
undefined;
some object not equal to NotImplemented if it is implemented
(this latter object may not be a Boolean).
*/
staticPyObject*
try_rich_compare(PyObject*v, PyObject*w, intop)
{
richcmpfuncf;
PyObject*res;
if (v->ob_type!=w->ob_type&&
PyType_IsSubtype(w->ob_type, v->ob_type) &&
(f=RICHCOMPARE(w->ob_type)) !=NULL) {
res= (*f)(w, v, _Py_SwappedOp[op]);
if (res!=Py_NotImplemented)
returnres;
Py_DECREF(res);
}
if ((f=RICHCOMPARE(v->ob_type)) !=NULL) {
res= (*f)(v, w, op);
if (res!=Py_NotImplemented)
returnres;
Py_DECREF(res);
}
if ((f=RICHCOMPARE(w->ob_type)) !=NULL) {
return (*f)(w, v, _Py_SwappedOp[op]);
}
res=Py_NotImplemented;
Py_INCREF(res);
returnres;
}
/* Try a genuine rich comparison, returning an int. Return:
-1 for exception (including the case where try_rich_compare() returns an
object that's not a Boolean);
0 if the outcome is false;
1 if the outcome is true;
2 if this particular rich comparison is not implemented or undefined.
*/
staticint
try_rich_compare_bool(PyObject*v, PyObject*w, intop)
{
PyObject*res;
intok;
if (RICHCOMPARE(v->ob_type) ==NULL&&RICHCOMPARE(w->ob_type) ==NULL)
return2; /* Shortcut, avoid INCREF+DECREF */
res=try_rich_compare(v, w, op);
if (res==NULL)
return-1;
if (res==Py_NotImplemented) {
Py_DECREF(res);
return2;
}
ok=PyObject_IsTrue(res);
Py_DECREF(res);
returnok;
}
/* Try rich comparisons to determine a 3-way comparison. Return:
-2 for an exception;
-1 if v < w;
0 if v == w;
1 if v > w;
2 if this particular rich comparison is not implemented or undefined.
*/
staticint
try_rich_to_3way_compare(PyObject*v, PyObject*w)
{
staticstruct { intop; intoutcome; } tries[3] = {
/* Try this operator, and if it is true, use this outcome: */
{Py_EQ, 0},
{Py_LT, -1},
{Py_GT, 1},
};
inti;
if (RICHCOMPARE(v->ob_type) ==NULL&&RICHCOMPARE(w->ob_type) ==NULL)
return2; /* Shortcut */
for (i=0; i<3; i++) {
switch (try_rich_compare_bool(v, w, tries[i].op)) {
case-1:
return-2;
case1:
returntries[i].outcome;
}
}
return2;
}
/* Try a 3-way comparison, returning an int. Return:
-2 for an exception;
-1 if v < w;
0 if v == w;
1 if v > w;
2 if this particular 3-way comparison is not implemented or undefined.
*/
staticint
try_3way_compare(PyObject*v, PyObject*w)
{
intc;
cmpfuncf;
/* Comparisons involving instances are given to instance_compare,
which has the same return conventions as this function. */
f=v->ob_type->tp_compare;
if (PyInstance_Check(v))
return (*f)(v, w);
if (PyInstance_Check(w))
return (*w->ob_type->tp_compare)(v, w);
/* If both have the same (non-NULL) tp_compare, use it. */
if (f!=NULL&&f==w->ob_type->tp_compare) {
c= (*f)(v, w);
returnadjust_tp_compare(c);
}
/* If either tp_compare is _PyObject_SlotCompare, that's safe. */
if (f==_PyObject_SlotCompare||
w->ob_type->tp_compare==_PyObject_SlotCompare)
return_PyObject_SlotCompare(v, w);
/* If we're here, v and w,
a) are not instances;
b) have different types or a type without tp_compare; and
c) don't have a user-defined tp_compare.
tp_compare implementations in C assume that both arguments
have their type, so we give up if the coercion fails or if
it yields types which are still incompatible (which can
happen with a user-defined nb_coerce).
*/
c=PyNumber_CoerceEx(&v, &w);
if (c<0)
return-2;
if (c>0)
return2;
f=v->ob_type->tp_compare;
if (f!=NULL&&f==w->ob_type->tp_compare) {
c= (*f)(v, w);
Py_DECREF(v);
Py_DECREF(w);
returnadjust_tp_compare(c);
}
/* No comparison defined */
Py_DECREF(v);
Py_DECREF(w);
return2;
}
/* Final fallback 3-way comparison, returning an int. Return:
-2 if an error occurred;
-1 if v < w;
0 if v == w;
1 if v > w.
*/
staticint
default_3way_compare(PyObject*v, PyObject*w)
{
intc;
constchar*vname, *wname;
if (v->ob_type==w->ob_type) {
/* When comparing these pointers, they must be cast to
* integer types (i.e. Py_uintptr_t, our spelling of C9X's
* uintptr_t). ANSI specifies that pointer compares other
* than == and != to non-related structures are undefined.
*/
Py_uintptr_tvv= (Py_uintptr_t)v;
Py_uintptr_tww= (Py_uintptr_t)w;
return (vv<ww) ? -1 : (vv>ww) ? 1 : 0;
}
/* None is smaller than anything */
if (v==Py_None)
return-1;
if (w==Py_None)
return1;
/* different type: compare type names; numbers are smaller */
if (PyNumber_Check(v))
vname="";
else
vname=v->ob_type->tp_name;
if (PyNumber_Check(w))
wname="";
else
wname=w->ob_type->tp_name;
c=strcmp(vname, wname);
if (c<0)
return-1;
if (c>0)
return1;
/* Same type name, or (more likely) incomparable numeric types */
return ((Py_uintptr_t)(v->ob_type) < (
Py_uintptr_t)(w->ob_type)) ? -1 : 1;
}
/* Do a 3-way comparison, by hook or by crook. Return:
-2 for an exception (but see below);
-1 if v < w;
0 if v == w;
1 if v > w;
BUT: if the object implements a tp_compare function, it returns
whatever this function returns (whether with an exception or not).
*/
staticint
do_cmp(PyObject*v, PyObject*w)
{
intc;
cmpfuncf;
if (v->ob_type==w->ob_type
&& (f=v->ob_type->tp_compare) !=NULL) {
c= (*f)(v, w);
if (PyInstance_Check(v)) {
/* Instance tp_compare has a different signature.
But if it returns undefined we fall through. */
if (c!=2)
returnc;
/* Else fall through to try_rich_to_3way_compare() */
}
else
returnadjust_tp_compare(c);
}
/* We only get here if one of the following is true:
a) v and w have different types
b) v and w have the same type, which doesn't have tp_compare
c) v and w are instances, and either __cmp__ is not defined or
__cmp__ returns NotImplemented
*/
c=try_rich_to_3way_compare(v, w);
if (c<2)
returnc;
c=try_3way_compare(v, w);
if (c<2)
returnc;
returndefault_3way_compare(v, w);
}
/* Compare v to w. Return
-1 if v < w or exception (PyErr_Occurred() true in latter case).
0 if v == w.
1 if v > w.
XXX The docs (C API manual) say the return value is undefined in case
XXX of error.
*/
int
PyObject_Compare(PyObject*v, PyObject*w)
{
intresult;
if (v==NULL||w==NULL) {
PyErr_BadInternalCall();
return-1;
}
if (v==w)
return0;
if (Py_EnterRecursiveCall(" in cmp"))
return-1;
result=do_cmp(v, w);
Py_LeaveRecursiveCall();
returnresult<0 ? -1 : result;
}
/* Return (new reference to) Py_True or Py_False. */
staticPyObject*
convert_3way_to_object(intop, intc)
{
PyObject*result;
switch (op) {
casePy_LT: c=c<0; break;
casePy_LE: c=c <= 0; break;
casePy_EQ: c=c==0; break;
casePy_NE: c=c!=0; break;
casePy_GT: c=c>0; break;
casePy_GE: c=c >= 0; break;
}
result=c ? Py_True : Py_False;
Py_INCREF(result);
returnresult;
}
/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
Return
NULL if error
Py_True if v op w
Py_False if not (v op w)
*/
staticPyObject*
try_3way_to_rich_compare(PyObject*v, PyObject*w, intop)
{
intc;
c=try_3way_compare(v, w);
if (c >= 2) {
/* Py3K warning if types are not equal and comparison isn't == or != */
if (Py_Py3kWarningFlag&&
v->ob_type!=w->ob_type&&op!=Py_EQ&&op!=Py_NE&&
PyErr_WarnEx(PyExc_DeprecationWarning,
"comparing unequal types not supported "
"in 3.x", 1) <0) {
returnNULL;
}
c=default_3way_compare(v, w);
}
if (c <= -2)
returnNULL;
returnconvert_3way_to_object(op, c);
}
/* Do rich comparison on v and w. Return
NULL if error
Else a new reference to an object other than Py_NotImplemented, usually(?):
Py_True if v op w
Py_False if not (v op w)
*/
staticPyObject*
do_richcmp(PyObject*v, PyObject*w, intop)
{
PyObject*res;
res=try_rich_compare(v, w, op);
if (res!=Py_NotImplemented)
returnres;
Py_DECREF(res);
returntry_3way_to_rich_compare(v, w, op);
}
/* Return:
NULL for exception;
some object not equal to NotImplemented if it is implemented
(this latter object may not be a Boolean).
*/
PyObject*
PyObject_RichCompare(PyObject*v, PyObject*w, intop)
{
PyObject*res;
assert(Py_LT <= op&&op <= Py_GE);
if (Py_EnterRecursiveCall(" in cmp"))
returnNULL;
/* If the types are equal, and not old-style instances, try to
get out cheap (don't bother with coercions etc.). */
if (v->ob_type==w->ob_type&& !PyInstance_Check(v)) {
cmpfuncfcmp;
richcmpfuncfrich=RICHCOMPARE(v->ob_type);
/* If the type has richcmp, try it first. try_rich_compare
tries it two-sided, which is not needed since we've a
single type only. */
if (frich!=NULL) {
res= (*frich)(v, w, op);
if (res!=Py_NotImplemented)
goto Done;
Py_DECREF(res);
}
/* No richcmp, or this particular richmp not implemented.
Try 3-way cmp. */
fcmp=v->ob_type->tp_compare;
if (fcmp!=NULL) {
intc= (*fcmp)(v, w);
c=adjust_tp_compare(c);
if (c==-2) {
res=NULL;
goto Done;
}
res=convert_3way_to_object(op, c);
goto Done;
}
}
/* Fast path not taken, or couldn't deliver a useful result. */
res=do_richcmp(v, w, op);
Done:
Py_LeaveRecursiveCall();
returnres;
}
/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
int
PyObject_RichCompareBool(PyObject*v, PyObject*w, intop)
{
PyObject*res;
intok;
/* Quick result when objects are the same.