Debian Codegraph @

interp/type.go

raw symbols SCIP
1 package interp
2
3 import (
4 "fmt"
5 "go/constant"
6 "path"
7 "reflect"
8 "strconv"
9 "strings"
10
11 "github.com/traefik/yaegi/internal/unsafe2"
12 )
13
14 // tcat defines interpreter type categories.
15 type tcat uint
16
17 // Types for go language.
18 const (
19 nilT tcat = iota
20 arrayT
21 binT
22 binPkgT
23 boolT
24 builtinT
25 chanT
26 chanSendT
27 chanRecvT
28 comparableT
29 complex64T
30 complex128T
31 constraintT
32 errorT
33 float32T
34 float64T
35 funcT
36 genericT
37 interfaceT
38 intT
39 int8T
40 int16T
41 int32T
42 int64T
43 linkedT
44 mapT
45 ptrT
46 sliceT
47 srcPkgT
48 stringT
49 structT
50 uintT
51 uint8T
52 uint16T
53 uint32T
54 uint64T
55 uintptrT
56 valueT
57 variadicT
58 maxT
59 )
60
61 var cats = [...]string{
62 nilT: "nilT",
63 arrayT: "arrayT",
64 binT: "binT",
65 binPkgT: "binPkgT",
66 boolT: "boolT",
67 builtinT: "builtinT",
68 chanT: "chanT",
69 comparableT: "comparableT",
70 complex64T: "complex64T",
71 complex128T: "complex128T",
72 constraintT: "constraintT",
73 errorT: "errorT",
74 float32T: "float32",
75 float64T: "float64T",
76 funcT: "funcT",
77 genericT: "genericT",
78 interfaceT: "interfaceT",
79 intT: "intT",
80 int8T: "int8T",
81 int16T: "int16T",
82 int32T: "int32T",
83 int64T: "int64T",
84 linkedT: "linkedT",
85 mapT: "mapT",
86 ptrT: "ptrT",
87 sliceT: "sliceT",
88 srcPkgT: "srcPkgT",
89 stringT: "stringT",
90 structT: "structT",
91 uintT: "uintT",
92 uint8T: "uint8T",
93 uint16T: "uint16T",
94 uint32T: "uint32T",
95 uint64T: "uint64T",
96 uintptrT: "uintptrT",
97 valueT: "valueT",
98 variadicT: "variadicT",
99 }
100
101 func (c tcat) String() string {
102 if c < tcat(len(cats)) {
103 return cats[c]
104 }
105 return "Cat(" + strconv.Itoa(int(c)) + ")"
106 }
107
108 // structField type defines a field in a struct.
109 type structField struct {
110 name string
111 tag string
112 embed bool
113 typ *itype
114 }
115
116 // itype defines the internal representation of types in the interpreter.
117 type itype struct {
118 cat tcat // Type category
119 field []structField // Array of struct fields if structT or interfaceT
120 key *itype // Type of key element if MapT or nil
121 val *itype // Type of value element if chanT, chanSendT, chanRecvT, mapT, ptrT, linkedT, arrayT, sliceT, variadicT or genericT
122 recv *itype // Receiver type for funcT or nil
123 arg []*itype // Argument types if funcT or nil
124 ret []*itype // Return types if funcT or nil
125 ptr *itype // Pointer to this type. Might be nil
126 method []*node // Associated methods or nil
127 constraint []*itype // For interfaceT: list of types part of interface set
128 ulconstraint []*itype // For interfaceT: list of underlying types part of interface set
129 instance []*itype // For genericT: list of instantiated types
130 name string // name of type within its package for a defined type
131 path string // for a defined type, the package import path
132 length int // length of array if ArrayT
133 rtype reflect.Type // Reflection type if ValueT, or nil
134 node *node // root AST node of type definition
135 scope *scope // type declaration scope (in case of re-parse incomplete type)
136 str string // String representation of the type
137 incomplete bool // true if type must be parsed again (out of order declarations)
138 untyped bool // true for a literal value (string or number)
139 isBinMethod bool // true if the type refers to a bin method function
140 }
141
142 type generic struct{}
143
144 func untypedBool(n *node) *itype {
145 return &itype{cat: boolT, name: "bool", untyped: true, str: "untyped bool", node: n}
146 }
147
148 func untypedString(n *node) *itype {
149 return &itype{cat: stringT, name: "string", untyped: true, str: "untyped string", node: n}
150 }
151
152 func untypedRune(n *node) *itype {
153 return &itype{cat: int32T, name: "int32", untyped: true, str: "untyped rune", node: n}
154 }
155
156 func untypedInt(n *node) *itype {
157 return &itype{cat: intT, name: "int", untyped: true, str: "untyped int", node: n}
158 }
159
160 func untypedFloat(n *node) *itype {
161 return &itype{cat: float64T, name: "float64", untyped: true, str: "untyped float", node: n}
162 }
163
164 func untypedComplex(n *node) *itype {
165 return &itype{cat: complex128T, name: "complex128", untyped: true, str: "untyped complex", node: n}
166 }
167
168 func errorMethodType(sc *scope) *itype {
169 return &itype{cat: funcT, ret: []*itype{sc.getType("string")}, str: "func() string"}
170 }
171
172 type itypeOption func(*itype)
173
174 func isBinMethod() itypeOption {
175 return func(t *itype) {
176 t.isBinMethod = true
177 }
178 }
179
180 func withRecv(typ *itype) itypeOption {
181 return func(t *itype) {
182 t.recv = typ
183 }
184 }
185
186 func withNode(n *node) itypeOption {
187 return func(t *itype) {
188 t.node = n
189 }
190 }
191
192 func withScope(sc *scope) itypeOption {
193 return func(t *itype) {
194 t.scope = sc
195 }
196 }
197
198 func withUntyped(b bool) itypeOption {
199 return func(t *itype) {
200 t.untyped = b
201 }
202 }
203
204 // valueTOf returns a valueT itype.
205 func valueTOf(rtype reflect.Type, opts ...itypeOption) *itype {
206 t := &itype{cat: valueT, rtype: rtype, str: rtype.String()}
207 for _, opt := range opts {
208 opt(t)
209 }
210 if t.untyped {
211 t.str = "untyped " + t.str
212 }
213 return t
214 }
215
216 // wrapperValueTOf returns a valueT itype wrapping an itype.
217 func wrapperValueTOf(rtype reflect.Type, val *itype, opts ...itypeOption) *itype {
218 t := &itype{cat: valueT, rtype: rtype, val: val, str: rtype.String()}
219 for _, opt := range opts {
220 opt(t)
221 }
222 return t
223 }
224
225 func variadicOf(val *itype, opts ...itypeOption) *itype {
226 t := &itype{cat: variadicT, val: val, str: "..." + val.str}
227 for _, opt := range opts {
228 opt(t)
229 }
230 return t
231 }
232
233 // ptrOf returns a pointer to t.
234 func ptrOf(val *itype, opts ...itypeOption) *itype {
235 if val.ptr != nil {
236 return val.ptr
237 }
238 t := &itype{cat: ptrT, val: val, str: "*" + val.str}
239 for _, opt := range opts {
240 opt(t)
241 }
242 val.ptr = t
243 return t
244 }
245
246 // namedOf returns a named type of val.
247 func namedOf(val *itype, path, name string, opts ...itypeOption) *itype {
248 str := name
249 if path != "" {
250 str = path + "." + name
251 }
252 t := &itype{cat: linkedT, val: val, path: path, name: name, str: str}
253 for _, opt := range opts {
254 opt(t)
255 }
256 return t
257 }
258
259 // funcOf returns a function type with the given args and returns.
260 func funcOf(args []*itype, ret []*itype, opts ...itypeOption) *itype {
261 b := []byte{}
262 b = append(b, "func("...)
263 b = append(b, paramsTypeString(args)...)
264 b = append(b, ')')
265 if len(ret) != 0 {
266 b = append(b, ' ')
267 if len(ret) > 1 {
268 b = append(b, '(')
269 }
270 b = append(b, paramsTypeString(ret)...)
271 if len(ret) > 1 {
272 b = append(b, ')')
273 }
274 }
275
276 t := &itype{cat: funcT, arg: args, ret: ret, str: string(b)}
277 for _, opt := range opts {
278 opt(t)
279 }
280 return t
281 }
282
283 type chanDir uint8
284
285 const (
286 chanSendRecv chanDir = iota
287 chanSend
288 chanRecv
289 )
290
291 // chanOf returns a channel of the underlying type val.
292 func chanOf(val *itype, dir chanDir, opts ...itypeOption) *itype {
293 cat := chanT
294 str := "chan "
295 switch dir {
296 case chanSend:
297 cat = chanSendT
298 str = "chan<- "
299 case chanRecv:
300 cat = chanRecvT
301 str = "<-chan "
302 }
303 t := &itype{cat: cat, val: val, str: str + val.str}
304 for _, opt := range opts {
305 opt(t)
306 }
307 return t
308 }
309
310 // arrayOf returns am array type of the underlying val with the given length.
311 func arrayOf(val *itype, l int, opts ...itypeOption) *itype {
312 lstr := strconv.Itoa(l)
313 t := &itype{cat: arrayT, val: val, length: l, str: "[" + lstr + "]" + val.str}
314 for _, opt := range opts {
315 opt(t)
316 }
317 return t
318 }
319
320 // sliceOf returns a slice type of the underlying val.
321 func sliceOf(val *itype, opts ...itypeOption) *itype {
322 t := &itype{cat: sliceT, val: val, str: "[]" + val.str}
323 for _, opt := range opts {
324 opt(t)
325 }
326 return t
327 }
328
329 // mapOf returns a map type of the underlying key and val.
330 func mapOf(key, val *itype, opts ...itypeOption) *itype {
331 t := &itype{cat: mapT, key: key, val: val, str: "map[" + key.str + "]" + val.str}
332 for _, opt := range opts {
333 opt(t)
334 }
335 return t
336 }
337
338 // interfaceOf returns an interface type with the given fields.
339 func interfaceOf(t *itype, fields []structField, constraint, ulconstraint []*itype, opts ...itypeOption) *itype {
340 str := "interface{}"
341 if len(fields) > 0 {
342 str = "interface { " + methodsTypeString(fields) + "}"
343 }
344 if t == nil {
345 t = &itype{}
346 }
347 t.cat = interfaceT
348 t.field = fields
349 t.constraint = constraint
350 t.ulconstraint = ulconstraint
351 t.str = str
352 for _, opt := range opts {
353 opt(t)
354 }
355 return t
356 }
357
358 // structOf returns a struct type with the given fields.
359 func structOf(t *itype, fields []structField, opts ...itypeOption) *itype {
360 str := "struct {}"
361 if len(fields) > 0 {
362 str = "struct { " + fieldsTypeString(fields) + "}"
363 }
364 if t == nil {
365 t = &itype{}
366 }
367 t.cat = structT
368 t.field = fields
369 t.str = str
370 for _, opt := range opts {
371 opt(t)
372 }
373 return t
374 }
375
376 // genericOf returns a generic type.
377 func genericOf(val *itype, name, path string, opts ...itypeOption) *itype {
378 t := &itype{cat: genericT, name: name, path: path, str: name, val: val}
379 for _, opt := range opts {
380 opt(t)
381 }
382 return t
383 }
384
385 // seenNode determines if a node has been seen.
386 //
387 // seenNode treats the slice of nodes as the path traveled down a node
388 // tree.
389 func seenNode(ns []*node, n *node) bool {
390 for _, nn := range ns {
391 if nn == n {
392 return true
393 }
394 }
395 return false
396 }
397
398 // nodeType returns a type definition for the corresponding AST subtree.
399 func nodeType(interp *Interpreter, sc *scope, n *node) (*itype, error) {
400 return nodeType2(interp, sc, n, nil)
401 }
402
403 func nodeType2(interp *Interpreter, sc *scope, n *node, seen []*node) (t *itype, err error) {
404 if n.typ != nil && !n.typ.incomplete {
405 return n.typ, nil
406 }
407 if sname := typeName(n); sname != "" {
408 sym, _, found := sc.lookup(sname)
409 if found && sym.kind == typeSym && sym.typ != nil {
410 if sym.typ.isComplete() {
411 return sym.typ, nil
412 }
413 if seenNode(seen, n) {
414 // We have seen this node in our tree, so it must be recursive.
415 sym.typ.incomplete = false
416 return sym.typ, nil
417 }
418 }
419 }
420 seen = append(seen, n)
421 defer func() { seen = seen[:len(seen)-1] }()
422
423 switch n.kind {
424 case addressExpr, starExpr:
425 val, err := nodeType2(interp, sc, n.child[0], seen)
426 if err != nil {
427 return nil, err
428 }
429 t = ptrOf(val, withNode(n), withScope(sc))
430 t.incomplete = val.incomplete
431
432 case arrayType:
433 c0 := n.child[0]
434 if len(n.child) == 1 {
435 val, err := nodeType2(interp, sc, c0, seen)
436 if err != nil {
437 return nil, err
438 }
439 t = sliceOf(val, withNode(n), withScope(sc))
440 t.incomplete = val.incomplete
441 break
442 }
443 // Array size is defined.
444 var (
445 length int
446 incomplete bool
447 )
448 switch v := c0.rval; {
449 case v.IsValid():
450 // Size if defined by a constant literal value.
451 if isConstantValue(v.Type()) {
452 c := v.Interface().(constant.Value)
453 length = constToInt(c)
454 } else {
455 switch v.Type().Kind() {
456 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
457 length = int(v.Int())
458 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
459 length = int(v.Uint())
460 default:
461 return nil, c0.cfgErrorf("non integer constant %v", v)
462 }
463 }
464 case c0.kind == ellipsisExpr:
465 // [...]T expression, get size from the length of composite array.
466 length, err = arrayTypeLen(n.anc, sc)
467 if err != nil {
468 incomplete = true
469 }
470 case c0.kind == identExpr:
471 sym, _, ok := sc.lookup(c0.ident)
472 if !ok {
473 incomplete = true
474 break
475 }
476 // Size is defined by a symbol which must be a constant integer.
477 if sym.kind != constSym {
478 return nil, c0.cfgErrorf("non-constant array bound %q", c0.ident)
479 }
480 if sym.typ == nil || !isInt(sym.typ.TypeOf()) || !sym.rval.IsValid() {
481 incomplete = true
482 break
483 }
484 length = int(vInt(sym.rval))
485 default:
486 // Size is defined by a numeric constant expression.
487 var ok bool
488 if _, err := interp.cfg(c0, sc, sc.pkgID, sc.pkgName); err != nil {
489 if strings.Contains(err.Error(), " undefined: ") {
490 incomplete = true
491 break
492 }
493 return nil, err
494 }
495 if !c0.rval.IsValid() {
496 return nil, c0.cfgErrorf("undefined array size")
497 }
498 if length, ok = c0.rval.Interface().(int); !ok {
499 v, ok := c0.rval.Interface().(constant.Value)
500 if !ok {
501 incomplete = true
502 break
503 }
504 length = constToInt(v)
505 }
506 }
507 val, err := nodeType2(interp, sc, n.child[1], seen)
508 if err != nil {
509 return nil, err
510 }
511 t = arrayOf(val, length, withNode(n), withScope(sc))
512 t.incomplete = incomplete || val.incomplete
513
514 case basicLit:
515 switch v := n.rval.Interface().(type) {
516 case bool:
517 n.rval = reflect.ValueOf(constant.MakeBool(v))
518 t = untypedBool(n)
519 case rune:
520 // It is impossible to work out rune const literals in AST
521 // with the correct type so we must make the const type here.
522 n.rval = reflect.ValueOf(constant.MakeInt64(int64(v)))
523 t = untypedRune(n)
524 case constant.Value:
525 switch v.Kind() {
526 case constant.Bool:
527 t = untypedBool(n)
528 case constant.String:
529 t = untypedString(n)
530 case constant.Int:
531 t = untypedInt(n)
532 case constant.Float:
533 t = untypedFloat(n)
534 case constant.Complex:
535 t = untypedComplex(n)
536 default:
537 err = n.cfgErrorf("missing support for type %v", n.rval)
538 }
539 default:
540 err = n.cfgErrorf("missing support for type %T: %v", v, n.rval)
541 }
542
543 case unaryExpr:
544 // In interfaceType, we process an underlying type constraint definition.
545 if isInInterfaceType(n) {
546 t1, err := nodeType2(interp, sc, n.child[0], seen)
547 if err != nil {
548 return nil, err
549 }
550 t = &itype{cat: constraintT, ulconstraint: []*itype{t1}}
551 break
552 }
553 t, err = nodeType2(interp, sc, n.child[0], seen)
554
555 case binaryExpr:
556 // In interfaceType, we process a type constraint union definition.
557 if isInInterfaceType(n) {
558 t = &itype{cat: constraintT, constraint: []*itype{}, ulconstraint: []*itype{}}
559 for _, c := range n.child {
560 t1, err := nodeType2(interp, sc, c, seen)
561 if err != nil {
562 return nil, err
563 }
564 switch t1.cat {
565 case constraintT:
566 t.constraint = append(t.constraint, t1.constraint...)
567 t.ulconstraint = append(t.ulconstraint, t1.ulconstraint...)
568 default:
569 t.constraint = append(t.constraint, t1)
570 }
571 }
572 break
573 }
574 // Get type of first operand.
575 if t, err = nodeType2(interp, sc, n.child[0], seen); err != nil {
576 return nil, err
577 }
578 // For operators other than shift, get the type from the 2nd operand if the first is untyped.
579 if t.untyped && !isShiftNode(n) {
580 var t1 *itype
581 t1, err = nodeType2(interp, sc, n.child[1], seen)
582 if !(t1.untyped && isInt(t1.TypeOf()) && isFloat(t.TypeOf())) {
583 t = t1
584 }
585 }
586
587 // If the node is to be assigned or returned, the node type is the destination type.
588 dt := t
589
590 switch a := n.anc; {
591 case a.kind == assignStmt && isEmptyInterface(a.child[0].typ):
592 // Because an empty interface concrete type "mutates" as different values are
593 // assigned to it, we need to make a new itype from scratch everytime a new
594 // assignment is made, and not let different nodes (of the same variable) share the
595 // same itype. Otherwise they would overwrite each other.
596 a.child[0].typ = &itype{cat: interfaceT, val: dt, str: "interface{}"}
597
598 case a.kind == defineStmt && len(a.child) > a.nleft+a.nright:
599 if dt, err = nodeType2(interp, sc, a.child[a.nleft], seen); err != nil {
600 return nil, err
601 }
602
603 case a.kind == returnStmt:
604 dt = sc.def.typ.ret[childPos(n)]
605 }
606
607 if isInterfaceSrc(dt) {
608 // Set a new interface type preserving the concrete type (.val field).
609 t2 := *dt
610 t2.val = t
611 dt = &t2
612 }
613 t = dt
614
615 case callExpr:
616 if isBuiltinCall(n, sc) {
617 // Builtin types are special and may depend from their input arguments.
618 switch n.child[0].ident {
619 case bltnComplex:
620 var nt0, nt1 *itype
621 if nt0, err = nodeType2(interp, sc, n.child[1], seen); err != nil {
622 return nil, err
623 }
624 if nt1, err = nodeType2(interp, sc, n.child[2], seen); err != nil {
625 return nil, err
626 }
627 if nt0.incomplete || nt1.incomplete {
628 t.incomplete = true
629 } else {
630 switch t0, t1 := nt0.TypeOf(), nt1.TypeOf(); {
631 case isFloat32(t0) && isFloat32(t1):
632 t = sc.getType("complex64")
633 case isFloat64(t0) && isFloat64(t1):
634 t = sc.getType("complex128")
635 case nt0.untyped && isNumber(t0) && nt1.untyped && isNumber(t1):
636 t = untypedComplex(n)
637 case nt0.untyped && isFloat32(t1) || nt1.untyped && isFloat32(t0):
638 t = sc.getType("complex64")
639 case nt0.untyped && isFloat64(t1) || nt1.untyped && isFloat64(t0):
640 t = sc.getType("complex128")
641 default:
642 err = n.cfgErrorf("invalid types %s and %s", t0.Kind(), t1.Kind())
643 }
644 if nt0.untyped && nt1.untyped {
645 t = untypedComplex(n)
646 }
647 }
648 case bltnReal, bltnImag:
649 if t, err = nodeType2(interp, sc, n.child[1], seen); err != nil {
650 return nil, err
651 }
652 if !t.incomplete {
653 switch k := t.TypeOf().Kind(); {
654 case t.untyped && isNumber(t.TypeOf()):
655 t = untypedFloat(n)
656 case k == reflect.Complex64:
657 t = sc.getType("float32")
658 case k == reflect.Complex128:
659 t = sc.getType("float64")
660 default:
661 err = n.cfgErrorf("invalid complex type %s", k)
662 }
663 }
664 case bltnCap, bltnCopy, bltnLen:
665 t = sc.getType("int")
666 case bltnAppend, bltnMake:
667 t, err = nodeType2(interp, sc, n.child[1], seen)
668 case bltnNew:
669 t, err = nodeType2(interp, sc, n.child[1], seen)
670 incomplete := t.incomplete
671 t = ptrOf(t, withScope(sc))
672 t.incomplete = incomplete
673 case bltnRecover:
674 t = sc.getType("interface{}")
675 default:
676 t = &itype{cat: builtinT}
677 }
678 if err != nil {
679 return nil, err
680 }
681 } else {
682 if t, err = nodeType2(interp, sc, n.child[0], seen); err != nil || t == nil {
683 return nil, err
684 }
685 switch t.cat {
686 case valueT:
687 if rt := t.rtype; rt.Kind() == reflect.Func && rt.NumOut() == 1 {
688 t = valueTOf(rt.Out(0), withScope(sc))
689 }
690 default:
691 if len(t.ret) == 1 {
692 t = t.ret[0]
693 }
694 }
695 }
696
697 case compositeLitExpr:
698 t, err = nodeType2(interp, sc, n.child[0], seen)
699
700 case chanType, chanTypeRecv, chanTypeSend:
701 dir := chanSendRecv
702 switch n.kind {
703 case chanTypeRecv:
704 dir = chanRecv
705 case chanTypeSend:
706 dir = chanSend
707 }
708 val, err := nodeType2(interp, sc, n.child[0], seen)
709 if err != nil {
710 return nil, err
711 }
712 t = chanOf(val, dir, withNode(n), withScope(sc))
713 t.incomplete = val.incomplete
714
715 case ellipsisExpr:
716 val, err := nodeType2(interp, sc, n.child[0], seen)
717 if err != nil {
718 return nil, err
719 }
720 t = variadicOf(val, withNode(n), withScope(sc))
721 t.incomplete = t.val.incomplete
722
723 case funcLit:
724 t, err = nodeType2(interp, sc, n.child[2], seen)
725
726 case funcType:
727 var incomplete bool
728
729 // Handle type parameters.
730 for _, arg := range n.child[0].child {
731 cl := len(arg.child) - 1
732 typ, err := nodeType2(interp, sc, arg.child[cl], seen)
733 if err != nil {
734 return nil, err
735 }
736 for _, c := range arg.child[:cl] {
737 sc.sym[c.ident] = &symbol{index: -1, kind: varTypeSym, typ: typ}
738 }
739 incomplete = incomplete || typ.incomplete
740 }
741
742 // Handle input parameters.
743 args := make([]*itype, 0, len(n.child[1].child))
744 for _, arg := range n.child[1].child {
745 cl := len(arg.child) - 1
746 typ, err := nodeType2(interp, sc, arg.child[cl], seen)
747 if err != nil {
748 return nil, err
749 }
750 args = append(args, typ)
751 // Several arguments may be factorized on the same field type.
752 for i := 1; i < cl; i++ {
753 args = append(args, typ)
754 }
755 incomplete = incomplete || typ.incomplete
756 }
757
758 // Handle returned values.
759 var rets []*itype
760 if len(n.child) == 3 {
761 for _, ret := range n.child[2].child {
762 cl := len(ret.child) - 1
763 typ, err := nodeType2(interp, sc, ret.child[cl], seen)
764 if err != nil {
765 return nil, err
766 }
767 rets = append(rets, typ)
768 // Several arguments may be factorized on the same field type.
769 for i := 1; i < cl; i++ {
770 rets = append(rets, typ)
771 }
772 incomplete = incomplete || typ.incomplete
773 }
774 }
775 t = funcOf(args, rets, withNode(n), withScope(sc))
776 t.incomplete = incomplete
777
778 case identExpr:
779 sym, _, found := sc.lookup(n.ident)
780 if !found {
781 // retry with the filename, in case ident is a package name.
782 baseName := path.Base(interp.fset.Position(n.pos).Filename)
783 ident := path.Join(n.ident, baseName)
784 sym, _, found = sc.lookup(ident)
785 if !found {
786 t = &itype{name: n.ident, path: sc.pkgName, node: n, incomplete: true, scope: sc}
787 sc.sym[n.ident] = &symbol{kind: typeSym, typ: t}
788 break
789 }
790 }
791 if sym.kind == varTypeSym {
792 t = genericOf(sym.typ, n.ident, sc.pkgName, withNode(n), withScope(sc))
793 } else {
794 t = sym.typ
795 }
796 if t == nil {
797 if t, err = nodeType2(interp, sc, sym.node, seen); err != nil {
798 return nil, err
799 }
800 }
801 if t.incomplete && t.cat == linkedT && t.val != nil && t.val.cat != nilT {
802 t.incomplete = false
803 }
804 if t.incomplete && t.node != n {
805 m := t.method
806 if t, err = nodeType2(interp, sc, t.node, seen); err != nil {
807 return nil, err
808 }
809 t.method = m
810 sym.typ = t
811 }
812 if t.node == nil {
813 t.node = n
814 }
815
816 case indexExpr:
817 var lt *itype
818 if lt, err = nodeType2(interp, sc, n.child[0], seen); err != nil {
819 return nil, err
820 }
821 if lt.incomplete {
822 if t == nil {
823 t = lt
824 } else {
825 t.incomplete = true
826 }
827 break
828 }
829 switch lt.cat {
830 case arrayT, mapT, sliceT, variadicT:
831 t = lt.val
832 case genericT:
833 t1, err := nodeType2(interp, sc, n.child[1], seen)
834 if err != nil {
835 return nil, err
836 }
837 if t1.cat == genericT || t1.incomplete {
838 t = lt
839 break
840 }
841 name := lt.id() + "[" + t1.id() + "]"
842 if sym, _, found := sc.lookup(name); found {
843 t = sym.typ
844 break
845 }
846 // A generic type is being instantiated. Generate it.
847 t, err = genType(interp, sc, name, lt, []*itype{t1}, seen)
848 if err != nil {
849 return nil, err
850 }
851 }
852
853 case indexListExpr:
854 // Similar to above indexExpr for generic types, but handle multiple type parameters.
855 var lt *itype
856 if lt, err = nodeType2(interp, sc, n.child[0], seen); err != nil {
857 return nil, err
858 }
859 if lt.incomplete {
860 if t == nil {
861 t = lt
862 } else {
863 t.incomplete = true
864 }
865 break
866 }
867
868 // Index list expressions can be used only in context of generic types.
869 if lt.cat != genericT {
870 err = n.cfgErrorf("not a generic type: %s", lt.id())
871 return nil, err
872 }
873 name := lt.id() + "["
874 out := false
875 types := []*itype{}
876 for _, c := range n.child[1:] {
877 t1, err := nodeType2(interp, sc, c, seen)
878 if err != nil {
879 return nil, err
880 }
881 if t1.cat == genericT || t1.incomplete {
882 t = lt
883 out = true
884 break
885 }
886 types = append(types, t1)
887 name += t1.id() + ","
888 }
889 if out {
890 break
891 }
892 name = strings.TrimSuffix(name, ",") + "]"
893 if sym, _, found := sc.lookup(name); found {
894 t = sym.typ
895 break
896 }
897 // A generic type is being instantiated. Generate it.
898 t, err = genType(interp, sc, name, lt, types, seen)
899
900 case interfaceType:
901 if sname := typeName(n); sname != "" {
902 if sym, _, found := sc.lookup(sname); found && sym.kind == typeSym {
903 t = interfaceOf(sym.typ, sym.typ.field, sym.typ.constraint, sym.typ.ulconstraint, withNode(n), withScope(sc))
904 }
905 }
906 var incomplete bool
907 fields := []structField{}
908 constraint := []*itype{}
909 ulconstraint := []*itype{}
910 for _, c := range n.child[0].child {
911 c0 := c.child[0]
912 if len(c.child) == 1 {
913 if c0.ident == "error" {
914 // Unwrap error interface inplace rather than embedding it, because
915 // "error" is lower case which may cause problems with reflect for method lookup.
916 typ := errorMethodType(sc)
917 fields = append(fields, structField{name: "Error", typ: typ})
918 continue
919 }
920 typ, err := nodeType2(interp, sc, c0, seen)
921 if err != nil {
922 return nil, err
923 }
924 incomplete = incomplete || typ.incomplete
925 if typ.cat == constraintT {
926 constraint = append(constraint, typ.constraint...)
927 ulconstraint = append(ulconstraint, typ.ulconstraint...)
928 continue
929 }
930 fields = append(fields, structField{name: fieldName(c0), embed: true, typ: typ})
931 continue
932 }
933 typ, err := nodeType2(interp, sc, c.child[1], seen)
934 if err != nil {
935 return nil, err
936 }
937 fields = append(fields, structField{name: c0.ident, typ: typ})
938 incomplete = incomplete || typ.incomplete
939 }
940 t = interfaceOf(t, fields, constraint, ulconstraint, withNode(n), withScope(sc))
941 t.incomplete = incomplete
942
943 case landExpr, lorExpr:
944 t = sc.getType("bool")
945
946 case mapType:
947 key, err := nodeType2(interp, sc, n.child[0], seen)
948 if err != nil {
949 return nil, err
950 }
951 val, err := nodeType2(interp, sc, n.child[1], seen)
952 if err != nil {
953 return nil, err
954 }
955 t = mapOf(key, val, withNode(n), withScope(sc))
956 t.incomplete = key.incomplete || val.incomplete
957
958 case parenExpr:
959 t, err = nodeType2(interp, sc, n.child[0], seen)
960
961 case selectorExpr:
962 // Resolve the left part of selector, then lookup the right part on it
963 var lt *itype
964
965 // Lookup the package symbol first if we are in a field expression as
966 // a previous parameter has the same name as the package, we need to
967 // prioritize the package type.
968 if n.anc.kind == fieldExpr {
969 lt = findPackageType(interp, sc, n.child[0])
970 }
971 if lt == nil {
972 // No package was found or we are not in a field expression, we are looking for a variable.
973 if lt, err = nodeType2(interp, sc, n.child[0], seen); err != nil {
974 return nil, err
975 }
976 }
977
978 if lt.incomplete {
979 break
980 }
981 name := n.child[1].ident
982 switch lt.cat {
983 case binPkgT:
984 pkg := interp.binPkg[lt.path]
985 if v, ok := pkg[name]; ok {
986 rtype := v.Type()
987 if isBinType(v) {
988 // A bin type is encoded as a pointer on a typed nil value.
989 rtype = rtype.Elem()
990 }
991 t = valueTOf(rtype, withNode(n), withScope(sc))
992 break
993 }
994 // Continue search in source package, as it may exist if package contains generics.
995 fallthrough
996 case srcPkgT:
997 if pkg, ok := interp.srcPkg[lt.path]; ok {
998 if s, ok := pkg[name]; ok {
999 t = s.typ
1000 break
1001 }
1002 }
1003 err = n.cfgErrorf("undefined selector %s.%s", lt.path, name)
1004 default:
1005 if m, _ := lt.lookupMethod(name); m != nil {
1006 t, err = nodeType2(interp, sc, m.child[2], seen)
1007 } else if bm, _, _, ok := lt.lookupBinMethod(name); ok {
1008 t = valueTOf(bm.Type, isBinMethod(), withRecv(lt), withScope(sc))
1009 } else if ti := lt.lookupField(name); len(ti) > 0 {
1010 t = lt.fieldSeq(ti)
1011 } else if bs, _, ok := lt.lookupBinField(name); ok {
1012 t = valueTOf(bs.Type, withScope(sc))
1013 } else {
1014 err = lt.node.cfgErrorf("undefined selector %s", name)
1015 }
1016 }
1017
1018 case sliceExpr:
1019 t, err = nodeType2(interp, sc, n.child[0], seen)
1020 if err != nil {
1021 return nil, err
1022 }
1023
1024 if t.cat == valueT {
1025 switch t.rtype.Kind() {
1026 case reflect.Array, reflect.Ptr:
1027 t = valueTOf(reflect.SliceOf(t.rtype.Elem()), withScope(sc))
1028 }
1029 break
1030 }
1031 if t.cat == ptrT {
1032 t = t.val
1033 }
1034 if t.cat == arrayT {
1035 incomplete := t.incomplete
1036 t = sliceOf(t.val, withNode(n), withScope(sc))
1037 t.incomplete = incomplete
1038 }
1039
1040 case structType:
1041 var sym *symbol
1042 var found bool
1043 sname := structName(n)
1044 if sname != "" {
1045 sym, _, found = sc.lookup(sname)
1046 if found && sym.kind == typeSym && sym.typ != nil {
1047 t = structOf(sym.typ, sym.typ.field, withNode(n), withScope(sc))
1048 } else {
1049 t = structOf(nil, nil, withNode(n), withScope(sc))
1050 sc.sym[sname] = &symbol{index: -1, kind: typeSym, typ: t, node: n}
1051 }
1052 }
1053 var incomplete bool
1054 fields := make([]structField, 0, len(n.child[0].child))
1055 for _, c := range n.child[0].child {
1056 switch {
1057 case len(c.child) == 1:
1058 typ, err := nodeType2(interp, sc, c.child[0], seen)
1059 if err != nil {
1060 return nil, err
1061 }
1062 fields = append(fields, structField{name: fieldName(c.child[0]), embed: true, typ: typ})
1063 incomplete = incomplete || typ.incomplete
1064 case len(c.child) == 2 && c.child[1].kind == basicLit:
1065 tag := vString(c.child[1].rval)
1066 typ, err := nodeType2(interp, sc, c.child[0], seen)
1067 if err != nil {
1068 return nil, err
1069 }
1070 fields = append(fields, structField{name: fieldName(c.child[0]), embed: true, typ: typ, tag: tag})
1071 incomplete = incomplete || typ.incomplete
1072 default:
1073 var tag string
1074 l := len(c.child)
1075 if c.lastChild().kind == basicLit {
1076 tag = vString(c.lastChild().rval)
1077 l--
1078 }
1079 typ, err := nodeType2(interp, sc, c.child[l-1], seen)
1080 if err != nil {
1081 return nil, err
1082 }
1083 incomplete = incomplete || typ.incomplete
1084 for _, d := range c.child[:l-1] {
1085 fields = append(fields, structField{name: d.ident, typ: typ, tag: tag})
1086 }
1087 }
1088 }
1089 t = structOf(t, fields, withNode(n), withScope(sc))
1090 t.incomplete = incomplete
1091 if sname != "" {
1092 if sc.sym[sname] == nil {
1093 sc.sym[sname] = &symbol{index: -1, kind: typeSym, node: n}
1094 }
1095 sc.sym[sname].typ = t
1096 }
1097
1098 case typeAssertExpr:
1099 t, err = nodeType2(interp, sc, n.child[1], seen)
1100
1101 default:
1102 err = n.cfgErrorf("type definition not implemented: %s", n.kind)
1103 }
1104
1105 if err == nil && t != nil && t.cat == nilT && !t.incomplete {
1106 err = n.cfgErrorf("use of untyped nil %s", t.name)
1107 }
1108
1109 // The existing symbol data needs to be recovered, but not in the
1110 // case where we are aliasing another type.
1111 if n.anc.kind == typeSpec && n.kind != selectorExpr && n.kind != identExpr {
1112 name := n.anc.child[0].ident
1113 if sym := sc.sym[name]; sym != nil {
1114 t.path = sc.pkgName
1115 t.name = name
1116 }
1117 }
1118
1119 switch {
1120 case t == nil:
1121 case t.name != "" && t.path != "":
1122 t.str = t.path + "." + t.name
1123 case t.cat == nilT:
1124 t.str = "nil"
1125 }
1126
1127 return t, err
1128 }
1129
1130 func genType(interp *Interpreter, sc *scope, name string, lt *itype, types []*itype, seen []*node) (t *itype, err error) {
1131 // A generic type is being instantiated. Generate it.
1132 g, _, err := genAST(sc, lt.node.anc, types)
1133 if err != nil {
1134 return nil, err
1135 }
1136 t, err = nodeType2(interp, sc, g.lastChild(), seen)
1137 if err != nil {
1138 return nil, err
1139 }
1140 lt.instance = append(lt.instance, t)
1141 // Add generated symbol in the scope of generic source and user.
1142 sc.sym[name] = &symbol{index: -1, kind: typeSym, typ: t, node: g}
1143 if lt.scope.sym[name] == nil {
1144 lt.scope.sym[name] = sc.sym[name]
1145 }
1146
1147 for _, nod := range lt.method {
1148 if err := genMethod(interp, sc, t, nod, types); err != nil {
1149 return nil, err
1150 }
1151 }
1152 return t, err
1153 }
1154
1155 func genMethod(interp *Interpreter, sc *scope, t *itype, nod *node, types []*itype) error {
1156 gm, _, err := genAST(sc, nod, types)
1157 if err != nil {
1158 return err
1159 }
1160 if gm.typ, err = nodeType(interp, sc, gm.child[2]); err != nil {
1161 return err
1162 }
1163 t.addMethod(gm)
1164
1165 // If the receiver is a pointer to a generic type, generate also the pointer type.
1166 if rtn := gm.child[0].child[0].lastChild(); rtn != nil && rtn.kind == starExpr {
1167 pt := ptrOf(t, withNode(t.node), withScope(sc))
1168 pt.addMethod(gm)
1169 rtn.typ = pt
1170 }
1171
1172 // Compile the method AST in the scope of the generic type.
1173 scop := nod.typ.scope
1174 if _, err = interp.cfg(gm, scop, scop.pkgID, scop.pkgName); err != nil {
1175 return err
1176 }
1177
1178 // Generate closures for function body.
1179 return genRun(gm)
1180 }
1181
1182 // findPackageType searches the top level scope for a package type.
1183 func findPackageType(interp *Interpreter, sc *scope, n *node) *itype {
1184 // Find the root scope, the package symbols will exist there.
1185 for sc.level != 0 {
1186 sc = sc.anc
1187 }
1188
1189 baseName := path.Base(interp.fset.Position(n.pos).Filename)
1190 sym, _, found := sc.lookup(path.Join(n.ident, baseName))
1191 if !found || sym.typ == nil && sym.typ.cat != srcPkgT && sym.typ.cat != binPkgT {
1192 return nil
1193 }
1194 return sym.typ
1195 }
1196
1197 func isBuiltinCall(n *node, sc *scope) bool {
1198 if n.kind != callExpr {
1199 return false
1200 }
1201 s := n.child[0].sym
1202 if s == nil {
1203 if sym, _, found := sc.lookup(n.child[0].ident); found {
1204 s = sym
1205 }
1206 }
1207 return s != nil && s.kind == bltnSym
1208 }
1209
1210 // struct name returns the name of a struct type.
1211 func typeName(n *node) string {
1212 if n.anc.kind == typeSpec && len(n.anc.child) == 2 {
1213 return n.anc.child[0].ident
1214 }
1215 return ""
1216 }
1217
1218 func structName(n *node) string {
1219 if n.anc.kind == typeSpec {
1220 return n.anc.child[0].ident
1221 }
1222 return ""
1223 }
1224
1225 // fieldName returns an implicit struct field name according to node kind.
1226 func fieldName(n *node) string {
1227 switch n.kind {
1228 case selectorExpr:
1229 return fieldName(n.child[1])
1230 case starExpr:
1231 return fieldName(n.child[0])
1232 case indexExpr:
1233 return fieldName(n.child[0])
1234 case identExpr:
1235 return n.ident
1236 default:
1237 return ""
1238 }
1239 }
1240
1241 var zeroValues [maxT]reflect.Value
1242
1243 func init() {
1244 zeroValues[boolT] = reflect.ValueOf(false)
1245 zeroValues[complex64T] = reflect.ValueOf(complex64(0))
1246 zeroValues[complex128T] = reflect.ValueOf(complex128(0))
1247 zeroValues[errorT] = reflect.ValueOf(new(error)).Elem()
1248 zeroValues[float32T] = reflect.ValueOf(float32(0))
1249 zeroValues[float64T] = reflect.ValueOf(float64(0))
1250 zeroValues[intT] = reflect.ValueOf(int(0))
1251 zeroValues[int8T] = reflect.ValueOf(int8(0))
1252 zeroValues[int16T] = reflect.ValueOf(int16(0))
1253 zeroValues[int32T] = reflect.ValueOf(int32(0))
1254 zeroValues[int64T] = reflect.ValueOf(int64(0))
1255 zeroValues[stringT] = reflect.ValueOf("")
1256 zeroValues[uintT] = reflect.ValueOf(uint(0))
1257 zeroValues[uint8T] = reflect.ValueOf(uint8(0))
1258 zeroValues[uint16T] = reflect.ValueOf(uint16(0))
1259 zeroValues[uint32T] = reflect.ValueOf(uint32(0))
1260 zeroValues[uint64T] = reflect.ValueOf(uint64(0))
1261 zeroValues[uintptrT] = reflect.ValueOf(uintptr(0))
1262 }
1263
1264 // Finalize returns a type pointer and error. It reparses a type from the
1265 // partial AST if necessary (after missing dependecy data is available).
1266 // If error is nil, the type is guarranteed to be completely defined and
1267 // usable for CFG.
1268 func (t *itype) finalize() (*itype, error) {
1269 var err error
1270 if t.incomplete {
1271 sym, _, found := t.scope.lookup(t.name)
1272 if found && !sym.typ.incomplete {
1273 sym.typ.method = append(sym.typ.method, t.method...)
1274 t.method = sym.typ.method
1275 t.incomplete = false
1276 return sym.typ, nil
1277 }
1278 m := t.method
1279 if t, err = nodeType(t.node.interp, t.scope, t.node); err != nil {
1280 return nil, err
1281 }
1282 if t.incomplete {
1283 return nil, t.node.cfgErrorf("incomplete type %s", t.name)
1284 }
1285 t.method = m
1286 t.node.typ = t
1287 if sym != nil {
1288 sym.typ = t
1289 }
1290 }
1291 return t, err
1292 }
1293
1294 func (t *itype) addMethod(n *node) {
1295 for _, m := range t.method {
1296 if m == n {
1297 return
1298 }
1299 }
1300 t.method = append(t.method, n)
1301 }
1302
1303 func (t *itype) numIn() int {
1304 switch t.cat {
1305 case funcT:
1306 return len(t.arg)
1307 case valueT:
1308 if t.rtype.Kind() != reflect.Func {
1309 return 0
1310 }
1311 in := t.rtype.NumIn()
1312 if t.recv != nil {
1313 in--
1314 }
1315 return in
1316 }
1317 return 0
1318 }
1319
1320 func (t *itype) in(i int) *itype {
1321 switch t.cat {
1322 case funcT:
1323 return t.arg[i]
1324 case valueT:
1325 if t.rtype.Kind() == reflect.Func {
1326 if t.recv != nil && !isInterface(t.recv) {
1327 i++
1328 }
1329 if t.rtype.IsVariadic() && i == t.rtype.NumIn()-1 {
1330 val := valueTOf(t.rtype.In(i).Elem())
1331 return &itype{cat: variadicT, val: val, str: "..." + val.str}
1332 }
1333 return valueTOf(t.rtype.In(i))
1334 }
1335 }
1336 return nil
1337 }
1338
1339 func (t *itype) numOut() int {
1340 switch t.cat {
1341 case funcT:
1342 return len(t.ret)
1343 case valueT:
1344 if t.rtype.Kind() == reflect.Func {
1345 return t.rtype.NumOut()
1346 }
1347 case builtinT:
1348 switch t.name {
1349 case "append", "cap", "complex", "copy", "imag", "len", "make", "new", "real", "recover", "unsafe.Alignof", "unsafe.Offsetof", "unsafe.Sizeof":
1350 return 1
1351 }
1352 }
1353 return 0
1354 }
1355
1356 func (t *itype) out(i int) *itype {
1357 switch t.cat {
1358 case funcT:
1359 return t.ret[i]
1360 case valueT:
1361 if t.rtype.Kind() == reflect.Func {
1362 return valueTOf(t.rtype.Out(i))
1363 }
1364 }
1365 return nil
1366 }
1367
1368 func (t *itype) concrete() *itype {
1369 if isInterface(t) && t.val != nil {
1370 return t.val.concrete()
1371 }
1372 return t
1373 }
1374
1375 func (t *itype) underlying() *itype {
1376 if t.cat == linkedT {
1377 return t.val.underlying()
1378 }
1379 return t
1380 }
1381
1382 // typeDefined returns true if type t1 is defined from type t2 or t2 from t1.
1383 func typeDefined(t1, t2 *itype) bool {
1384 if t1.cat == linkedT && t1.val == t2 {
1385 return true
1386 }
1387 if t2.cat == linkedT && t2.val == t1 {
1388 return true
1389 }
1390 return false
1391 }
1392
1393 // isVariadic returns true if the function type is variadic.
1394 // If the type is not a function or is not variadic, it will
1395 // return false.
1396 func (t *itype) isVariadic() bool {
1397 switch t.cat {
1398 case funcT:
1399 return len(t.arg) > 0 && t.arg[len(t.arg)-1].cat == variadicT
1400 case valueT:
1401 if t.rtype.Kind() == reflect.Func {
1402 return t.rtype.IsVariadic()
1403 }
1404 }
1405 return false
1406 }
1407
1408 // isComplete returns true if type definition is complete.
1409 func (t *itype) isComplete() bool { return isComplete(t, map[string]bool{}) }
1410
1411 func isComplete(t *itype, visited map[string]bool) bool {
1412 if t.incomplete {
1413 return false
1414 }
1415 name := t.path + "/" + t.name
1416 if visited[name] {
1417 return true
1418 }
1419 if t.name != "" {
1420 visited[name] = true
1421 }
1422 switch t.cat {
1423 case linkedT:
1424 if t.val != nil && t.val.cat != nilT {
1425 // A type aliased to a partially defined type is considered complete, to allow recursivity.
1426 return true
1427 }
1428 fallthrough
1429 case arrayT, chanT, chanRecvT, chanSendT, ptrT, sliceT, variadicT:
1430 return isComplete(t.val, visited)
1431 case funcT:
1432 complete := true
1433 for _, a := range t.arg {
1434 complete = complete && isComplete(a, visited)
1435 }
1436 for _, a := range t.ret {
1437 complete = complete && isComplete(a, visited)
1438 }
1439 return complete
1440 case interfaceT, structT:
1441 complete := true
1442 for _, f := range t.field {
1443 // Field implicit type names must be marked as visited, to break false circles.
1444 visited[f.typ.path+"/"+f.typ.name] = true
1445 complete = complete && isComplete(f.typ, visited)
1446 }
1447 return complete
1448 case mapT:
1449 return isComplete(t.key, visited) && isComplete(t.val, visited)
1450 case nilT:
1451 return false
1452 }
1453 return true
1454 }
1455
1456 // comparable returns true if the type is comparable.
1457 func (t *itype) comparable() bool {
1458 typ := t.TypeOf()
1459 return t.cat == nilT || typ != nil && typ.Comparable()
1460 }
1461
1462 func (t *itype) assignableTo(o *itype) bool {
1463 if t.equals(o) {
1464 return true
1465 }
1466
1467 if t.cat == linkedT && o.cat == linkedT && (t.underlying().id() != o.underlying().id() || !typeDefined(t, o)) {
1468 return false
1469 }
1470
1471 if t.isNil() && o.hasNil() || o.isNil() && t.hasNil() {
1472 return true
1473 }
1474
1475 if t.TypeOf().AssignableTo(o.TypeOf()) {
1476 return true
1477 }
1478
1479 if isInterface(o) && t.implements(o) {
1480 return true
1481 }
1482
1483 if t.cat == sliceT && o.cat == sliceT {
1484 return t.val.assignableTo(o.val)
1485 }
1486
1487 if t.isBinMethod && isFunc(o) {
1488 // TODO (marc): check that t without receiver as first parameter is equivalent to o.
1489 return true
1490 }
1491
1492 if t.untyped && isNumber(t.TypeOf()) && isNumber(o.TypeOf()) {
1493 // Assignability depends on constant numeric value (overflow check), to be tested elsewhere.
1494 return true
1495 }
1496
1497 n := t.node
1498 if n == nil || !n.rval.IsValid() {
1499 return false
1500 }
1501 con, ok := n.rval.Interface().(constant.Value)
1502 if !ok {
1503 return false
1504 }
1505 if con == nil || !isConstType(o) {
1506 return false
1507 }
1508 return representableConst(con, o.TypeOf())
1509 }
1510
1511 // convertibleTo returns true if t is convertible to o.
1512 func (t *itype) convertibleTo(o *itype) bool {
1513 if t.assignableTo(o) {
1514 return true
1515 }
1516
1517 // unsafe checks
1518 tt, ot := t.TypeOf(), o.TypeOf()
1519 if (tt.Kind() == reflect.Ptr || tt.Kind() == reflect.Uintptr) && ot.Kind() == reflect.UnsafePointer {
1520 return true
1521 }
1522 if tt.Kind() == reflect.UnsafePointer && (ot.Kind() == reflect.Ptr || ot.Kind() == reflect.Uintptr) {
1523 return true
1524 }
1525
1526 return t.TypeOf().ConvertibleTo(o.TypeOf())
1527 }
1528
1529 // ordered returns true if the type is ordered.
1530 func (t *itype) ordered() bool {
1531 typ := t.TypeOf()
1532 return isInt(typ) || isFloat(typ) || isString(typ)
1533 }
1534
1535 // equals returns true if the given type is identical to the receiver one.
1536 func (t *itype) equals(o *itype) bool {
1537 switch ti, oi := isInterface(t), isInterface(o); {
1538 case ti && oi:
1539 return t.methods().equals(o.methods())
1540 case ti && !oi:
1541 return o.methods().contains(t.methods())
1542 case oi && !ti:
1543 return t.methods().contains(o.methods())
1544 default:
1545 return t.id() == o.id()
1546 }
1547 }
1548
1549 // matchDefault returns true if the receiver default type is the same as the given one.
1550 func (t *itype) matchDefault(o *itype) bool {
1551 return t.untyped && t.id() == "untyped "+o.id()
1552 }
1553
1554 // MethodSet defines the set of methods signatures as strings, indexed per method name.
1555 type methodSet map[string]string
1556
1557 // Contains returns true if the method set m contains the method set n.
1558 func (m methodSet) contains(n methodSet) bool {
1559 for k := range n {
1560 // Only check the presence of method, not its complete signature,
1561 // as the receiver may be part of the arguments, which makes a
1562 // robust check complex.
1563 if _, ok := m[k]; !ok {
1564 return false
1565 }
1566 }
1567 return true
1568 }
1569
1570 // Equal returns true if the method set m is equal to the method set n.
1571 func (m methodSet) equals(n methodSet) bool {
1572 return m.contains(n) && n.contains(m)
1573 }
1574
1575 // Methods returns a map of method type strings, indexed by method names.
1576 func (t *itype) methods() methodSet {
1577 seen := map[*itype]bool{}
1578 var getMethods func(typ *itype) methodSet
1579
1580 getMethods = func(typ *itype) methodSet {
1581 res := make(methodSet)
1582
1583 if seen[typ] {
1584 // Stop the recursion, we have seen this type.
1585 return res
1586 }
1587 seen[typ] = true
1588
1589 switch typ.cat {
1590 case linkedT:
1591 for k, v := range getMethods(typ.val) {
1592 res[k] = v
1593 }
1594 case interfaceT:
1595 // Get methods from recursive analysis of interface fields.
1596 for _, f := range typ.field {
1597 if f.typ.cat == funcT {
1598 res[f.name] = f.typ.TypeOf().String()
1599 } else {
1600 for k, v := range getMethods(f.typ) {
1601 res[k] = v
1602 }
1603 }
1604 }
1605 case valueT, errorT:
1606 // Get method from corresponding reflect.Type.
1607 for i := typ.TypeOf().NumMethod() - 1; i >= 0; i-- {
1608 m := typ.rtype.Method(i)
1609 res[m.Name] = m.Type.String()
1610 }
1611 case ptrT:
1612 if typ.val.cat == valueT {
1613 // Ptr receiver methods need to be found with the ptr type.
1614 typ.TypeOf() // Ensure the rtype exists.
1615 for i := typ.rtype.NumMethod() - 1; i >= 0; i-- {
1616 m := typ.rtype.Method(i)
1617 res[m.Name] = m.Type.String()
1618 }
1619 }
1620 for k, v := range getMethods(typ.val) {
1621 res[k] = v
1622 }
1623 case structT:
1624 for _, f := range typ.field {
1625 if !f.embed {
1626 continue
1627 }
1628 for k, v := range getMethods(f.typ) {
1629 res[k] = v
1630 }
1631 }
1632 }
1633 // Get all methods defined on this type.
1634 for _, m := range typ.method {
1635 res[m.ident] = m.typ.TypeOf().String()
1636 }
1637 return res
1638 }
1639
1640 return getMethods(t)
1641 }
1642
1643 // id returns a unique type identificator string.
1644 func (t *itype) id() (res string) {
1645 // Prefer the wrapped type string over the rtype string.
1646 if t.cat == valueT && t.val != nil {
1647 return t.val.str
1648 }
1649 return t.str
1650 }
1651
1652 // fixPossibleConstType returns the input type if it not a constant value,
1653 // otherwise, it returns the default Go type corresponding to the
1654 // constant.Value.
1655 func fixPossibleConstType(t reflect.Type) (r reflect.Type) {
1656 cv, ok := reflect.New(t).Elem().Interface().(constant.Value)
1657 if !ok {
1658 return t
1659 }
1660 switch cv.Kind() {
1661 case constant.Bool:
1662 r = reflect.TypeOf(true)
1663 case constant.Int:
1664 r = reflect.TypeOf(0)
1665 case constant.String:
1666 r = reflect.TypeOf("")
1667 case constant.Float:
1668 r = reflect.TypeOf(float64(0))
1669 case constant.Complex:
1670 r = reflect.TypeOf(complex128(0))
1671 }
1672 return r
1673 }
1674
1675 // zero instantiates and return a zero value object for the given type during execution.
1676 func (t *itype) zero() (v reflect.Value, err error) {
1677 if t, err = t.finalize(); err != nil {
1678 return v, err
1679 }
1680 switch t.cat {
1681 case linkedT:
1682 v, err = t.val.zero()
1683
1684 case arrayT, ptrT, structT, sliceT:
1685 v = reflect.New(t.frameType()).Elem()
1686
1687 case valueT:
1688 v = reflect.New(t.rtype).Elem()
1689
1690 default:
1691 v = zeroValues[t.cat]
1692 }
1693 return v, err
1694 }
1695
1696 // fieldIndex returns the field index from name in a struct, or -1 if not found.
1697 func (t *itype) fieldIndex(name string) int {
1698 switch t.cat {
1699 case linkedT, ptrT:
1700 return t.val.fieldIndex(name)
1701 }
1702 for i, field := range t.field {
1703 if name == field.name {
1704 return i
1705 }
1706 }
1707 return -1
1708 }
1709
1710 // fieldSeq returns the field type from the list of field indexes.
1711 func (t *itype) fieldSeq(seq []int) *itype {
1712 ft := t
1713 for _, i := range seq {
1714 ft = baseType(ft).field[i].typ
1715 }
1716 return ft
1717 }
1718
1719 // lookupField returns a list of indices, i.e. a path to access a field in a struct object.
1720 func (t *itype) lookupField(name string) []int {
1721 seen := map[*itype]bool{}
1722 var lookup func(*itype) []int
1723 tias := isStruct(t)
1724
1725 lookup = func(typ *itype) []int {
1726 if seen[typ] {
1727 return nil
1728 }
1729 seen[typ] = true
1730
1731 switch typ.cat {
1732 case linkedT, ptrT:
1733 return lookup(typ.val)
1734 }
1735 if fi := typ.fieldIndex(name); fi >= 0 {
1736 return []int{fi}
1737 }
1738
1739 for i, f := range typ.field {
1740 switch f.typ.cat {
1741 case ptrT, structT, interfaceT, linkedT:
1742 if tias != isStruct(f.typ) {
1743 // Interface fields are not valid embedded struct fields.
1744 // Struct fields are not valid interface fields.
1745 break
1746 }
1747 if index2 := lookup(f.typ); len(index2) > 0 {
1748 return append([]int{i}, index2...)
1749 }
1750 }
1751 }
1752
1753 return nil
1754 }
1755
1756 return lookup(t)
1757 }
1758
1759 // lookupBinField returns a structfield and a path to access an embedded binary field in a struct object.
1760 func (t *itype) lookupBinField(name string) (s reflect.StructField, index []int, ok bool) {
1761 if t.cat == ptrT {
1762 return t.val.lookupBinField(name)
1763 }
1764 if !isStruct(t) {
1765 return
1766 }
1767 rt := t.TypeOf()
1768 for t.cat == valueT && rt.Kind() == reflect.Ptr {
1769 rt = rt.Elem()
1770 }
1771 if rt.Kind() != reflect.Struct {
1772 return
1773 }
1774 s, ok = rt.FieldByName(name)
1775 if !ok {
1776 for i, f := range t.field {
1777 if f.embed {
1778 if s2, index2, ok2 := f.typ.lookupBinField(name); ok2 {
1779 index = append([]int{i}, index2...)
1780 return s2, index, ok2
1781 }
1782 }
1783 }
1784 }
1785 return s, index, ok
1786 }
1787
1788 // MethodCallType returns a method function type without the receiver defined.
1789 // The input type must be a method function type with the receiver as the first input argument.
1790 func (t *itype) methodCallType() reflect.Type {
1791 it := []reflect.Type{}
1792 ni := t.rtype.NumIn()
1793 for i := 1; i < ni; i++ {
1794 it = append(it, t.rtype.In(i))
1795 }
1796 ot := []reflect.Type{}
1797 no := t.rtype.NumOut()
1798 for i := 0; i < no; i++ {
1799 ot = append(ot, t.rtype.Out(i))
1800 }
1801 return reflect.FuncOf(it, ot, t.rtype.IsVariadic())
1802 }
1803
1804 func (t *itype) resolveAlias() *itype {
1805 for t.cat == linkedT {
1806 t = t.val
1807 }
1808 return t
1809 }
1810
1811 // GetMethod returns a pointer to the method definition.
1812 func (t *itype) getMethod(name string) *node {
1813 for _, m := range t.method {
1814 if name == m.ident {
1815 return m
1816 }
1817 }
1818 return nil
1819 }
1820
1821 // LookupMethod returns a pointer to method definition associated to type t
1822 // and the list of indices to access the right struct field, in case of an embedded method.
1823 func (t *itype) lookupMethod(name string) (*node, []int) {
1824 return t.lookupMethod2(name, nil)
1825 }
1826
1827 func (t *itype) lookupMethod2(name string, seen map[*itype]bool) (*node, []int) {
1828 if seen == nil {
1829 seen = map[*itype]bool{}
1830 }
1831 if seen[t] {
1832 return nil, nil
1833 }
1834 seen[t] = true
1835 if t.cat == ptrT {
1836 return t.val.lookupMethod2(name, seen)
1837 }
1838 var index []int
1839 m := t.getMethod(name)
1840 if m == nil {
1841 for i, f := range t.field {
1842 if f.embed {
1843 if n, index2 := f.typ.lookupMethod2(name, seen); n != nil {
1844 index = append([]int{i}, index2...)
1845 return n, index
1846 }
1847 }
1848 }
1849 if t.cat == linkedT || isInterfaceSrc(t) && t.val != nil {
1850 return t.val.lookupMethod2(name, seen)
1851 }
1852 }
1853 return m, index
1854 }
1855
1856 // interfaceMethod returns type of method matching an interface method name (not as a concrete method).
1857 func (t *itype) interfaceMethod(name string) *itype {
1858 return t.interfaceMethod2(name, nil)
1859 }
1860
1861 func (t *itype) interfaceMethod2(name string, seen map[*itype]bool) *itype {
1862 if seen == nil {
1863 seen = map[*itype]bool{}
1864 }
1865 if seen[t] {
1866 return nil
1867 }
1868 seen[t] = true
1869 if t.cat == ptrT {
1870 return t.val.interfaceMethod2(name, seen)
1871 }
1872 for _, f := range t.field {
1873 if f.name == name && isInterface(t) {
1874 return f.typ
1875 }
1876 if !f.embed {
1877 continue
1878 }
1879 if typ := f.typ.interfaceMethod2(name, seen); typ != nil {
1880 return typ
1881 }
1882 }
1883 if t.cat == linkedT || isInterfaceSrc(t) && t.val != nil {
1884 return t.val.interfaceMethod2(name, seen)
1885 }
1886 return nil
1887 }
1888
1889 // methodDepth returns a depth greater or equal to 0, or -1 if no match.
1890 func (t *itype) methodDepth(name string) int {
1891 if m, lint := t.lookupMethod(name); m != nil {
1892 return len(lint)
1893 }
1894 if _, lint, _, ok := t.lookupBinMethod(name); ok {
1895 return len(lint)
1896 }
1897 return -1
1898 }
1899
1900 // LookupBinMethod returns a method and a path to access a field in a struct object (the receiver).
1901 func (t *itype) lookupBinMethod(name string) (m reflect.Method, index []int, isPtr, ok bool) {
1902 return t.lookupBinMethod2(name, nil)
1903 }
1904
1905 func (t *itype) lookupBinMethod2(name string, seen map[*itype]bool) (m reflect.Method, index []int, isPtr, ok bool) {
1906 if seen == nil {
1907 seen = map[*itype]bool{}
1908 }
1909 if seen[t] {
1910 return
1911 }
1912 seen[t] = true
1913 if t.cat == ptrT {
1914 return t.val.lookupBinMethod2(name, seen)
1915 }
1916 for i, f := range t.field {
1917 if f.embed {
1918 if m2, index2, isPtr2, ok2 := f.typ.lookupBinMethod2(name, seen); ok2 {
1919 index = append([]int{i}, index2...)
1920 return m2, index, isPtr2, ok2
1921 }
1922 }
1923 }
1924 m, ok = t.TypeOf().MethodByName(name)
1925 if !ok {
1926 m, ok = reflect.PtrTo(t.TypeOf()).MethodByName(name)
1927 isPtr = ok
1928 }
1929 return m, index, isPtr, ok
1930 }
1931
1932 func lookupFieldOrMethod(t *itype, name string) *itype {
1933 switch {
1934 case t.cat == valueT || t.cat == ptrT && t.val.cat == valueT:
1935 m, _, isPtr, ok := t.lookupBinMethod(name)
1936 if !ok {
1937 return nil
1938 }
1939 var recv *itype
1940 if t.rtype.Kind() != reflect.Interface {
1941 recv = t
1942 if isPtr && t.cat != ptrT && t.rtype.Kind() != reflect.Ptr {
1943 recv = ptrOf(t)
1944 }
1945 }
1946 return valueTOf(m.Type, withRecv(recv))
1947 case t.cat == interfaceT:
1948 seq := t.lookupField(name)
1949 if seq == nil {
1950 return nil
1951 }
1952 return t.fieldSeq(seq)
1953 default:
1954 n, _ := t.lookupMethod(name)
1955 if n == nil {
1956 return nil
1957 }
1958 return n.typ
1959 }
1960 }
1961
1962 func exportName(s string) string {
1963 if canExport(s) {
1964 return s
1965 }
1966 return "X" + s
1967 }
1968
1969 var (
1970 // TODO(mpl): generators.
1971 emptyInterfaceType = reflect.TypeOf((*interface{})(nil)).Elem()
1972 valueInterfaceType = reflect.TypeOf((*valueInterface)(nil)).Elem()
1973 constVal = reflect.TypeOf((*constant.Value)(nil)).Elem()
1974 )
1975
1976 type refTypeContext struct {
1977 defined map[string]*itype
1978
1979 // refs keeps track of all the places (in the same type recursion) where the
1980 // type name (as key) is used as a field of another (or possibly the same) struct
1981 // type. Each of these fields will then live as an unsafe2.dummy type until the
1982 // whole recursion is fully resolved, and the type is fixed.
1983 refs map[string][]*itype
1984
1985 // When we detect for the first time that we are in a recursive type (thanks to
1986 // defined), we keep track of the first occurrence of the type where the recursion
1987 // started, so we can restart the last step that fixes all the types from the same
1988 // "top-level" point.
1989 rect *itype
1990 rebuilding bool
1991 slevel int
1992 }
1993
1994 // Clone creates a copy of the ref type context.
1995 func (c *refTypeContext) Clone() *refTypeContext {
1996 return &refTypeContext{defined: c.defined, refs: c.refs, rebuilding: c.rebuilding}
1997 }
1998
1999 func (c *refTypeContext) isComplete() bool {
2000 for _, t := range c.defined {
2001 if t.rtype == nil {
2002 return false
2003 }
2004 }
2005 return true
2006 }
2007
2008 func (t *itype) fixDummy(typ reflect.Type) reflect.Type {
2009 if typ == unsafe2.DummyType {
2010 return t.rtype
2011 }
2012 switch typ.Kind() {
2013 case reflect.Array:
2014 return reflect.ArrayOf(typ.Len(), t.fixDummy(typ.Elem()))
2015 case reflect.Chan:
2016 return reflect.ChanOf(typ.ChanDir(), t.fixDummy(typ.Elem()))
2017 case reflect.Func:
2018 in := make([]reflect.Type, typ.NumIn())
2019 for i := range in {
2020 in[i] = t.fixDummy(typ.In(i))
2021 }
2022 out := make([]reflect.Type, typ.NumOut())
2023 for i := range out {
2024 out[i] = t.fixDummy(typ.Out(i))
2025 }
2026 return reflect.FuncOf(in, out, typ.IsVariadic())
2027 case reflect.Map:
2028 return reflect.MapOf(t.fixDummy(typ.Key()), t.fixDummy(typ.Elem()))
2029 case reflect.Ptr:
2030 return reflect.PtrTo(t.fixDummy(typ.Elem()))
2031 case reflect.Slice:
2032 return reflect.SliceOf(t.fixDummy(typ.Elem()))
2033 case reflect.Struct:
2034 fields := make([]reflect.StructField, typ.NumField())
2035 for i := range fields {
2036 fields[i] = typ.Field(i)
2037 fields[i].Type = t.fixDummy(fields[i].Type)
2038 }
2039 return reflect.StructOf(fields)
2040 }
2041 return typ
2042 }
2043
2044 // RefType returns a reflect.Type representation from an interpreter type.
2045 // In simple cases, reflect types are directly mapped from the interpreter
2046 // counterpart.
2047 // For recursive named struct or interfaces, as reflect does not permit to
2048 // create a recursive named struct, a dummy type is set temporarily for each recursive
2049 // field. When done, the dummy type fields are updated with the original reflect type
2050 // pointer using unsafe. We thus obtain a usable recursive type definition, except
2051 // for string representation, as created reflect types are still unnamed.
2052 func (t *itype) refType(ctx *refTypeContext) reflect.Type {
2053 if ctx == nil {
2054 ctx = &refTypeContext{
2055 defined: map[string]*itype{},
2056 refs: map[string][]*itype{},
2057 }
2058 }
2059 if t.incomplete || t.cat == nilT {
2060 var err error
2061 if t, err = t.finalize(); err != nil {
2062 panic(err)
2063 }
2064 }
2065 name := t.path + "/" + t.name
2066
2067 if t.rtype != nil && !ctx.rebuilding {
2068 return t.rtype
2069 }
2070 if dt := ctx.defined[name]; dt != nil {
2071 // We get here when we are a struct field, and our type name has already been
2072 // seen at least once in one of our englobing structs. i.e. there's at least one
2073 // level of type recursion.
2074 if dt.rtype != nil {
2075 t.rtype = dt.rtype
2076 return dt.rtype
2077 }
2078
2079 // The recursion has not been fully resolved yet.
2080 // To indicate that a rebuild is needed on the englobing struct,
2081 // return a dummy field type and create an empty entry.
2082 flds := ctx.refs[name]
2083 ctx.rect = dt
2084
2085 // We know we are used as a field by someone, but we don't know by who
2086 // at this point in the code, so we just mark it as an empty *itype for now.
2087 // We'll complete the *itype in the caller.
2088 ctx.refs[name] = append(flds, (*itype)(nil))
2089 return unsafe2.DummyType
2090 }
2091 if isGeneric(t) {
2092 return reflect.TypeOf((*generic)(nil)).Elem()
2093 }
2094 switch t.cat {
2095 case linkedT:
2096 t.rtype = t.val.refType(ctx)
2097 case arrayT:
2098 t.rtype = reflect.ArrayOf(t.length, t.val.refType(ctx))
2099 case sliceT, variadicT:
2100 t.rtype = reflect.SliceOf(t.val.refType(ctx))
2101 case chanT:
2102 t.rtype = reflect.ChanOf(reflect.BothDir, t.val.refType(ctx))
2103 case chanRecvT:
2104 t.rtype = reflect.ChanOf(reflect.RecvDir, t.val.refType(ctx))
2105 case chanSendT:
2106 t.rtype = reflect.ChanOf(reflect.SendDir, t.val.refType(ctx))
2107 case errorT:
2108 t.rtype = reflect.TypeOf(new(error)).Elem()
2109 case funcT:
2110 variadic := false
2111 in := make([]reflect.Type, len(t.arg))
2112 out := make([]reflect.Type, len(t.ret))
2113 for i, v := range t.arg {
2114 in[i] = v.refType(ctx)
2115 variadic = v.cat == variadicT
2116 }
2117 for i, v := range t.ret {
2118 out[i] = v.refType(ctx)
2119 }
2120 t.rtype = reflect.FuncOf(in, out, variadic)
2121 case interfaceT:
2122 if len(t.field) == 0 {
2123 // empty interface, do not wrap it
2124 t.rtype = emptyInterfaceType
2125 break
2126 }
2127 t.rtype = valueInterfaceType
2128 case mapT:
2129 t.rtype = reflect.MapOf(t.key.refType(ctx), t.val.refType(ctx))
2130 case ptrT:
2131 rt := t.val.refType(ctx)
2132 if rt == unsafe2.DummyType && ctx.slevel > 1 {
2133 // We have a pointer to a recursive struct which is not yet fully computed.
2134 // Return it but do not yet store it in rtype, so the complete version can
2135 // be stored in future.
2136 return reflect.PtrTo(rt)
2137 }
2138 t.rtype = reflect.PtrTo(rt)
2139 case structT:
2140 if t.name != "" {
2141 ctx.defined[name] = t
2142 }
2143 ctx.slevel++
2144 var fields []reflect.StructField
2145 for _, f := range t.field {
2146 field := reflect.StructField{
2147 Name: exportName(f.name),
2148 Type: f.typ.refType(ctx),
2149 Tag: reflect.StructTag(f.tag),
2150 }
2151 if len(t.field) == 1 && f.embed {
2152 // Mark the field as embedded (anonymous) only if it is the
2153 // only one, to avoid a panic due to golang/go#15924 issue.
2154 field.Anonymous = true
2155 }
2156 fields = append(fields, field)
2157 // Find any nil type refs that indicates a rebuild is needed on this field.
2158 for _, flds := range ctx.refs {
2159 for j, fld := range flds {
2160 if fld == nil {
2161 flds[j] = t
2162 }
2163 }
2164 }
2165 }
2166 ctx.slevel--
2167 type fixStructField struct {
2168 name string
2169 index int
2170 }
2171 fieldFix := []fixStructField{} // Slice of field indices to fix for recursivity.
2172 t.rtype = reflect.StructOf(fields)
2173 if ctx.isComplete() {
2174 for _, s := range ctx.defined {
2175 for i := 0; i < s.rtype.NumField(); i++ {
2176 f := s.rtype.Field(i)
2177 if strings.HasSuffix(f.Type.String(), "unsafe2.dummy") {
2178 unsafe2.SetFieldType(s.rtype, i, ctx.rect.fixDummy(s.rtype.Field(i).Type))
2179 if name == s.path+"/"+s.name {
2180 fieldFix = append(fieldFix, fixStructField{s.name, i})
2181 }
2182 continue
2183 }
2184 if f.Type.Kind() == reflect.Func && strings.Contains(f.Type.String(), "unsafe2.dummy") {
2185 fieldFix = append(fieldFix, fixStructField{s.name, i})
2186 }
2187 }
2188 }
2189 }
2190
2191 // The rtype has now been built, we can go back and rebuild
2192 // all the recursive types that relied on this type.
2193 // However, as we are keyed by type name, if two or more (recursive) fields at
2194 // the same depth level are of the same type, or a "variation" of the same type
2195 // (slice of, map of, etc), they "mask" each other, and only one
2196 // of them is in ctx.refs. That is why the code around here is a bit convoluted,
2197 // and we need both the loop above, around all the struct fields, and the loop
2198 // below, around the ctx.refs.
2199 for _, f := range ctx.refs[name] {
2200 for _, ff := range fieldFix {
2201 if ff.name == f.name {
2202 ftyp := f.field[ff.index].typ.refType(&refTypeContext{defined: ctx.defined, rebuilding: true})
2203 unsafe2.SetFieldType(f.rtype, ff.index, ftyp)
2204 }
2205 }
2206 }
2207 default:
2208 if z, _ := t.zero(); z.IsValid() {
2209 t.rtype = z.Type()
2210 }
2211 }
2212 return t.rtype
2213 }
2214
2215 // TypeOf returns the reflection type of dynamic interpreter type t.
2216 func (t *itype) TypeOf() reflect.Type {
2217 return t.refType(nil)
2218 }
2219
2220 func (t *itype) frameType() (r reflect.Type) {
2221 var err error
2222 if t, err = t.finalize(); err != nil {
2223 panic(err)
2224 }
2225 switch t.cat {
2226 case linkedT:
2227 r = t.val.frameType()
2228 case arrayT:
2229 r = reflect.ArrayOf(t.length, t.val.frameType())
2230 case sliceT, variadicT:
2231 r = reflect.SliceOf(t.val.frameType())
2232 case interfaceT:
2233 if len(t.field) == 0 {
2234 // empty interface, do not wrap it
2235 r = emptyInterfaceType
2236 break
2237 }
2238 r = valueInterfaceType
2239 case mapT:
2240 r = reflect.MapOf(t.key.frameType(), t.val.frameType())
2241 case ptrT:
2242 r = reflect.PtrTo(t.val.frameType())
2243 default:
2244 r = t.TypeOf()
2245 }
2246 return r
2247 }
2248
2249 func (t *itype) implements(it *itype) bool {
2250 if isBin(t) {
2251 // Note: in case of a valueInterfaceType, we
2252 // miss required data which will be available
2253 // later, so we optimistically return true to progress,
2254 // and additional checks will be hopefully performed at
2255 // runtime.
2256 if rt := it.TypeOf(); rt == valueInterfaceType {
2257 return true
2258 }
2259 return t.TypeOf().Implements(it.TypeOf())
2260 }
2261 return t.methods().contains(it.methods())
2262 }
2263
2264 // defaultType returns the default type of an untyped type.
2265 func (t *itype) defaultType(v reflect.Value, sc *scope) *itype {
2266 if !t.untyped {
2267 return t
2268 }
2269
2270 typ := t
2271 // The default type can also be derived from a constant value.
2272 if v.IsValid() && v.Type().Implements(constVal) {
2273 switch v.Interface().(constant.Value).Kind() {
2274 case constant.String:
2275 typ = sc.getType("string")
2276 case constant.Bool:
2277 typ = sc.getType("bool")
2278 case constant.Int:
2279 switch t.cat {
2280 case int32T:
2281 typ = sc.getType("int32")
2282 default:
2283 typ = sc.getType("int")
2284 }
2285 case constant.Float:
2286 typ = sc.getType("float64")
2287 case constant.Complex:
2288 typ = sc.getType("complex128")
2289 }
2290 }
2291 if typ.untyped {
2292 switch t.cat {
2293 case stringT:
2294 typ = sc.getType("string")
2295 case boolT:
2296 typ = sc.getType("bool")
2297 case intT:
2298 typ = sc.getType("int")
2299 case float64T:
2300 typ = sc.getType("float64")
2301 case complex128T:
2302 typ = sc.getType("complex128")
2303 default:
2304 *typ = *t
2305 typ.untyped = false
2306 }
2307 }
2308 return typ
2309 }
2310
2311 func (t *itype) isNil() bool { return t.cat == nilT }
2312
2313 func (t *itype) hasNil() bool {
2314 switch rt := t.TypeOf(); rt.Kind() {
2315 case reflect.UnsafePointer:
2316 return true
2317 case reflect.Slice, reflect.Ptr, reflect.Func, reflect.Interface, reflect.Map, reflect.Chan:
2318 return true
2319 case reflect.Struct:
2320 if rt == valueInterfaceType {
2321 return true
2322 }
2323 }
2324 return false
2325 }
2326
2327 func (t *itype) elem() *itype {
2328 if t.cat == valueT {
2329 return valueTOf(t.rtype.Elem())
2330 }
2331 return t.val
2332 }
2333
2334 func hasElem(t reflect.Type) bool {
2335 switch t.Kind() {
2336 case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
2337 return true
2338 }
2339 return false
2340 }
2341
2342 func constToInt(c constant.Value) int {
2343 if constant.BitLen(c) > 64 {
2344 panic(fmt.Sprintf("constant %s overflows int64", c.ExactString()))
2345 }
2346 i, _ := constant.Int64Val(c)
2347 return int(i)
2348 }
2349
2350 func constToString(v reflect.Value) string {
2351 c := v.Interface().(constant.Value)
2352 return constant.StringVal(c)
2353 }
2354
2355 func wrappedType(n *node) *itype {
2356 if n.typ.cat != valueT {
2357 return nil
2358 }
2359 return n.typ.val
2360 }
2361
2362 func isShiftNode(n *node) bool {
2363 switch n.action {
2364 case aShl, aShr, aShlAssign, aShrAssign:
2365 return true
2366 }
2367 return false
2368 }
2369
2370 // chanElement returns the channel element type.
2371 func chanElement(t *itype) *itype {
2372 switch t.cat {
2373 case linkedT:
2374 return chanElement(t.val)
2375 case chanT, chanSendT, chanRecvT:
2376 return t.val
2377 case valueT:
2378 return valueTOf(t.rtype.Elem(), withNode(t.node), withScope(t.scope))
2379 }
2380 return nil
2381 }
2382
2383 func isBool(t *itype) bool { return t.TypeOf().Kind() == reflect.Bool }
2384 func isChan(t *itype) bool { return t.TypeOf().Kind() == reflect.Chan }
2385 func isFunc(t *itype) bool { return t.TypeOf().Kind() == reflect.Func }
2386 func isMap(t *itype) bool { return t.TypeOf().Kind() == reflect.Map }
2387 func isPtr(t *itype) bool { return t.TypeOf().Kind() == reflect.Ptr }
2388
2389 func isEmptyInterface(t *itype) bool {
2390 return t != nil && t.cat == interfaceT && len(t.field) == 0
2391 }
2392
2393 func isGeneric(t *itype) bool {
2394 return t.cat == funcT && t.node != nil && len(t.node.child) > 0 && len(t.node.child[0].child) > 0
2395 }
2396
2397 func isNamedFuncSrc(t *itype) bool {
2398 return isFuncSrc(t) && t.node.anc.kind == funcDecl
2399 }
2400
2401 func isFuncSrc(t *itype) bool {
2402 return t.cat == funcT || (t.cat == linkedT && isFuncSrc(t.val))
2403 }
2404
2405 func isPtrSrc(t *itype) bool {
2406 return t.cat == ptrT || (t.cat == linkedT && isPtrSrc(t.val))
2407 }
2408
2409 func isSendChan(t *itype) bool {
2410 rt := t.TypeOf()
2411 return rt.Kind() == reflect.Chan && rt.ChanDir() == reflect.SendDir
2412 }
2413
2414 func isArray(t *itype) bool {
2415 if t.cat == nilT {
2416 return false
2417 }
2418 k := t.TypeOf().Kind()
2419 return k == reflect.Array || k == reflect.Slice
2420 }
2421
2422 func isInterfaceSrc(t *itype) bool {
2423 return t.cat == interfaceT || (t.cat == linkedT && isInterfaceSrc(t.val))
2424 }
2425
2426 func isInterfaceBin(t *itype) bool {
2427 return t.cat == valueT && t.rtype.Kind() == reflect.Interface || t.cat == errorT
2428 }
2429
2430 func isInterface(t *itype) bool {
2431 return isInterfaceSrc(t) || t.TypeOf() == valueInterfaceType || t.TypeOf() != nil && t.TypeOf().Kind() == reflect.Interface
2432 }
2433
2434 func isBin(t *itype) bool {
2435 switch t.cat {
2436 case valueT:
2437 return true
2438 case linkedT, ptrT:
2439 return isBin(t.val)
2440 default:
2441 return false
2442 }
2443 }
2444
2445 func isStruct(t *itype) bool {
2446 // Test first for a struct category, because a recursive interpreter struct may be
2447 // represented by an interface{} at reflect level.
2448 switch t.cat {
2449 case structT:
2450 return true
2451 case linkedT, ptrT:
2452 return isStruct(t.val)
2453 case valueT:
2454 k := t.rtype.Kind()
2455 return k == reflect.Struct || (k == reflect.Ptr && t.rtype.Elem().Kind() == reflect.Struct)
2456 default:
2457 return false
2458 }
2459 }
2460
2461 func isConstType(t *itype) bool {
2462 rt := t.TypeOf()
2463 return isBoolean(rt) || isString(rt) || isNumber(rt)
2464 }
2465
2466 func isInt(t reflect.Type) bool {
2467 if t == nil {
2468 return false
2469 }
2470 switch t.Kind() {
2471 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
2472 return true
2473 }
2474 return false
2475 }
2476
2477 func isUint(t reflect.Type) bool {
2478 if t == nil {
2479 return false
2480 }
2481 switch t.Kind() {
2482 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
2483 return true
2484 }
2485 return false
2486 }
2487
2488 func isComplex(t reflect.Type) bool {
2489 if t == nil {
2490 return false
2491 }
2492 switch t.Kind() {
2493 case reflect.Complex64, reflect.Complex128:
2494 return true
2495 }
2496 return false
2497 }
2498
2499 func isFloat(t reflect.Type) bool {
2500 if t == nil {
2501 return false
2502 }
2503 switch t.Kind() {
2504 case reflect.Float32, reflect.Float64:
2505 return true
2506 }
2507 return false
2508 }
2509
2510 func isByteArray(t reflect.Type) bool {
2511 if t == nil {
2512 return false
2513 }
2514 k := t.Kind()
2515 return (k == reflect.Array || k == reflect.Slice) && t.Elem().Kind() == reflect.Uint8
2516 }
2517
2518 func isFloat32(t reflect.Type) bool { return t != nil && t.Kind() == reflect.Float32 }
2519 func isFloat64(t reflect.Type) bool { return t != nil && t.Kind() == reflect.Float64 }
2520 func isNumber(t reflect.Type) bool {
2521 return isInt(t) || isFloat(t) || isComplex(t) || isConstantValue(t)
2522 }
2523 func isBoolean(t reflect.Type) bool { return t != nil && t.Kind() == reflect.Bool }
2524 func isString(t reflect.Type) bool { return t != nil && t.Kind() == reflect.String }
2525 func isConstantValue(t reflect.Type) bool { return t != nil && t.Implements(constVal) }