gitlab.com/ethan.reesor/vscode-notebooks/yaegi@v0.0.0-20220417214422-5c573557938e/interp/type.go (about)

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