-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathtype.go
1765 lines (1573 loc) · 46.8 KB
/
type.go
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
// Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Type objects - these make objects
// FIXME should be caching the expensive lookups in the superclasses
// and using the cache clearing machinery to clear the caches when the
// heirachy changes
// FIXME should make Mro and Bases be []*Type
package py
import (
"fmt"
"log"
)
// Type flags (tp_flags)
//
// These flags are used to extend the type structure in a backwards-compatible
// fashion. Extensions can use the flags to indicate (and test) when a given
// type structure contains a new feature. The Python core will use these when
// introducing new functionality between major revisions (to avoid mid-version
// changes in the PYTHON_API_VERSION).
//
// Arbitration of the flag bit positions will need to be coordinated among
// all extension writers who publically release their extensions (this will
// be fewer than you might expect!)..
//
// Most flags were removed as of Python 3.0 to make room for new flags. (Some
// flags are not for backwards compatibility but to indicate the presence of an
// optional feature; these flags remain of course.)
//
// Type definitions should use TPFLAGS_DEFAULT for their tp_flags value.
//
// Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
// given type object has a specified feature.
const (
// Set if the type object is dynamically allocated
TPFLAGS_HEAPTYPE uint = 1 << 9
// Set if the type allows subclassing
TPFLAGS_BASETYPE uint = 1 << 10
// Set if the type is 'ready' -- fully initialized
TPFLAGS_READY uint = 1 << 12
// Set while the type is being 'readied', to prevent recursive ready calls
TPFLAGS_READYING uint = 1 << 13
// Objects support garbage collection (see objimp.h)
TPFLAGS_HAVE_GC uint = 1 << 14
// Objects support type attribute cache
TPFLAGS_HAVE_VERSION_TAG uint = 1 << 18
TPFLAGS_VALID_VERSION_TAG uint = 1 << 19
// Type is abstract and cannot be instantiated
TPFLAGS_IS_ABSTRACT uint = 1 << 20
// These flags are used to determine if a type is a subclass.
TPFLAGS_INT_SUBCLASS uint = 1 << 23
TPFLAGS_LONG_SUBCLASS uint = 1 << 24
TPFLAGS_LIST_SUBCLASS uint = 1 << 25
TPFLAGS_TUPLE_SUBCLASS uint = 1 << 26
TPFLAGS_BYTES_SUBCLASS uint = 1 << 27
TPFLAGS_UNICODE_SUBCLASS uint = 1 << 28
TPFLAGS_DICT_SUBCLASS uint = 1 << 29
TPFLAGS_BASE_EXC_SUBCLASS uint = 1 << 30
TPFLAGS_TYPE_SUBCLASS uint = 1 << 31
TPFLAGS_DEFAULT = TPFLAGS_HAVE_VERSION_TAG
)
type NewFunc func(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
type InitFunc func(self Object, args Tuple, kwargs StringDict) error
type Type struct {
ObjectType *Type // Type of this object -- FIXME this is redundant in Base?
Name string // For printing, in format "<module>.<name>"
Doc string // Documentation string
// Methods StringDict // *PyMethodDef
// Members StringDict // *PyMemberDef
// Getset *PyGetSetDef
Base *Type
Dict StringDict
// Dictoffset int
Bases Tuple
Mro Tuple // method resolution order
// Cache Object
// Subclasses Tuple
// Weaklist Tuple
New NewFunc
Init InitFunc
Flags uint // Flags to define presence of optional/expanded features
Qualname string
/*
Py_ssize_t tp_basicsize, tp_itemsize; // For allocation
// Methods to implement standard operations
destructor tp_dealloc;
printfunc tp_print;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
void *tp_reserved; // formerly known as tp_compare
reprfunc tp_repr;
// Method suites for standard classes
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
// More standard operations (here for binary compatibility)
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
// Functions to access object as input/output buffer
PyBufferProcs *tp_as_buffer;
// Flags to define presence of optional/expanded features
unsigned long tp_flags;
const char *tp_doc; // Documentation string
// Assigned meaning in release 2.0
// call function for all accessible objects
traverseproc tp_traverse;
// delete references to contained objects
inquiry tp_clear;
// Assigned meaning in release 2.1
// rich comparisons
richcmpfunc tp_richcompare;
// weak reference enabler
Py_ssize_t tp_weaklistoffset;
// Iterators
getiterfunc tp_iter;
iternextfunc tp_iternext;
// Attribute descriptor and subclassing stuff
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
Py_ssize_t tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; // Low-level free-memory routine
inquiry tp_is_gc; // For PyObject_IS_GC
PyObject *tp_bases;
PyObject *tp_mro; // method resolution order
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;
// Type attribute cache version tag. Added in version 2.6
unsigned int tp_version_tag;
destructor tp_finalize;
*/
}
var TypeType *Type = &Type{
Name: "type",
Doc: "type(object) -> the object's type\ntype(name, bases, dict) -> a new type",
Dict: StringDict{},
}
var ObjectType = &Type{
Name: "object",
Doc: "The most base type",
Flags: TPFLAGS_BASETYPE,
Dict: StringDict{},
}
func init() {
// Initialised like this to avoid initialisation loops
TypeType.New = TypeNew
TypeType.Init = TypeInit
TypeType.ObjectType = TypeType
ObjectType.New = ObjectNew
ObjectType.Init = ObjectInit
ObjectType.ObjectType = TypeType
err := TypeType.Ready()
if err != nil {
log.Fatal(err)
}
err = ObjectType.Ready()
if err != nil {
log.Fatal(err)
}
}
// Type of this object
func (t *Type) Type() *Type {
return t.ObjectType
}
// Satistfy error interface
func (t *Type) Error() string {
return t.Name
}
// Get the Dict
func (t *Type) GetDict() StringDict {
return t.Dict
}
// delayedReady holds types waiting to be intialised
var delayedReady = []*Type{}
// TypeDelayReady stores the list of types to initialise
//
// Call MakeReady when all initialised
func TypeDelayReady(t *Type) {
delayedReady = append(delayedReady, t)
}
// TypeMakeReady readies all the types
func TypeMakeReady() (err error) {
for _, t := range delayedReady {
err = t.Ready()
if err != nil {
return fmt.Errorf("Error initialising go type %s: %v", t.Name, err)
}
}
delayedReady = nil
return nil
}
func init() {
err := TypeMakeReady()
if err != nil {
log.Fatal(err)
}
}
// Make a new type from a name
//
// For making Go types
func NewType(Name string, Doc string) *Type {
t := &Type{
ObjectType: TypeType,
Name: Name,
Doc: Doc,
Dict: StringDict{},
}
TypeDelayReady(t)
return t
}
// Make a new type with constructors
//
// For making Go types
func NewTypeX(Name string, Doc string, New NewFunc, Init InitFunc) *Type {
t := &Type{
ObjectType: TypeType,
Name: Name,
Doc: Doc,
New: New,
Init: Init,
Dict: StringDict{},
}
TypeDelayReady(t)
return t
}
// Make a subclass of a type
//
// For making Go types
func (t *Type) NewTypeFlags(Name string, Doc string, New NewFunc, Init InitFunc, Flags uint) *Type {
// inherit constructors
if New == nil {
New = t.New
}
if Init == nil {
Init = t.Init
}
// FIXME inherit more stuff
tt := &Type{
ObjectType: t,
Name: Name,
Doc: Doc,
New: New,
Init: Init,
Flags: Flags,
Dict: StringDict{},
Bases: Tuple{t},
}
TypeDelayReady(tt)
return tt
}
// Make a subclass of a type
//
// For making Go types
func (t *Type) NewType(Name string, Doc string, New NewFunc, Init InitFunc) *Type {
// Inherit flags from superclass
// FIXME not sure this is correct!
return t.NewTypeFlags(Name, Doc, New, Init, t.Flags)
}
// Determine the most derived metatype.
func (metatype *Type) CalculateMetaclass(bases Tuple) (*Type, error) {
// Determine the proper metatype to deal with this,
// and check for metatype conflicts while we're at it.
// Note that if some other metatype wins to contract,
// it's possible that its instances are not types. */
winner := metatype
for _, tmp := range bases {
tmptype := tmp.Type()
if winner.IsSubtype(tmptype) {
continue
}
if tmptype.IsSubtype(winner) {
winner = tmptype
continue
}
// else:
return nil, ExceptionNewf(TypeError, "metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases")
}
return winner, nil
}
// type test with subclassing support
// reads a IsSubtype of b
func (a *Type) IsSubtype(b *Type) bool {
mro := a.Mro
if len(mro) != 0 {
// Deal with multiple inheritance without recursion
// by walking the MRO tuple
for _, baseObj := range mro {
base := baseObj.(*Type)
if base == b {
return true
}
}
return false
} else {
// a is not completely initilized yet; follow tp_base
for {
if a == b {
return true
}
a = a.Base
if a == nil {
break
}
}
return b == ObjectType
}
}
// Call type()
func (t *Type) M__call__(args Tuple, kwargs StringDict) (Object, error) {
if t.New == nil {
return nil, ExceptionNewf(TypeError, "cannot create '%s' instances", t.Name)
}
obj, err := t.New(t, args, kwargs)
if err != nil {
return nil, err
}
// Ugly exception: when the call was type(something),
// don't call tp_init on the result.
if t == TypeType && len(args) == 1 && len(kwargs) == 0 {
return obj, nil
}
// If the returned object is not an instance of type,
// it won't be initialized.
if !obj.Type().IsSubtype(t) {
return obj, nil
}
objType := obj.Type()
if objType.Init != nil {
err = objType.Init(obj, args, kwargs)
if err != nil {
return nil, err
}
}
return obj, nil
}
// Internal API to look for a name through the MRO.
// This returns a borrowed reference, and doesn't set an exception,
// returning nil instead
func (t *Type) Lookup(name string) Object {
// Py_ssize_t i, n;
// PyObject *mro, *res, *base, *dict;
// unsigned int h;
// FIXME caching
// if (MCACHE_CACHEABLE_NAME(name) &&
// PyType_HasFeature(type, TPFLAGS_VALID_VERSION_TAG)) {
// // fast path
// h = MCACHE_HASH_METHOD(type, name);
// if (method_cache[h].version == type->tp_version_tag &&
// method_cache[h].name == name)
// return method_cache[h].value;
// }
// Look in tp_dict of types in MRO
mro := t.Mro
// If mro is nil, 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 nil.
if mro == nil {
return nil
}
var res Object
// keep a strong reference to mro because type->tp_mro can be replaced
// during PyDict_GetItem(dict, name)
for _, baseObj := range mro {
base := baseObj.(*Type)
var ok bool
res, ok = base.Dict[name]
if ok {
break
}
}
// FIXME caching
// if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
// h = MCACHE_HASH_METHOD(type, name);
// method_cache[h].version = type->tp_version_tag;
// method_cache[h].value = res; /* borrowed */
// Py_INCREF(name);
// Py_DECREF(method_cache[h].name);
// method_cache[h].name = name;
// }
return res
}
// Get an attribute from the type of a go type
//
// Doesn't call __getattr__ etc
//
// # Returns nil if not found
//
// Doesn't look in the instance dictionary
//
// FIXME this isn't totally correct!
// as we are ignoring getattribute etc
// See _PyObject_GenericGetAttrWithDict in object.c
func (t *Type) NativeGetAttrOrNil(name string) Object {
// Look in type Dict
if res, ok := t.Dict[name]; ok {
return res
}
// Now look through base classes etc
return t.Lookup(name)
}
// Get an attribute from the type
//
// Doesn't call __getattr__ etc
//
// # Returns nil if not found
//
// FIXME this isn't totally correct!
// as we are ignoring getattribute etc
// See _PyObject_GenericGetAttrWithDict in object.c
func (t *Type) GetAttrOrNil(name string) Object {
// Look in instance dictionary first
if res, ok := t.Dict[name]; ok {
return res
}
// Then look in type Dict
if res, ok := t.Type().Dict[name]; ok {
return res
}
// Now look through base classes etc
return t.Lookup(name)
}
// Calls method on name
//
// If method not found returns (nil, false, nil)
//
// If method found returns (object, true, err)
//
// May raise exceptions if calling the method failed
func (t *Type) CallMethod(name string, args Tuple, kwargs StringDict) (Object, bool, error) {
fn := t.GetAttrOrNil(name) // FIXME this should use py.GetAttrOrNil?
if fn == nil {
return nil, false, nil
}
res, err := Call(fn, args, kwargs)
return res, true, err
}
// Calls a type method on obj
//
// If obj isnt a *Type or the method isn't found on it returns (nil, false, nil)
//
// Otherwise returns (object, true, err)
//
// May raise exceptions if calling the method fails
func TypeCall(self Object, name string, args Tuple, kwargs StringDict) (Object, bool, error) {
t, ok := self.(*Type)
if !ok {
return nil, false, nil
}
return t.CallMethod(name, args, kwargs)
}
// Calls TypeCall with 0 arguments
func TypeCall0(self Object, name string) (Object, bool, error) {
return TypeCall(self, name, Tuple{self}, nil)
}
// Calls TypeCall with 1 argument
func TypeCall1(self Object, name string, arg Object) (Object, bool, error) {
return TypeCall(self, name, Tuple{self, arg}, nil)
}
// Calls TypeCall with 2 arguments
func TypeCall2(self Object, name string, arg1, arg2 Object) (Object, bool, error) {
return TypeCall(self, name, Tuple{self, arg1, arg2}, nil)
}
// Internal routines to do a method lookup in the type
// without looking in the instance dictionary
// (so we can't use PyObject_GetAttr) but still binding
// it to the instance. The arguments are the object,
// the method name as a C string, and the address of a
// static variable used to cache the interned Python string.
//
// Two variants:
//
// - lookup_maybe() returns nil without raising an exception
//
// when the _PyType_Lookup() call fails;
//
// - lookup_method() always raises an exception upon errors.
func lookup_maybe(self Object, attr string) Object {
res := self.Type().Lookup(attr)
// FIXME descriptor lookup
// if (res != nil) {
// descrgetfunc f;
// if ((f = Py_TYPE(res)->tp_descr_get) == nil) {
// Py_INCREF(res);
// }else{
// res = f(res, self, (PyObject *)(Py_TYPE(self)));
// }
// }
return res
}
// func lookup_method(self Object, attr string) Object {
// res := lookup_maybe(self, attr)
// if res == nil {
// // FIXME PyErr_SetObject(PyExc_AttributeError, attrid->object);
// return ExceptionNewf(AttributeError, "'%s' object has no attribute '%s'", self.Type().Name, attr)
// }
// return res
// }
// Method resolution order algorithm C3 described in
// "A Monotonic Superclass Linearization for Dylan",
// by Kim Barrett, Bob Cassel, Paul Haahr,
// David A. Moon, Keith Playford, and P. Tucker Withington.
// (OOPSLA 1996)
//
// Some notes about the rules implied by C3:
//
// No duplicate bases.
// It isn't legal to repeat a class in a list of base classes.
//
// The next three properties are the 3 constraints in "C3".
//
// Local precendece order.
// If A precedes B in C's MRO, then A will precede B in the MRO of all
// subclasses of C.
//
// Monotonicity.
// The MRO of a class must be an extension without reordering of the
// MRO of each of its superclasses.
//
// Extended Precedence Graph (EPG).
// Linearization is consistent if there is a path in the EPG from
// each class to all its successors in the linearization. See
// the paper for definition of EPG.
func tail_contains(list *List, whence int, o Object) bool {
for j := whence + 1; j < len(list.Items); j++ {
if list.Items[j] == o {
return true
}
}
return false
}
func class_name(cls Object) string {
name := ObjectGetAttr(cls, "__name__")
if name == nil {
name = ObjectRepr(cls)
}
nameString, ok := name.(String)
if !ok {
return ""
}
return string(nameString)
}
func check_duplicates(list *List) error {
// Let's use a quadratic time algorithm,
// assuming that the bases lists is short.
for i := range list.Items {
o := list.Items[i]
for j := i + 1; j < len(list.Items); j++ {
if list.Items[j] == o {
return ExceptionNewf(TypeError, "duplicate base class %s", class_name(o))
}
}
}
return nil
}
// Raise a TypeError for an MRO order disagreement.
//
// It's hard to produce a good error message. In the absence of better
// insight into error reporting, report the classes that were candidates
// to be put next into the MRO. There is some conflict between the
// order in which they should be put in the MRO, but it's hard to
// diagnose what constraint can't be satisfied.
func set_mro_error(to_merge *List, remain []int) error {
return ExceptionNewf(TypeError, "mro is wonky")
/* FIXME implement this!
Py_ssize_t i, n, off, to_merge_size;
char buf[1000];
PyObject *k, *v;
PyObject *set = PyDict_New();
if (!set) return;
to_merge_size = PyList_GET_SIZE(to_merge);
for (i = 0; i < to_merge_size; i++) {
PyObject *L = PyList_GET_ITEM(to_merge, i);
if (remain[i] < PyList_GET_SIZE(L)) {
PyObject *c = PyList_GET_ITEM(L, remain[i]);
if (PyDict_SetItem(set, c, Py_None) < 0) {
Py_DECREF(set);
return;
}
}
}
n = PyDict_Size(set);
off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
consistent method resolution\norder (MRO) for bases");
i = 0;
while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
PyObject *name = class_name(k);
char *name_str;
if (name != nil) {
name_str = _PyUnicode_AsString(name);
if (name_str == nil)
name_str = "?";
} else
name_str = "?";
off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
Py_XDECREF(name);
if (--n && (size_t)(off+1) < sizeof(buf)) {
buf[off++] = ',';
buf[off] = '\0';
}
}
PyErr_SetString(PyExc_TypeError, buf);
Py_DECREF(set);
*/
}
func pmerge(acc, to_merge *List) error {
// Py_ssize_t i, j, to_merge_size, empty_cnt;
// int *remain;
// int ok;
to_merge_size := len(to_merge.Items)
// remain stores an index into each sublist of to_merge.
// remain[i] is the index of the next base in to_merge[i]
// that is not included in acc.
remain := make([]int, to_merge_size)
again:
empty_cnt := 0
for i := 0; i < to_merge_size; i++ {
cur_list := to_merge.Items[i].(*List)
if remain[i] >= len(cur_list.Items) {
empty_cnt++
continue
}
// Choose next candidate for MRO.
//
// The input sequences alone can determine the choice.
// If not, choose the class which appears in the MRO
// of the earliest direct superclass of the new class.
candidate := cur_list.Items[remain[i]]
for j := 0; j < to_merge_size; j++ {
j_lst := to_merge.Items[j].(*List)
if tail_contains(j_lst, remain[j], candidate) {
goto skip // continue outer loop
}
}
acc.Append(candidate)
for j := 0; j < to_merge_size; j++ {
j_lst := to_merge.Items[j].(*List)
if remain[j] < len(j_lst.Items) && j_lst.Items[remain[j]] == candidate {
remain[j]++
}
}
goto again
skip:
}
if empty_cnt == to_merge_size {
return nil
}
return set_mro_error(to_merge, remain)
}
func (t *Type) mro_implementation() (Object, error) {
// Py_ssize_t i, n;
// int ok;
// PyObject *bases, *result;
// PyObject *to_merge, *bases_aslist;
var err error
if t.Dict == nil {
err = t.Ready()
if err != nil {
return nil, err
}
}
// Find a superclass linearization that honors the constraints
// of the explicit lists of bases and the constraints implied by
// each base class.
//
// to_merge is a list of lists, where each list is a superclass
// linearization implied by a base class. The last element of
// to_merge is the declared list of bases.
bases := t.Bases
n := len(bases)
to_merge := NewListSized(n + 1)
for i := range bases {
base := bases[i].(*Type)
parentMRO, err := SequenceList(base.Mro)
if err != nil {
return nil, err
}
to_merge.Items[i] = parentMRO
}
bases_aslist, err := SequenceList(bases)
if err != nil {
return nil, err
}
// This is just a basic sanity check.
err = check_duplicates(bases_aslist)
if err != nil {
return nil, err
}
to_merge.Items[n] = bases_aslist
result := NewListFromItems([]Object{t})
err = pmerge(result, to_merge)
if err != nil {
return nil, err
}
return result, nil
}
func (t *Type) mro_internal() (err error) {
// PyObject *mro, *result, *tuple;
var result Object
checkit := false
if t == TypeType {
result, err = t.mro_implementation()
if err != nil {
return err
}
} else {
checkit = true
// FIXME this is what it was originally
// but we haven't put mro in slots or anything
// mro := lookup_method(t, "mro")
mro := lookup_maybe(t, "mro")
if mro == nil {
// Default to internal implementation
result, err = t.mro_implementation()
if err != nil {
return err
}
} else {
result, err = Call(mro, nil, nil)
if err != nil {
return err
}
}
}
tuple, err := SequenceTuple(result)
if err != nil {
return err
}
if checkit {
// Py_ssize_t i, len;
// PyObject *cls;
// PyTypeObject *solid;
solid := t.solid_base()
for i := range tuple {
cls := tuple[i]
t, ok := cls.(*Type)
if !ok {
return ExceptionNewf(TypeError, "mro() returned a non-class ('%s')", cls.Type().Name)
}
if !solid.IsSubtype(t.solid_base()) {
return ExceptionNewf(TypeError, "mro() returned base with unsuitable layout ('%.500s')", cls.Type().Name)
}
}
}
t.Mro = tuple
// FIXME t.type_mro_modified(t.Mro)
// corner case: the super class might have been hidden
// from the custom MRO
// FIXME t.type_mro_modified(t.Bases)
// FIXME t.Modified()
return nil
}
func (t *Type) inherit_special(base *Type) {
// /* Copying basicsize is connected to the GC flags */
// if (!(type->tp_flags & TPFLAGS_HAVE_GC) &&
// (base->tp_flags & TPFLAGS_HAVE_GC) &&
// (!type->tp_traverse && !type->tp_clear)) {
// type->tp_flags |= TPFLAGS_HAVE_GC;
// if (type->tp_traverse == nil)
// type->tp_traverse = base->tp_traverse;
// if (type->tp_clear == nil)
// type->tp_clear = base->tp_clear;
// }
// {
// /* The condition below could use some explanation.
// It appears that tp_new is not inherited for static types
// whose base class is 'object'; this seems to be a precaution
// so that old extension types don't suddenly become
// callable (object.__new__ wouldn't insure the invariants
// that the extension type's own factory function ensures).
// Heap types, of course, are under our control, so they do
// inherit tp_new; static extension types that specify some
// other built-in type as the default also
// inherit object.__new__. */
// if (base != &PyBaseObject_Type ||
// (type->tp_flags & TPFLAGS_HEAPTYPE)) {
// if (type->tp_new == nil)
// type->tp_new = base->tp_new;
// }
// }
// if (type->tp_basicsize == 0)
// type->tp_basicsize = base->tp_basicsize;
// /* Copy other non-function slots */
// #undef COPYVAL
// #define COPYVAL(SLOT) \
// if (type->SLOT == 0) type->SLOT = base->SLOT
// COPYVAL(tp_itemsize);
// COPYVAL(tp_weaklistoffset);
// COPYVAL(tp_dictoffset);
// Setup fast subclass flags
switch {
case base.IsSubtype(BaseException):
t.Flags |= TPFLAGS_BASE_EXC_SUBCLASS
case base.IsSubtype(TypeType):
t.Flags |= TPFLAGS_TYPE_SUBCLASS
case base.IsSubtype(IntType):
t.Flags |= TPFLAGS_LONG_SUBCLASS
case base.IsSubtype(BigIntType):
t.Flags |= TPFLAGS_LONG_SUBCLASS
case base.IsSubtype(BytesType):
t.Flags |= TPFLAGS_BYTES_SUBCLASS
case base.IsSubtype(StringType):
t.Flags |= TPFLAGS_UNICODE_SUBCLASS
case base.IsSubtype(TupleType):
t.Flags |= TPFLAGS_TUPLE_SUBCLASS
case base.IsSubtype(ListType):
t.Flags |= TPFLAGS_LIST_SUBCLASS
case base.IsSubtype(DictType):
t.Flags |= TPFLAGS_DICT_SUBCLASS
}
}
func add_subclass(base, t *Type) {
// Py_ssize_t i;
// int result;
// PyObject *list, *ref, *newobj;
// list = base->tp_subclasses;
// if (list == nil) {
// base->tp_subclasses = list = PyList_New(0);
// if (list == nil)
// return -1;
// }
// assert(PyList_Check(list));
// newobj = PyWeakref_NewRef((PyObject *)type, nil);
// i = PyList_GET_SIZE(list);
// while (--i >= 0) {
// ref = PyList_GET_ITEM(list, i);
// assert(PyWeakref_CheckRef(ref));
// if (PyWeakref_GET_OBJECT(ref) == Py_None)
// return PyList_SetItem(list, i, newobj);
// }
// result = PyList_Append(list, newobj);
// Py_DECREF(newobj);
// return result;
}
// func remove_subclass(base, t *Type) {
// // Py_ssize_t i;
// // PyObject *list, *ref;
//
// // list = base->tp_subclasses;
// // if (list == nil) {
// // return;
// // }
// // assert(PyList_Check(list));
// // i = PyList_GET_SIZE(list);
// // while (--i >= 0) {
// // ref = PyList_GET_ITEM(list, i);
// // assert(PyWeakref_CheckRef(ref));
// // if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
// // /* this can't fail, right? */
// // PySequence_DelItem(list, i);
// // return;
// // }
// // }
// }
// Ready the type for use
//
// Returns an error on problems
func (t *Type) Ready() error {
// PyObject *dict, *bases;
// PyTypeObject *base;
// Py_ssize_t i, n;
var err error
if t.Flags&TPFLAGS_READY != 0 {
if t.Dict == nil {
return ExceptionNewf(SystemError, "Type.Ready is Ready but Dict is nil")
}
return nil
}
if t.Flags&TPFLAGS_READYING != 0 {
return ExceptionNewf(SystemError, "Type.Ready already readying")
}
t.Flags |= TPFLAGS_READYING
// Initialize tp_base (defaults to BaseObject unless that's us)