forked from alanjds/grumpy
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtype.go
491 lines (461 loc) · 13.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
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package grumpy
import (
"fmt"
"reflect"
)
type typeFlag int
const (
// Set when instances can be created via __new__. This is the default.
// We need to be able to prohibit instantiation of certain internal
// types like NoneType. CPython accomplishes this via tp_new == NULL but
// we don't have a tp_new.
typeFlagInstantiable typeFlag = 1 << iota
// Set when the type can be used as a base class. This is the default.
// Corresponds to the Py_TPFLAGS_BASETYPE flag in CPython.
typeFlagBasetype typeFlag = 1 << iota
typeFlagDefault = typeFlagInstantiable | typeFlagBasetype
)
// Type represents Python 'type' objects.
type Type struct {
Object
name string `attr:"__name__"`
basis reflect.Type
bases []*Type
mro []*Type
flags typeFlag
slots typeSlots
}
var basisTypes = map[reflect.Type]*Type{
objectBasis: ObjectType,
typeBasis: TypeType,
}
// newClass creates a Python type with the given name, base classes and type
// dict. It is similar to the Python expression 'type(name, bases, dict)'.
func newClass(f *Frame, meta *Type, name string, bases []*Type, dict *Dict) (*Type, *BaseException) {
numBases := len(bases)
if numBases == 0 {
return nil, f.RaiseType(TypeErrorType, "class must have base classes")
}
var basis reflect.Type
for _, base := range bases {
if base.flags&typeFlagBasetype == 0 {
format := "type '%s' is not an acceptable base type"
return nil, f.RaiseType(TypeErrorType, fmt.Sprintf(format, base.Name()))
}
basis = basisSelect(basis, base.basis)
}
if basis == nil {
return nil, f.RaiseType(TypeErrorType, "class layout error")
}
t := newType(meta, name, basis, bases, dict)
// Populate slots for any special methods overridden in dict.
slotsValue := reflect.ValueOf(&t.slots).Elem()
for i := 0; i < numSlots; i++ {
dictFunc, raised := dict.GetItemString(f, slotNames[i])
if raised != nil {
return nil, raised
}
if dictFunc != nil {
slotField := slotsValue.Field(i)
slotValue := reflect.New(slotField.Type().Elem())
if slotValue.Interface().(slot).wrapCallable(dictFunc) {
slotField.Set(slotValue)
}
}
}
if err := prepareType(t); err != "" {
return nil, f.RaiseType(TypeErrorType, err)
}
// Set the __module__ attr if it's not already specified.
mod, raised := dict.GetItemString(f, "__module__")
if raised != nil {
return nil, raised
}
if mod == nil {
if raised := dict.SetItemString(f, "__module__", builtinStr.ToObject()); raised != nil {
return nil, raised
}
}
return t, nil
}
func newType(meta *Type, name string, basis reflect.Type, bases []*Type, dict *Dict) *Type {
return &Type{
Object: Object{typ: meta, dict: dict},
name: name,
basis: basis,
bases: bases,
flags: typeFlagDefault,
}
}
func newBasisType(name string, basis reflect.Type, basisFunc interface{}, base *Type) *Type {
if _, ok := basisTypes[basis]; ok {
logFatal(fmt.Sprintf("type for basis already exists: %s", basis))
}
if basis.Kind() != reflect.Struct {
logFatal(fmt.Sprintf("basis must be a struct not: %s", basis.Kind()))
}
if basis.NumField() == 0 {
logFatal(fmt.Sprintf("1st field of basis must be base type's basis"))
}
if basis.Field(0).Type != base.basis {
logFatal(fmt.Sprintf("1st field of basis must be base type's basis not: %s", basis.Field(0).Type))
}
basisFuncValue := reflect.ValueOf(basisFunc)
basisFuncType := basisFuncValue.Type()
if basisFuncValue.Kind() != reflect.Func || basisFuncType.NumIn() != 1 || basisFuncType.NumOut() != 1 ||
basisFuncType.In(0) != reflect.PtrTo(objectBasis) || basisFuncType.Out(0) != reflect.PtrTo(basis) {
logFatal(fmt.Sprintf("expected basis func of type func(*Object) *%s", nativeTypeName(basis)))
}
t := newType(TypeType, name, basis, []*Type{base}, nil)
t.slots.Basis = &basisSlot{func(o *Object) reflect.Value {
return basisFuncValue.Call([]reflect.Value{reflect.ValueOf(o)})[0].Elem()
}}
basisTypes[basis] = t
return t
}
func newSimpleType(name string, base *Type) *Type {
return newType(TypeType, name, base.basis, []*Type{base}, nil)
}
// prepareBuiltinType initializes the builtin typ by populating dict with
// struct field descriptors and slot wrappers, and then calling prepareType.
func prepareBuiltinType(typ *Type, init builtinTypeInit) {
dict := map[string]*Object{"__module__": builtinStr.ToObject()}
if init != nil {
init(dict)
}
// For basis types, export field descriptors.
if basis := typ.basis; basisTypes[basis] == typ {
numFields := basis.NumField()
for i := 0; i < numFields; i++ {
field := basis.Field(i)
if attr := field.Tag.Get("attr"); attr != "" {
fieldMode := fieldDescriptorRO
if mode := field.Tag.Get("attr_mode"); mode == "rw" {
fieldMode = fieldDescriptorRW
}
dict[attr] = makeStructFieldDescriptor(typ, field.Name, attr, fieldMode)
}
}
}
// Create dict entries for slot methods.
slotsValue := reflect.ValueOf(&typ.slots).Elem()
for i := 0; i < numSlots; i++ {
slotField := slotsValue.Field(i)
if !slotField.IsNil() {
slot := slotField.Interface().(slot)
if fun := slot.makeCallable(typ, slotNames[i]); fun != nil {
dict[slotNames[i]] = fun
}
}
}
typ.setDict(newStringDict(dict))
if err := prepareType(typ); err != "" {
logFatal(err)
}
}
// prepareType calculates typ's mro and inherits its flags and slots from its
// base classes.
func prepareType(typ *Type) string {
typ.mro = mroCalc(typ)
if typ.mro == nil {
return fmt.Sprintf("mro error for: %s", typ.name)
}
for _, base := range typ.mro {
if base.flags&typeFlagInstantiable == 0 {
typ.flags &^= typeFlagInstantiable
}
if base.flags&typeFlagBasetype == 0 {
typ.flags &^= typeFlagBasetype
}
}
// Inherit slots from typ's mro.
slotsValue := reflect.ValueOf(&typ.slots).Elem()
for i := 0; i < numSlots; i++ {
slotField := slotsValue.Field(i)
if slotField.IsNil() {
for _, base := range typ.mro {
baseSlotFunc := reflect.ValueOf(base.slots).Field(i)
if !baseSlotFunc.IsNil() {
slotField.Set(baseSlotFunc)
break
}
}
}
}
return ""
}
// Precondition: At least one of seqs is non-empty.
func mroMerge(seqs [][]*Type) []*Type {
var res []*Type
numSeqs := len(seqs)
hasNonEmptySeqs := true
for hasNonEmptySeqs {
var cand *Type
for i := 0; i < numSeqs && cand == nil; i++ {
// The next candidate will be absent from or at the head
// of all lists. If we try a candidate and we find it's
// somewhere past the head of one of the lists, reject.
seq := seqs[i]
if len(seq) == 0 {
continue
}
cand = seq[0]
RejectCandidate:
for _, seq := range seqs {
numElems := len(seq)
for j := 1; j < numElems; j++ {
if seq[j] == cand {
cand = nil
break RejectCandidate
}
}
}
}
if cand == nil {
// We could not find a candidate meaning that the
// hierarchy is inconsistent.
return nil
}
res = append(res, cand)
hasNonEmptySeqs = false
for i, seq := range seqs {
if len(seq) > 0 {
if seq[0] == cand {
// Remove the candidate from all lists
// (it will only be found at the head of
// any list because otherwise it would
// have been rejected above.)
seqs[i] = seq[1:]
}
if len(seqs[i]) > 0 {
hasNonEmptySeqs = true
}
}
}
}
return res
}
func mroCalc(t *Type) []*Type {
seqs := [][]*Type{{t}}
for _, b := range t.bases {
seqs = append(seqs, b.mro)
}
seqs = append(seqs, t.bases)
return mroMerge(seqs)
}
func toTypeUnsafe(o *Object) *Type {
return (*Type)(o.toPointer())
}
// ToObject upcasts t to an Object.
func (t *Type) ToObject() *Object {
return &t.Object
}
// Name returns t's name field.
func (t *Type) Name() string {
return t.name
}
// FullName returns t's fully qualified name including the module.
func (t *Type) FullName(f *Frame) (string, *BaseException) {
moduleAttr, raised := t.Dict().GetItemString(f, "__module__")
if raised != nil {
return "", raised
}
if moduleAttr == nil {
return t.Name(), nil
}
if moduleAttr.isInstance(StrType) {
if s := toStrUnsafe(moduleAttr).Value(); s != "__builtin__" {
return fmt.Sprintf("%s.%s", s, t.Name()), nil
}
}
return t.Name(), nil
}
func (t *Type) isSubclass(super *Type) bool {
for _, b := range t.mro {
if b == super {
return true
}
}
return false
}
func (t *Type) mroLookup(f *Frame, name *Str) (*Object, *BaseException) {
for _, t := range t.mro {
v, raised := t.Dict().GetItem(f, name.ToObject())
if v != nil || raised != nil {
return v, raised
}
}
return nil, nil
}
var typeBasis = reflect.TypeOf(Type{})
func typeBasisFunc(o *Object) reflect.Value {
return reflect.ValueOf(toTypeUnsafe(o)).Elem()
}
// TypeType is the object representing the Python 'type' type.
//
// Don't use newType() since that depends on the initialization of
// TypeType.
var TypeType = &Type{
name: "type",
basis: typeBasis,
bases: []*Type{ObjectType},
flags: typeFlagDefault,
slots: typeSlots{Basis: &basisSlot{typeBasisFunc}},
}
func typeCall(f *Frame, callable *Object, args Args, kwargs KWArgs) (*Object, *BaseException) {
t := toTypeUnsafe(callable)
newFunc := t.slots.New
if newFunc == nil {
return nil, f.RaiseType(TypeErrorType, fmt.Sprintf("type %s has no __new__", t.Name()))
}
o, raised := newFunc.Fn(f, t, args, kwargs)
if raised != nil {
return nil, raised
}
if init := o.Type().slots.Init; init != nil {
if _, raised := init.Fn(f, o, args, kwargs); raised != nil {
return nil, raised
}
}
return o, nil
}
// typeGetAttribute is very similar to objectGetAttribute except that it uses
// MRO to resolve dict attributes rather than just the type's own dict and the
// exception message is slightly different.
func typeGetAttribute(f *Frame, o *Object, name *Str) (*Object, *BaseException) {
t := toTypeUnsafe(o)
// Look for a data descriptor in the metaclass.
var metaGet *getSlot
metaType := t.typ
metaAttr, raised := metaType.mroLookup(f, name)
if raised != nil {
return nil, raised
}
if metaAttr != nil {
metaGet = metaAttr.typ.slots.Get
if metaGet != nil && (metaAttr.typ.slots.Set != nil || metaAttr.typ.slots.Delete != nil) {
return metaGet.Fn(f, metaAttr, t.ToObject(), metaType)
}
}
// Look in dict of this type and its bases.
attr, raised := t.mroLookup(f, name)
if raised != nil {
return nil, raised
}
if attr != nil {
if get := attr.typ.slots.Get; get != nil {
return get.Fn(f, attr, None, t)
}
return attr, nil
}
// Use the (non-data) descriptor from the metaclass.
if metaGet != nil {
return metaGet.Fn(f, metaAttr, t.ToObject(), metaType)
}
// Return the ordinary attr from metaclass.
if metaAttr != nil {
return metaAttr, nil
}
msg := fmt.Sprintf("type object '%s' has no attribute '%s'", t.Name(), name.Value())
return nil, f.RaiseType(AttributeErrorType, msg)
}
func typeNew(f *Frame, t *Type, args Args, kwargs KWArgs) (*Object, *BaseException) {
switch len(args) {
case 0:
return nil, f.RaiseType(TypeErrorType, "type() takes 1 or 3 arguments")
case 1:
return args[0].typ.ToObject(), nil
}
// case 3+
if raised := checkMethodArgs(f, "__new__", args, StrType, TupleType, DictType); raised != nil {
return nil, raised
}
name := toStrUnsafe(args[0]).Value()
bases := toTupleUnsafe(args[1]).elems
dict := toDictUnsafe(args[2])
baseTypes := make([]*Type, len(bases))
meta := t
for i, o := range bases {
if !o.isInstance(TypeType) {
s, raised := Repr(f, o)
if raised != nil {
return nil, raised
}
return nil, f.RaiseType(TypeErrorType, fmt.Sprintf("not a valid base class: %s", s.Value()))
}
// Choose the most derived metaclass among all the bases to be
// the metaclass for the new type.
if o.typ.isSubclass(meta) {
meta = o.typ
} else if !meta.isSubclass(o.typ) {
msg := "metaclass conflict: the metaclass of a derived class must " +
"a be a (non-strict) subclass of the metaclasses of all its bases"
return nil, f.RaiseType(TypeErrorType, msg)
}
baseTypes[i] = toTypeUnsafe(o)
}
ret, raised := newClass(f, meta, name, baseTypes, dict)
if raised != nil {
return nil, raised
}
return ret.ToObject(), nil
}
func typeRepr(f *Frame, o *Object) (*Object, *BaseException) {
s, raised := toTypeUnsafe(o).FullName(f)
if raised != nil {
return nil, raised
}
return NewStr(fmt.Sprintf("<type '%s'>", s)).ToObject(), nil
}
func initTypeType(map[string]*Object) {
TypeType.typ = TypeType
TypeType.slots.Call = &callSlot{typeCall}
TypeType.slots.GetAttribute = &getAttributeSlot{typeGetAttribute}
TypeType.slots.New = &newSlot{typeNew}
TypeType.slots.Repr = &unaryOpSlot{typeRepr}
}
// basisParent returns the immediate ancestor of basis, which is its first
// field. Returns nil when basis is objectBasis (the root of basis hierarchy.)
func basisParent(basis reflect.Type) reflect.Type {
if basis == objectBasis {
return nil
}
return basis.Field(0).Type
}
// basisSelect returns b1 if b2 inherits from it, b2 if b1 inherits from b2,
// otherwise nil. b1 can be nil in which case b2 is always returned.
func basisSelect(b1, b2 reflect.Type) reflect.Type {
if b1 == nil {
return b2
}
// Search up b1's inheritance chain to see if b2 is present.
basis := b1
for basis != nil && basis != b2 {
basis = basisParent(basis)
}
if basis != nil {
return b1
}
// Search up b2's inheritance chain to see if b1 is present.
basis = b2
for basis != nil && basis != b1 {
basis = basisParent(basis)
}
if basis != nil {
return b2
}
return nil
}