package interp

import (
	
	
	
	
	
	

	
)

// tcat defines interpreter type categories.
type tcat uint

// Types for go language.
const (
	nilT tcat = iota
	arrayT
	binT
	binPkgT
	boolT
	builtinT
	chanT
	chanSendT
	chanRecvT
	comparableT
	complex64T
	complex128T
	constraintT
	errorT
	float32T
	float64T
	funcT
	genericT
	interfaceT
	intT
	int8T
	int16T
	int32T
	int64T
	linkedT
	mapT
	ptrT
	sliceT
	srcPkgT
	stringT
	structT
	uintT
	uint8T
	uint16T
	uint32T
	uint64T
	uintptrT
	valueT
	variadicT
	maxT
)

var cats = [...]string{
	nilT:        "nilT",
	arrayT:      "arrayT",
	binT:        "binT",
	binPkgT:     "binPkgT",
	boolT:       "boolT",
	builtinT:    "builtinT",
	chanT:       "chanT",
	comparableT: "comparableT",
	complex64T:  "complex64T",
	complex128T: "complex128T",
	constraintT: "constraintT",
	errorT:      "errorT",
	float32T:    "float32",
	float64T:    "float64T",
	funcT:       "funcT",
	genericT:    "genericT",
	interfaceT:  "interfaceT",
	intT:        "intT",
	int8T:       "int8T",
	int16T:      "int16T",
	int32T:      "int32T",
	int64T:      "int64T",
	linkedT:     "linkedT",
	mapT:        "mapT",
	ptrT:        "ptrT",
	sliceT:      "sliceT",
	srcPkgT:     "srcPkgT",
	stringT:     "stringT",
	structT:     "structT",
	uintT:       "uintT",
	uint8T:      "uint8T",
	uint16T:     "uint16T",
	uint32T:     "uint32T",
	uint64T:     "uint64T",
	uintptrT:    "uintptrT",
	valueT:      "valueT",
	variadicT:   "variadicT",
}

func ( tcat) () string {
	if  < tcat(len(cats)) {
		return cats[]
	}
	return "Cat(" + strconv.Itoa(int()) + ")"
}

// structField type defines a field in a struct.
type structField struct {
	name  string
	tag   string
	embed bool
	typ   *itype
}

// itype defines the internal representation of types in the interpreter.
type itype struct {
	cat          tcat          // Type category
	field        []structField // Array of struct fields if structT or interfaceT
	key          *itype        // Type of key element if MapT or nil
	val          *itype        // Type of value element if chanT, chanSendT, chanRecvT, mapT, ptrT, linkedT, arrayT, sliceT, variadicT or genericT
	recv         *itype        // Receiver type for funcT or nil
	arg          []*itype      // Argument types if funcT or nil
	ret          []*itype      // Return types if funcT or nil
	ptr          *itype        // Pointer to this type. Might be nil
	method       []*node       // Associated methods or nil
	constraint   []*itype      // For interfaceT: list of types part of interface set
	ulconstraint []*itype      // For interfaceT: list of underlying types part of interface set
	instance     []*itype      // For genericT: list of instantiated types
	name         string        // name of type within its package for a defined type
	path         string        // for a defined type, the package import path
	length       int           // length of array if ArrayT
	rtype        reflect.Type  // Reflection type if ValueT, or nil
	node         *node         // root AST node of type definition
	scope        *scope        // type declaration scope (in case of re-parse incomplete type)
	str          string        // String representation of the type
	incomplete   bool          // true if type must be parsed again (out of order declarations)
	untyped      bool          // true for a literal value (string or number)
	isBinMethod  bool          // true if the type refers to a bin method function
}

type generic struct{}

func untypedBool( *node) *itype {
	return &itype{cat: boolT, name: "bool", untyped: true, str: "untyped bool", node: }
}

func untypedString( *node) *itype {
	return &itype{cat: stringT, name: "string", untyped: true, str: "untyped string", node: }
}

func untypedRune( *node) *itype {
	return &itype{cat: int32T, name: "int32", untyped: true, str: "untyped rune", node: }
}

func untypedInt( *node) *itype {
	return &itype{cat: intT, name: "int", untyped: true, str: "untyped int", node: }
}

func untypedFloat( *node) *itype {
	return &itype{cat: float64T, name: "float64", untyped: true, str: "untyped float", node: }
}

func untypedComplex( *node) *itype {
	return &itype{cat: complex128T, name: "complex128", untyped: true, str: "untyped complex", node: }
}

func errorMethodType( *scope) *itype {
	return &itype{cat: funcT, ret: []*itype{.getType("string")}, str: "func() string"}
}

type itypeOption func(*itype)

func isBinMethod() itypeOption {
	return func( *itype) {
		.isBinMethod = true
	}
}

func withRecv( *itype) itypeOption {
	return func( *itype) {
		.recv = 
	}
}

func withNode( *node) itypeOption {
	return func( *itype) {
		.node = 
	}
}

func withScope( *scope) itypeOption {
	return func( *itype) {
		.scope = 
	}
}

func withUntyped( bool) itypeOption {
	return func( *itype) {
		.untyped = 
	}
}

// valueTOf returns a valueT itype.
func valueTOf( reflect.Type,  ...itypeOption) *itype {
	 := &itype{cat: valueT, rtype: , str: .String()}
	for ,  := range  {
		()
	}
	if .untyped {
		.str = "untyped " + .str
	}
	return 
}

// wrapperValueTOf returns a valueT itype wrapping an itype.
func wrapperValueTOf( reflect.Type,  *itype,  ...itypeOption) *itype {
	 := &itype{cat: valueT, rtype: , val: , str: .String()}
	for ,  := range  {
		()
	}
	return 
}

func variadicOf( *itype,  ...itypeOption) *itype {
	 := &itype{cat: variadicT, val: , str: "..." + .str}
	for ,  := range  {
		()
	}
	return 
}

// ptrOf returns a pointer to t.
func ptrOf( *itype,  ...itypeOption) *itype {
	if .ptr != nil {
		return .ptr
	}
	 := &itype{cat: ptrT, val: , str: "*" + .str}
	for ,  := range  {
		()
	}
	.ptr = 
	return 
}

// namedOf returns a named type of val.
func namedOf( *itype, ,  string,  ...itypeOption) *itype {
	 := 
	if  != "" {
		 =  + "." + 
	}
	 := &itype{cat: linkedT, val: , path: , name: , str: }
	for ,  := range  {
		()
	}
	return 
}

// funcOf returns a function type with the given args and returns.
func funcOf( []*itype,  []*itype,  ...itypeOption) *itype {
	 := []byte{}
	 = append(, "func("...)
	 = append(, paramsTypeString()...)
	 = append(, ')')
	if len() != 0 {
		 = append(, ' ')
		if len() > 1 {
			 = append(, '(')
		}
		 = append(, paramsTypeString()...)
		if len() > 1 {
			 = append(, ')')
		}
	}

	 := &itype{cat: funcT, arg: , ret: , str: string()}
	for ,  := range  {
		()
	}
	return 
}

type chanDir uint8

const (
	chanSendRecv chanDir = iota
	chanSend
	chanRecv
)

// chanOf returns a channel of the underlying type val.
func chanOf( *itype,  chanDir,  ...itypeOption) *itype {
	 := chanT
	 := "chan "
	switch  {
	case chanSend:
		 = chanSendT
		 = "chan<- "
	case chanRecv:
		 = chanRecvT
		 = "<-chan "
	}
	 := &itype{cat: , val: , str:  + .str}
	for ,  := range  {
		()
	}
	return 
}

// arrayOf returns am array type of the underlying val with the given length.
func arrayOf( *itype,  int,  ...itypeOption) *itype {
	 := strconv.Itoa()
	 := &itype{cat: arrayT, val: , length: , str: "[" +  + "]" + .str}
	for ,  := range  {
		()
	}
	return 
}

// sliceOf returns a slice type of the underlying val.
func sliceOf( *itype,  ...itypeOption) *itype {
	 := &itype{cat: sliceT, val: , str: "[]" + .str}
	for ,  := range  {
		()
	}
	return 
}

// mapOf returns a map type of the underlying key and val.
func mapOf(,  *itype,  ...itypeOption) *itype {
	 := &itype{cat: mapT, key: , val: , str: "map[" + .str + "]" + .str}
	for ,  := range  {
		()
	}
	return 
}

// interfaceOf returns an interface type with the given fields.
func interfaceOf( *itype,  []structField, ,  []*itype,  ...itypeOption) *itype {
	 := "interface{}"
	if len() > 0 {
		 = "interface { " + methodsTypeString() + "}"
	}
	if  == nil {
		 = &itype{}
	}
	.cat = interfaceT
	.field = 
	.constraint = 
	.ulconstraint = 
	.str = 
	for ,  := range  {
		()
	}
	return 
}

// structOf returns a struct type with the given fields.
func structOf( *itype,  []structField,  ...itypeOption) *itype {
	 := "struct {}"
	if len() > 0 {
		 = "struct { " + fieldsTypeString() + "}"
	}
	if  == nil {
		 = &itype{}
	}
	.cat = structT
	.field = 
	.str = 
	for ,  := range  {
		()
	}
	return 
}

// genericOf returns a generic type.
func genericOf( *itype, ,  string,  ...itypeOption) *itype {
	 := &itype{cat: genericT, name: , path: , str: , val: }
	for ,  := range  {
		()
	}
	return 
}

// seenNode determines if a node has been seen.
//
// seenNode treats the slice of nodes as the path traveled down a node
// tree.
func seenNode( []*node,  *node) bool {
	for ,  := range  {
		if  ==  {
			return true
		}
	}
	return false
}

// nodeType returns a type definition for the corresponding AST subtree.
func nodeType( *Interpreter,  *scope,  *node) (*itype, error) {
	return nodeType2(, , , nil)
}

func nodeType2( *Interpreter,  *scope,  *node,  []*node) ( *itype,  error) {
	if .typ != nil && !.typ.incomplete {
		return .typ, nil
	}
	if  := typeName();  != "" {
		, ,  := .lookup()
		if  && .kind == typeSym && .typ != nil {
			if .typ.isComplete() {
				return .typ, nil
			}
			if seenNode(, ) {
				// We have seen this node in our tree, so it must be recursive.
				.typ.incomplete = false
				return .typ, nil
			}
		}
	}
	 = append(, )
	defer func() {  = [:len()-1] }()

	switch .kind {
	case addressExpr, starExpr:
		,  := (, , .child[0], )
		if  != nil {
			return nil, 
		}
		 = ptrOf(, withNode(), withScope())
		.incomplete = .incomplete

	case arrayType:
		 := .child[0]
		if len(.child) == 1 {
			,  := (, , , )
			if  != nil {
				return nil, 
			}
			 = sliceOf(, withNode(), withScope())
			.incomplete = .incomplete
			break
		}
		// Array size is defined.
		var (
			     int
			 bool
		)
		switch  := .rval; {
		case .IsValid():
			// Size if defined by a constant literal value.
			if isConstantValue(.Type()) {
				 := .Interface().(constant.Value)
				 = constToInt()
			} else {
				switch .Type().Kind() {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					 = int(.Int())
				case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
					 = int(.Uint())
				default:
					return nil, .cfgErrorf("non integer constant %v", )
				}
			}
		case .kind == ellipsisExpr:
			// [...]T expression, get size from the length of composite array.
			,  = arrayTypeLen(.anc, )
			if  != nil {
				 = true
			}
		case .kind == identExpr:
			, ,  := .lookup(.ident)
			if ! {
				 = true
				break
			}
			// Size is defined by a symbol which must be a constant integer.
			if .kind != constSym {
				return nil, .cfgErrorf("non-constant array bound %q", .ident)
			}
			if .typ == nil || !isInt(.typ.TypeOf()) || !.rval.IsValid() {
				 = true
				break
			}
			 = int(vInt(.rval))
		default:
			// Size is defined by a numeric constant expression.
			var  bool
			if ,  := .cfg(, , .pkgID, .pkgName);  != nil {
				if strings.Contains(.Error(), " undefined: ") {
					 = true
					break
				}
				return nil, 
			}
			if !.rval.IsValid() {
				return nil, .cfgErrorf("undefined array size")
			}
			if ,  = .rval.Interface().(int); ! {
				,  := .rval.Interface().(constant.Value)
				if ! {
					 = true
					break
				}
				 = constToInt()
			}
		}
		,  := (, , .child[1], )
		if  != nil {
			return nil, 
		}
		 = arrayOf(, , withNode(), withScope())
		.incomplete =  || .incomplete

	case basicLit:
		switch v := .rval.Interface().(type) {
		case bool:
			.rval = reflect.ValueOf(constant.MakeBool())
			 = untypedBool()
		case rune:
			// It is impossible to work out rune const literals in AST
			// with the correct type so we must make the const type here.
			.rval = reflect.ValueOf(constant.MakeInt64(int64()))
			 = untypedRune()
		case constant.Value:
			switch .Kind() {
			case constant.Bool:
				 = untypedBool()
			case constant.String:
				 = untypedString()
			case constant.Int:
				 = untypedInt()
			case constant.Float:
				 = untypedFloat()
			case constant.Complex:
				 = untypedComplex()
			default:
				 = .cfgErrorf("missing support for type %v", .rval)
			}
		default:
			 = .cfgErrorf("missing support for type %T: %v", , .rval)
		}

	case unaryExpr:
		// In interfaceType, we process an underlying type constraint definition.
		if isInInterfaceType() {
			,  := (, , .child[0], )
			if  != nil {
				return nil, 
			}
			 = &itype{cat: constraintT, ulconstraint: []*itype{}}
			break
		}
		,  = (, , .child[0], )

	case binaryExpr:
		// In interfaceType, we process a type constraint union definition.
		if isInInterfaceType() {
			 = &itype{cat: constraintT, constraint: []*itype{}, ulconstraint: []*itype{}}
			for ,  := range .child {
				,  := (, , , )
				if  != nil {
					return nil, 
				}
				switch .cat {
				case constraintT:
					.constraint = append(.constraint, .constraint...)
					.ulconstraint = append(.ulconstraint, .ulconstraint...)
				default:
					.constraint = append(.constraint, )
				}
			}
			break
		}
		// Get type of first operand.
		if ,  = (, , .child[0], );  != nil {
			return nil, 
		}
		// For operators other than shift, get the type from the 2nd operand if the first is untyped.
		if .untyped && !isShiftNode() {
			var  *itype
			,  = (, , .child[1], )
			if !(.untyped && isInt(.TypeOf()) && isFloat(.TypeOf())) {
				 = 
			}
		}

		// If the node is to be assigned or returned, the node type is the destination type.
		 := 

		switch  := .anc; {
		case .kind == assignStmt && isEmptyInterface(.child[0].typ):
			// Because an empty interface concrete type "mutates" as different values are
			// assigned to it, we need to make a new itype from scratch everytime a new
			// assignment is made, and not let different nodes (of the same variable) share the
			// same itype. Otherwise they would overwrite each other.
			.child[0].typ = &itype{cat: interfaceT, val: , str: "interface{}"}

		case .kind == defineStmt && len(.child) > .nleft+.nright:
			if ,  = (, , .child[.nleft], );  != nil {
				return nil, 
			}

		case .kind == returnStmt:
			 = .def.typ.ret[childPos()]
		}

		if isInterfaceSrc() {
			// Set a new interface type preserving the concrete type (.val field).
			 := *
			.val = 
			 = &
		}
		 = 

	case callExpr:
		if isBuiltinCall(, ) {
			// Builtin types are special and may depend from their input arguments.
			switch .child[0].ident {
			case bltnComplex:
				var ,  *itype
				if ,  = (, , .child[1], );  != nil {
					return nil, 
				}
				if ,  = (, , .child[2], );  != nil {
					return nil, 
				}
				if .incomplete || .incomplete {
					.incomplete = true
				} else {
					switch ,  := .TypeOf(), .TypeOf(); {
					case isFloat32() && isFloat32():
						 = .getType("complex64")
					case isFloat64() && isFloat64():
						 = .getType("complex128")
					case .untyped && isNumber() && .untyped && isNumber():
						 = untypedComplex()
					case .untyped && isFloat32() || .untyped && isFloat32():
						 = .getType("complex64")
					case .untyped && isFloat64() || .untyped && isFloat64():
						 = .getType("complex128")
					default:
						 = .cfgErrorf("invalid types %s and %s", .Kind(), .Kind())
					}
					if .untyped && .untyped {
						 = untypedComplex()
					}
				}
			case bltnReal, bltnImag:
				if ,  = (, , .child[1], );  != nil {
					return nil, 
				}
				if !.incomplete {
					switch  := .TypeOf().Kind(); {
					case .untyped && isNumber(.TypeOf()):
						 = untypedFloat()
					case  == reflect.Complex64:
						 = .getType("float32")
					case  == reflect.Complex128:
						 = .getType("float64")
					default:
						 = .cfgErrorf("invalid complex type %s", )
					}
				}
			case bltnCap, bltnCopy, bltnLen:
				 = .getType("int")
			case bltnAppend, bltnMake:
				,  = (, , .child[1], )
			case bltnNew:
				,  = (, , .child[1], )
				 := .incomplete
				 = ptrOf(, withScope())
				.incomplete = 
			case bltnRecover:
				 = .getType("interface{}")
			default:
				 = &itype{cat: builtinT}
			}
			if  != nil {
				return nil, 
			}
		} else {
			if ,  = (, , .child[0], );  != nil ||  == nil {
				return nil, 
			}
			switch .cat {
			case valueT:
				if  := .rtype; .Kind() == reflect.Func && .NumOut() == 1 {
					 = valueTOf(.Out(0), withScope())
				}
			default:
				if len(.ret) == 1 {
					 = .ret[0]
				}
			}
		}

	case compositeLitExpr:
		,  = (, , .child[0], )

	case chanType, chanTypeRecv, chanTypeSend:
		 := chanSendRecv
		switch .kind {
		case chanTypeRecv:
			 = chanRecv
		case chanTypeSend:
			 = chanSend
		}
		,  := (, , .child[0], )
		if  != nil {
			return nil, 
		}
		 = chanOf(, , withNode(), withScope())
		.incomplete = .incomplete

	case ellipsisExpr:
		,  := (, , .child[0], )
		if  != nil {
			return nil, 
		}
		 = variadicOf(, withNode(), withScope())
		.incomplete = .val.incomplete

	case funcLit:
		,  = (, , .child[2], )

	case funcType:
		var  bool

		// Handle type parameters.
		for ,  := range .child[0].child {
			 := len(.child) - 1
			,  := (, , .child[], )
			if  != nil {
				return nil, 
			}
			for ,  := range .child[:] {
				.sym[.ident] = &symbol{index: -1, kind: varTypeSym, typ: }
			}
			 =  || .incomplete
		}

		// Handle input parameters.
		 := make([]*itype, 0, len(.child[1].child))
		for ,  := range .child[1].child {
			 := len(.child) - 1
			,  := (, , .child[], )
			if  != nil {
				return nil, 
			}
			 = append(, )
			// Several arguments may be factorized on the same field type.
			for  := 1;  < ; ++ {
				 = append(, )
			}
			 =  || .incomplete
		}

		// Handle returned values.
		var  []*itype
		if len(.child) == 3 {
			for ,  := range .child[2].child {
				 := len(.child) - 1
				,  := (, , .child[], )
				if  != nil {
					return nil, 
				}
				 = append(, )
				// Several arguments may be factorized on the same field type.
				for  := 1;  < ; ++ {
					 = append(, )
				}
				 =  || .incomplete
			}
		}
		 = funcOf(, , withNode(), withScope())
		.incomplete = 

	case identExpr:
		, ,  := .lookup(.ident)
		if ! {
			// retry with the filename, in case ident is a package name.
			 := filepath.Base(.fset.Position(.pos).Filename)
			 := filepath.Join(.ident, )
			, _,  = .lookup()
			if ! {
				 = &itype{name: .ident, path: .pkgName, node: , incomplete: true, scope: }
				.sym[.ident] = &symbol{kind: typeSym, typ: }
				break
			}
		}
		if .kind == varTypeSym {
			 = genericOf(.typ, .ident, .pkgName, withNode(), withScope())
		} else {
			 = .typ
		}
		if  == nil {
			if ,  = (, , .node, );  != nil {
				return nil, 
			}
		}
		if .incomplete && .cat == linkedT && .val != nil && .val.cat != nilT {
			.incomplete = false
		}
		if .incomplete && .node !=  {
			 := .method
			if ,  = (, , .node, );  != nil {
				return nil, 
			}
			.method = 
			.typ = 
		}
		if .node == nil {
			.node = 
		}

	case indexExpr:
		var  *itype
		if ,  = (, , .child[0], );  != nil {
			return nil, 
		}
		if .incomplete {
			if  == nil {
				 = 
			} else {
				.incomplete = true
			}
			break
		}
		switch .cat {
		case arrayT, mapT, sliceT, variadicT:
			 = .val
		case genericT:
			,  := (, , .child[1], )
			if  != nil {
				return nil, 
			}
			if .cat == genericT || .incomplete {
				 = 
				break
			}
			 := .id() + "[" + .id() + "]"
			if , ,  := .lookup();  {
				 = .typ
				break
			}
			// A generic type is being instantiated. Generate it.
			,  = genType(, , , , []*itype{}, )
			if  != nil {
				return nil, 
			}
		}

	case indexListExpr:
		// Similar to above indexExpr for generic types, but handle multiple type parameters.
		var  *itype
		if ,  = (, , .child[0], );  != nil {
			return nil, 
		}
		if .incomplete {
			if  == nil {
				 = 
			} else {
				.incomplete = true
			}
			break
		}

		// Index list expressions can be used only in context of generic types.
		if .cat != genericT {
			 = .cfgErrorf("not a generic type: %s", .id())
			return nil, 
		}
		 := .id() + "["
		 := false
		 := []*itype{}
		for ,  := range .child[1:] {
			,  := (, , , )
			if  != nil {
				return nil, 
			}
			if .cat == genericT || .incomplete {
				 = 
				 = true
				break
			}
			 = append(, )
			 += .id() + ","
		}
		if  {
			break
		}
		 = strings.TrimSuffix(, ",") + "]"
		if , ,  := .lookup();  {
			 = .typ
			break
		}
		// A generic type is being instantiated. Generate it.
		,  = genType(, , , , , )

	case interfaceType:
		if  := typeName();  != "" {
			if , ,  := .lookup();  && .kind == typeSym {
				 = interfaceOf(.typ, .typ.field, .typ.constraint, .typ.ulconstraint, withNode(), withScope())
			}
		}
		var  bool
		 := []structField{}
		 := []*itype{}
		 := []*itype{}
		for ,  := range .child[0].child {
			 := .child[0]
			if len(.child) == 1 {
				if .ident == "error" {
					// Unwrap error interface inplace rather than embedding it, because
					// "error" is lower case which may cause problems with reflect for method lookup.
					 := errorMethodType()
					 = append(, structField{name: "Error", typ: })
					continue
				}
				,  := (, , , )
				if  != nil {
					return nil, 
				}
				 =  || .incomplete
				if .cat == constraintT {
					 = append(, .constraint...)
					 = append(, .ulconstraint...)
					continue
				}
				 = append(, structField{name: fieldName(), embed: true, typ: })
				continue
			}
			,  := (, , .child[1], )
			if  != nil {
				return nil, 
			}
			 = append(, structField{name: .ident, typ: })
			 =  || .incomplete
		}
		 = interfaceOf(, , , , withNode(), withScope())
		.incomplete = 

	case landExpr, lorExpr:
		 = .getType("bool")

	case mapType:
		,  := (, , .child[0], )
		if  != nil {
			return nil, 
		}
		,  := (, , .child[1], )
		if  != nil {
			return nil, 
		}
		 = mapOf(, , withNode(), withScope())
		.incomplete = .incomplete || .incomplete

	case parenExpr:
		,  = (, , .child[0], )

	case selectorExpr:
		// Resolve the left part of selector, then lookup the right part on it
		var  *itype

		// Lookup the package symbol first if we are in a field expression as
		// a previous parameter has the same name as the package, we need to
		// prioritize the package type.
		if .anc.kind == fieldExpr {
			 = findPackageType(, , .child[0])
		}
		if  == nil {
			// No package was found or we are not in a field expression, we are looking for a variable.
			if ,  = (, , .child[0], );  != nil {
				return nil, 
			}
		}

		if .incomplete {
			break
		}
		 := .child[1].ident
		switch .cat {
		case binPkgT:
			 := .binPkg[.path]
			if ,  := [];  {
				 := .Type()
				if isBinType() {
					// A bin type is encoded as a pointer on a typed nil value.
					 = .Elem()
				}
				 = valueTOf(, withNode(), withScope())
				break
			}
			// Continue search in source package, as it may exist if package contains generics.
			fallthrough
		case srcPkgT:
			if ,  := .srcPkg[.path];  {
				if ,  := [];  {
					 = .typ
					break
				}
			}
			 = .cfgErrorf("undefined selector %s.%s", .path, )
		default:
			if ,  := .lookupMethod();  != nil {
				,  = (, , .child[2], )
			} else if , , ,  := .lookupBinMethod();  {
				 = valueTOf(.Type, isBinMethod(), withRecv(), withScope())
			} else if  := .lookupField(); len() > 0 {
				 = .fieldSeq()
			} else if , ,  := .lookupBinField();  {
				 = valueTOf(.Type, withScope())
			} else {
				 = .node.cfgErrorf("undefined selector %s", )
			}
		}

	case sliceExpr:
		,  = (, , .child[0], )
		if  != nil {
			return nil, 
		}

		if .cat == valueT {
			switch .rtype.Kind() {
			case reflect.Array, reflect.Ptr:
				 = valueTOf(reflect.SliceOf(.rtype.Elem()), withScope())
			}
			break
		}
		if .cat == ptrT {
			 = .val
		}
		if .cat == arrayT {
			 := .incomplete
			 = sliceOf(.val, withNode(), withScope())
			.incomplete = 
		}

	case structType:
		var  *symbol
		var  bool
		 := structName()
		if  != "" {
			, _,  = .lookup()
			if  && .kind == typeSym && .typ != nil {
				 = structOf(.typ, .typ.field, withNode(), withScope())
			} else {
				 = structOf(nil, nil, withNode(), withScope())
				.sym[] = &symbol{index: -1, kind: typeSym, typ: , node: }
			}
		}
		var  bool
		 := make([]structField, 0, len(.child[0].child))
		for ,  := range .child[0].child {
			switch {
			case len(.child) == 1:
				,  := (, , .child[0], )
				if  != nil {
					return nil, 
				}
				 = append(, structField{name: fieldName(.child[0]), embed: true, typ: })
				 =  || .incomplete
			case len(.child) == 2 && .child[1].kind == basicLit:
				 := vString(.child[1].rval)
				,  := (, , .child[0], )
				if  != nil {
					return nil, 
				}
				 = append(, structField{name: fieldName(.child[0]), embed: true, typ: , tag: })
				 =  || .incomplete
			default:
				var  string
				 := len(.child)
				if .lastChild().kind == basicLit {
					 = vString(.lastChild().rval)
					--
				}
				,  := (, , .child[-1], )
				if  != nil {
					return nil, 
				}
				 =  || .incomplete
				for ,  := range .child[:-1] {
					 = append(, structField{name: .ident, typ: , tag: })
				}
			}
		}
		 = structOf(, , withNode(), withScope())
		.incomplete = 
		if  != "" {
			if .sym[] == nil {
				.sym[] = &symbol{index: -1, kind: typeSym, node: }
			}
			.sym[].typ = 
		}

	case typeAssertExpr:
		,  = (, , .child[1], )

	default:
		 = .cfgErrorf("type definition not implemented: %s", .kind)
	}

	if  == nil &&  != nil && .cat == nilT && !.incomplete {
		 = .cfgErrorf("use of untyped nil %s", .name)
	}

	// The existing symbol data needs to be recovered, but not in the
	// case where we are aliasing another type.
	if .anc.kind == typeSpec && .kind != selectorExpr && .kind != identExpr {
		 := .anc.child[0].ident
		if  := .sym[];  != nil {
			.path = .pkgName
			.name = 
		}
	}

	switch {
	case  == nil:
	case .name != "" && .path != "":
		.str = .path + "." + .name
	case .cat == nilT:
		.str = "nil"
	}

	return , 
}

func genType( *Interpreter,  *scope,  string,  *itype,  []*itype,  []*node) ( *itype,  error) {
	// A generic type is being instantiated. Generate it.
	, ,  := genAST(, .node.anc, )
	if  != nil {
		return nil, 
	}
	,  = nodeType2(, , .lastChild(), )
	if  != nil {
		return nil, 
	}
	.instance = append(.instance, )
	// Add generated symbol in the scope of generic source and user.
	.sym[] = &symbol{index: -1, kind: typeSym, typ: , node: }
	if .scope.sym[] == nil {
		.scope.sym[] = .sym[]
	}

	for ,  := range .method {
		if  := genMethod(, , , , );  != nil {
			return nil, 
		}
	}
	return , 
}

func genMethod( *Interpreter,  *scope,  *itype,  *node,  []*itype) error {
	, ,  := genAST(, , )
	if  != nil {
		return 
	}
	if .typ,  = nodeType(, , .child[2]);  != nil {
		return 
	}
	.addMethod()

	// If the receiver is a pointer to a generic type, generate also the pointer type.
	if  := .child[0].child[0].lastChild();  != nil && .kind == starExpr {
		 := ptrOf(, withNode(.node), withScope())
		.addMethod()
		.typ = 
	}

	// Compile the method AST in the scope of the generic type.
	 := .typ.scope
	if _,  = .cfg(, , .pkgID, .pkgName);  != nil {
		return 
	}

	// Generate closures for function body.
	return genRun()
}

// findPackageType searches the top level scope for a package type.
func findPackageType( *Interpreter,  *scope,  *node) *itype {
	// Find the root scope, the package symbols will exist there.
	for {
		if .level == 0 {
			break
		}
		 = .anc
	}

	 := filepath.Base(.fset.Position(.pos).Filename)
	, ,  := .lookup(filepath.Join(.ident, ))
	if ! || .typ == nil && .typ.cat != srcPkgT && .typ.cat != binPkgT {
		return nil
	}
	return .typ
}

func isBuiltinCall( *node,  *scope) bool {
	if .kind != callExpr {
		return false
	}
	 := .child[0].sym
	if  == nil {
		if , ,  := .lookup(.child[0].ident);  {
			 = 
		}
	}
	return  != nil && .kind == bltnSym
}

// struct name returns the name of a struct type.
func typeName( *node) string {
	if .anc.kind == typeSpec && len(.anc.child) == 2 {
		return .anc.child[0].ident
	}
	return ""
}

func structName( *node) string {
	if .anc.kind == typeSpec {
		return .anc.child[0].ident
	}
	return ""
}

// fieldName returns an implicit struct field name according to node kind.
func fieldName( *node) string {
	switch .kind {
	case selectorExpr:
		return (.child[1])
	case starExpr:
		return (.child[0])
	case indexExpr:
		return (.child[0])
	case identExpr:
		return .ident
	default:
		return ""
	}
}

var zeroValues [maxT]reflect.Value

func init() {
	zeroValues[boolT] = reflect.ValueOf(false)
	zeroValues[complex64T] = reflect.ValueOf(complex64(0))
	zeroValues[complex128T] = reflect.ValueOf(complex128(0))
	zeroValues[errorT] = reflect.ValueOf(new(error)).Elem()
	zeroValues[float32T] = reflect.ValueOf(float32(0))
	zeroValues[float64T] = reflect.ValueOf(float64(0))
	zeroValues[intT] = reflect.ValueOf(int(0))
	zeroValues[int8T] = reflect.ValueOf(int8(0))
	zeroValues[int16T] = reflect.ValueOf(int16(0))
	zeroValues[int32T] = reflect.ValueOf(int32(0))
	zeroValues[int64T] = reflect.ValueOf(int64(0))
	zeroValues[stringT] = reflect.ValueOf("")
	zeroValues[uintT] = reflect.ValueOf(uint(0))
	zeroValues[uint8T] = reflect.ValueOf(uint8(0))
	zeroValues[uint16T] = reflect.ValueOf(uint16(0))
	zeroValues[uint32T] = reflect.ValueOf(uint32(0))
	zeroValues[uint64T] = reflect.ValueOf(uint64(0))
	zeroValues[uintptrT] = reflect.ValueOf(uintptr(0))
}

// Finalize returns a type pointer and error. It reparses a type from the
// partial AST if necessary (after missing dependecy data is available).
// If error is nil, the type is guarranteed to be completely defined and
// usable for CFG.
func ( *itype) () (*itype, error) {
	var  error
	if .incomplete {
		, ,  := .scope.lookup(.name)
		if  && !.typ.incomplete {
			.typ.method = append(.typ.method, .method...)
			.method = .typ.method
			.incomplete = false
			return .typ, nil
		}
		 := .method
		if ,  = nodeType(.node.interp, .scope, .node);  != nil {
			return nil, 
		}
		if .incomplete {
			return nil, .node.cfgErrorf("incomplete type %s", .name)
		}
		.method = 
		.node.typ = 
		if  != nil {
			.typ = 
		}
	}
	return , 
}

func ( *itype) ( *node) {
	for ,  := range .method {
		if  ==  {
			return
		}
	}
	.method = append(.method, )
}

func ( *itype) () int {
	switch .cat {
	case funcT:
		return len(.arg)
	case valueT:
		if .rtype.Kind() != reflect.Func {
			return 0
		}
		 := .rtype.NumIn()
		if .recv != nil {
			--
		}
		return 
	}
	return 0
}

func ( *itype) ( int) *itype {
	switch .cat {
	case funcT:
		return .arg[]
	case valueT:
		if .rtype.Kind() == reflect.Func {
			if .recv != nil && !isInterface(.recv) {
				++
			}
			if .rtype.IsVariadic() &&  == .rtype.NumIn()-1 {
				 := valueTOf(.rtype.In().Elem())
				return &itype{cat: variadicT, val: , str: "..." + .str}
			}
			return valueTOf(.rtype.In())
		}
	}
	return nil
}

func ( *itype) () int {
	switch .cat {
	case funcT:
		return len(.ret)
	case valueT:
		if .rtype.Kind() == reflect.Func {
			return .rtype.NumOut()
		}
	case builtinT:
		switch .name {
		case "append", "cap", "complex", "copy", "imag", "len", "make", "new", "real", "recover", "unsafe.Alignof", "unsafe.Offsetof", "unsafe.Sizeof":
			return 1
		}
	}
	return 0
}

func ( *itype) ( int) *itype {
	switch .cat {
	case funcT:
		return .ret[]
	case valueT:
		if .rtype.Kind() == reflect.Func {
			return valueTOf(.rtype.Out())
		}
	}
	return nil
}

func ( *itype) () *itype {
	if isInterface() && .val != nil {
		return .val.()
	}
	return 
}

func ( *itype) () *itype {
	if .cat == linkedT {
		return .val.()
	}
	return 
}

// typeDefined returns true if type t1 is defined from type t2 or t2 from t1.
func typeDefined(,  *itype) bool {
	if .cat == linkedT && .val ==  {
		return true
	}
	if .cat == linkedT && .val ==  {
		return true
	}
	return false
}

// isVariadic returns true if the function type is variadic.
// If the type is not a function or is not variadic, it will
// return false.
func ( *itype) () bool {
	switch .cat {
	case funcT:
		return len(.arg) > 0 && .arg[len(.arg)-1].cat == variadicT
	case valueT:
		if .rtype.Kind() == reflect.Func {
			return .rtype.IsVariadic()
		}
	}
	return false
}

// isComplete returns true if type definition is complete.
func ( *itype) () bool { return isComplete(, map[string]bool{}) }

func isComplete( *itype,  map[string]bool) bool {
	if .incomplete {
		return false
	}
	 := .path + "/" + .name
	if [] {
		return true
	}
	if .name != "" {
		[] = true
	}
	switch .cat {
	case linkedT:
		if .val != nil && .val.cat != nilT {
			// A type aliased to a partially defined type is considered complete, to allow recursivity.
			return true
		}
		fallthrough
	case arrayT, chanT, chanRecvT, chanSendT, ptrT, sliceT, variadicT:
		return (.val, )
	case funcT:
		 := true
		for ,  := range .arg {
			 =  && (, )
		}
		for ,  := range .ret {
			 =  && (, )
		}
		return 
	case interfaceT, structT:
		 := true
		for ,  := range .field {
			// Field implicit type names must be marked as visited, to break false circles.
			[.typ.path+"/"+.typ.name] = true
			 =  && (.typ, )
		}
		return 
	case mapT:
		return (.key, ) && (.val, )
	case nilT:
		return false
	}
	return true
}

// comparable returns true if the type is comparable.
func ( *itype) () bool {
	 := .TypeOf()
	return .cat == nilT ||  != nil && .Comparable()
}

func ( *itype) ( *itype) bool {
	if .equals() {
		return true
	}

	if .cat == linkedT && .cat == linkedT && (.underlying().id() != .underlying().id() || !typeDefined(, )) {
		return false
	}

	if .isNil() && .hasNil() || .isNil() && .hasNil() {
		return true
	}

	if .TypeOf().AssignableTo(.TypeOf()) {
		return true
	}

	if isInterface() && .implements() {
		return true
	}

	if .cat == sliceT && .cat == sliceT {
		return .val.(.val)
	}

	if .isBinMethod && isFunc() {
		// TODO (marc): check that t without receiver as first parameter is equivalent to o.
		return true
	}

	if .untyped && isNumber(.TypeOf()) && isNumber(.TypeOf()) {
		// Assignability depends on constant numeric value (overflow check), to be tested elsewhere.
		return true
	}

	 := .node
	if  == nil || !.rval.IsValid() {
		return false
	}
	,  := .rval.Interface().(constant.Value)
	if ! {
		return false
	}
	if  == nil || !isConstType() {
		return false
	}
	return representableConst(, .TypeOf())
}

// convertibleTo returns true if t is convertible to o.
func ( *itype) ( *itype) bool {
	if .assignableTo() {
		return true
	}

	// unsafe checks
	,  := .TypeOf(), .TypeOf()
	if (.Kind() == reflect.Ptr || .Kind() == reflect.Uintptr) && .Kind() == reflect.UnsafePointer {
		return true
	}
	if .Kind() == reflect.UnsafePointer && (.Kind() == reflect.Ptr || .Kind() == reflect.Uintptr) {
		return true
	}

	return .TypeOf().ConvertibleTo(.TypeOf())
}

// ordered returns true if the type is ordered.
func ( *itype) () bool {
	 := .TypeOf()
	return isInt() || isFloat() || isString()
}

// equals returns true if the given type is identical to the receiver one.
func ( *itype) ( *itype) bool {
	switch ,  := isInterface(), isInterface(); {
	case  && :
		return .methods().equals(.methods())
	case  && !:
		return .methods().contains(.methods())
	case  && !:
		return .methods().contains(.methods())
	default:
		return .id() == .id()
	}
}

// matchDefault returns true if the receiver default type is the same as the given one.
func ( *itype) ( *itype) bool {
	return .untyped && .id() == "untyped "+.id()
}

// MethodSet defines the set of methods signatures as strings, indexed per method name.
type methodSet map[string]string

// Contains returns true if the method set m contains the method set n.
func ( methodSet) ( methodSet) bool {
	for  := range  {
		// Only check the presence of method, not its complete signature,
		// as the receiver may be part of the arguments, which makes a
		// robust check complex.
		if ,  := []; ! {
			return false
		}
	}
	return true
}

// Equal returns true if the method set m is equal to the method set n.
func ( methodSet) ( methodSet) bool {
	return .contains() && .contains()
}

// Methods returns a map of method type strings, indexed by method names.
func ( *itype) () methodSet {
	 := map[*itype]bool{}
	var  func( *itype) methodSet

	 = func( *itype) methodSet {
		 := make(methodSet)

		if [] {
			// Stop the recursion, we have seen this type.
			return 
		}
		[] = true

		switch .cat {
		case linkedT:
			for ,  := range (.val) {
				[] = 
			}
		case interfaceT:
			// Get methods from recursive analysis of interface fields.
			for ,  := range .field {
				if .typ.cat == funcT {
					[.name] = .typ.TypeOf().String()
				} else {
					for ,  := range (.typ) {
						[] = 
					}
				}
			}
		case valueT, errorT:
			// Get method from corresponding reflect.Type.
			for  := .TypeOf().NumMethod() - 1;  >= 0; -- {
				 := .rtype.Method()
				[.Name] = .Type.String()
			}
		case ptrT:
			if .val.cat == valueT {
				// Ptr receiver methods need to be found with the ptr type.
				.TypeOf() // Ensure the rtype exists.
				for  := .rtype.NumMethod() - 1;  >= 0; -- {
					 := .rtype.Method()
					[.Name] = .Type.String()
				}
			}
			for ,  := range (.val) {
				[] = 
			}
		case structT:
			for ,  := range .field {
				if !.embed {
					continue
				}
				for ,  := range (.typ) {
					[] = 
				}
			}
		}
		// Get all methods defined on this type.
		for ,  := range .method {
			[.ident] = .typ.TypeOf().String()
		}
		return 
	}

	return ()
}

// id returns a unique type identificator string.
func ( *itype) () ( string) {
	// Prefer the wrapped type string over the rtype string.
	if .cat == valueT && .val != nil {
		return .val.str
	}
	return .str
}

// fixPossibleConstType returns the input type if it not a constant value,
// otherwise, it returns the default Go type corresponding to the
// constant.Value.
func fixPossibleConstType( reflect.Type) ( reflect.Type) {
	,  := reflect.New().Elem().Interface().(constant.Value)
	if ! {
		return 
	}
	switch .Kind() {
	case constant.Bool:
		 = reflect.TypeOf(true)
	case constant.Int:
		 = reflect.TypeOf(0)
	case constant.String:
		 = reflect.TypeOf("")
	case constant.Float:
		 = reflect.TypeOf(float64(0))
	case constant.Complex:
		 = reflect.TypeOf(complex128(0))
	}
	return 
}

// zero instantiates and return a zero value object for the given type during execution.
func ( *itype) () ( reflect.Value,  error) {
	if ,  = .finalize();  != nil {
		return , 
	}
	switch .cat {
	case linkedT:
		,  = .val.()

	case arrayT, ptrT, structT, sliceT:
		 = reflect.New(.frameType()).Elem()

	case valueT:
		 = reflect.New(.rtype).Elem()

	default:
		 = zeroValues[.cat]
	}
	return , 
}

// fieldIndex returns the field index from name in a struct, or -1 if not found.
func ( *itype) ( string) int {
	switch .cat {
	case linkedT, ptrT:
		return .val.()
	}
	for ,  := range .field {
		if  == .name {
			return 
		}
	}
	return -1
}

// fieldSeq returns the field type from the list of field indexes.
func ( *itype) ( []int) *itype {
	 := 
	for ,  := range  {
		if .cat == ptrT {
			 = .val
		}
		 = .field[].typ
	}
	return 
}

// lookupField returns a list of indices, i.e. a path to access a field in a struct object.
func ( *itype) ( string) []int {
	 := map[*itype]bool{}
	var  func(*itype) []int
	 := isStruct()

	 = func( *itype) []int {
		if [] {
			return nil
		}
		[] = true

		switch .cat {
		case linkedT, ptrT:
			return (.val)
		}
		if  := .fieldIndex();  >= 0 {
			return []int{}
		}

		for ,  := range .field {
			switch .typ.cat {
			case ptrT, structT, interfaceT, linkedT:
				if  != isStruct(.typ) {
					// Interface fields are not valid embedded struct fields.
					// Struct fields are not valid interface fields.
					break
				}
				if  := (.typ); len() > 0 {
					return append([]int{}, ...)
				}
			}
		}

		return nil
	}

	return ()
}

// lookupBinField returns a structfield and a path to access an embedded binary field in a struct object.
func ( *itype) ( string) ( reflect.StructField,  []int,  bool) {
	if .cat == ptrT {
		return .val.()
	}
	if !isStruct() {
		return
	}
	 := .TypeOf()
	for .cat == valueT && .Kind() == reflect.Ptr {
		 = .Elem()
	}
	if .Kind() != reflect.Struct {
		return
	}
	,  = .FieldByName()
	if ! {
		for ,  := range .field {
			if .embed {
				if , ,  := .typ.();  {
					 = append([]int{}, ...)
					return , , 
				}
			}
		}
	}
	return , , 
}

// MethodCallType returns a method function type without the receiver defined.
// The input type must be a method function type with the receiver as the first input argument.
func ( *itype) () reflect.Type {
	 := []reflect.Type{}
	 := .rtype.NumIn()
	for  := 1;  < ; ++ {
		 = append(, .rtype.In())
	}
	 := []reflect.Type{}
	 := .rtype.NumOut()
	for  := 0;  < ; ++ {
		 = append(, .rtype.Out())
	}
	return reflect.FuncOf(, , .rtype.IsVariadic())
}

func ( *itype) () *itype {
	for .cat == linkedT {
		 = .val
	}
	return 
}

// GetMethod returns a pointer to the method definition.
func ( *itype) ( string) *node {
	for ,  := range .method {
		if  == .ident {
			return 
		}
	}
	return nil
}

// LookupMethod returns a pointer to method definition associated to type t
// and the list of indices to access the right struct field, in case of an embedded method.
func ( *itype) ( string) (*node, []int) {
	return .lookupMethod2(, nil)
}

func ( *itype) ( string,  map[*itype]bool) (*node, []int) {
	if  == nil {
		 = map[*itype]bool{}
	}
	if [] {
		return nil, nil
	}
	[] = true
	if .cat == ptrT {
		return .val.(, )
	}
	var  []int
	 := .getMethod()
	if  == nil {
		for ,  := range .field {
			if .embed {
				if ,  := .typ.(, );  != nil {
					 = append([]int{}, ...)
					return , 
				}
			}
		}
		if .cat == linkedT || isInterfaceSrc() && .val != nil {
			return .val.(, )
		}
	}
	return , 
}

// interfaceMethod returns type of method matching an interface method name (not as a concrete method).
func ( *itype) ( string) *itype {
	return .interfaceMethod2(, nil)
}

func ( *itype) ( string,  map[*itype]bool) *itype {
	if  == nil {
		 = map[*itype]bool{}
	}
	if [] {
		return nil
	}
	[] = true
	if .cat == ptrT {
		return .val.(, )
	}
	for ,  := range .field {
		if .name ==  && isInterface() {
			return .typ
		}
		if !.embed {
			continue
		}
		if  := .typ.(, );  != nil {
			return 
		}
	}
	if .cat == linkedT || isInterfaceSrc() && .val != nil {
		return .val.(, )
	}
	return nil
}

// methodDepth returns a depth greater or equal to 0, or -1 if no match.
func ( *itype) ( string) int {
	if ,  := .lookupMethod();  != nil {
		return len()
	}
	if , , ,  := .lookupBinMethod();  {
		return len()
	}
	return -1
}

// LookupBinMethod returns a method and a path to access a field in a struct object (the receiver).
func ( *itype) ( string) ( reflect.Method,  []int, ,  bool) {
	return .lookupBinMethod2(, nil)
}

func ( *itype) ( string,  map[*itype]bool) ( reflect.Method,  []int, ,  bool) {
	if  == nil {
		 = map[*itype]bool{}
	}
	if [] {
		return
	}
	[] = true
	if .cat == ptrT {
		return .val.(, )
	}
	for ,  := range .field {
		if .embed {
			if , , ,  := .typ.(, );  {
				 = append([]int{}, ...)
				return , , , 
			}
		}
	}
	,  = .TypeOf().MethodByName()
	if ! {
		,  = reflect.PtrTo(.TypeOf()).MethodByName()
		 = 
	}
	return , , , 
}

func lookupFieldOrMethod( *itype,  string) *itype {
	switch {
	case .cat == valueT || .cat == ptrT && .val.cat == valueT:
		, , ,  := .lookupBinMethod()
		if ! {
			return nil
		}
		var  *itype
		if .rtype.Kind() != reflect.Interface {
			 = 
			if  && .cat != ptrT && .rtype.Kind() != reflect.Ptr {
				 = ptrOf()
			}
		}
		return valueTOf(.Type, withRecv())
	case .cat == interfaceT:
		 := .lookupField()
		if  == nil {
			return nil
		}
		return .fieldSeq()
	default:
		,  := .lookupMethod()
		if  == nil {
			return nil
		}
		return .typ
	}
}

func exportName( string) string {
	if canExport() {
		return 
	}
	return "X" + 
}

var (
	// TODO(mpl): generators.
	emptyInterfaceType = reflect.TypeOf((*interface{})(nil)).Elem()
	valueInterfaceType = reflect.TypeOf((*valueInterface)(nil)).Elem()
	constVal           = reflect.TypeOf((*constant.Value)(nil)).Elem()
)

type refTypeContext struct {
	defined map[string]*itype

	// refs keeps track of all the places (in the same type recursion) where the
	// type name (as key) is used as a field of another (or possibly the same) struct
	// type. Each of these fields will then live as an unsafe2.dummy type until the
	// whole recursion is fully resolved, and the type is fixed.
	refs map[string][]*itype

	// When we detect for the first time that we are in a recursive type (thanks to
	// defined), we keep track of the first occurrence of the type where the recursion
	// started, so we can restart the last step that fixes all the types from the same
	// "top-level" point.
	rect       *itype
	rebuilding bool
	slevel     int
}

// Clone creates a copy of the ref type context.
func ( *refTypeContext) () *refTypeContext {
	return &refTypeContext{defined: .defined, refs: .refs, rebuilding: .rebuilding}
}

func ( *refTypeContext) () bool {
	for ,  := range .defined {
		if .rtype == nil {
			return false
		}
	}
	return true
}

func ( *itype) ( reflect.Type) reflect.Type {
	if  == unsafe2.DummyType {
		return .rtype
	}
	switch .Kind() {
	case reflect.Array:
		return reflect.ArrayOf(.Len(), .(.Elem()))
	case reflect.Chan:
		return reflect.ChanOf(.ChanDir(), .(.Elem()))
	case reflect.Func:
		 := make([]reflect.Type, .NumIn())
		for  := range  {
			[] = .(.In())
		}
		 := make([]reflect.Type, .NumOut())
		for  := range  {
			[] = .(.Out())
		}
		return reflect.FuncOf(, , .IsVariadic())
	case reflect.Map:
		return reflect.MapOf(.(.Key()), .(.Elem()))
	case reflect.Ptr:
		return reflect.PtrTo(.(.Elem()))
	case reflect.Slice:
		return reflect.SliceOf(.(.Elem()))
	case reflect.Struct:
		 := make([]reflect.StructField, .NumField())
		for  := range  {
			[] = .Field()
			[].Type = .([].Type)
		}
		return reflect.StructOf()
	}
	return 
}

// RefType returns a reflect.Type representation from an interpreter type.
// In simple cases, reflect types are directly mapped from the interpreter
// counterpart.
// For recursive named struct or interfaces, as reflect does not permit to
// create a recursive named struct, a dummy type is set temporarily for each recursive
// field. When done, the dummy type fields are updated with the original reflect type
// pointer using unsafe. We thus obtain a usable recursive type definition, except
// for string representation, as created reflect types are still unnamed.
func ( *itype) ( *refTypeContext) reflect.Type {
	if  == nil {
		 = &refTypeContext{
			defined: map[string]*itype{},
			refs:    map[string][]*itype{},
		}
	}
	if .incomplete || .cat == nilT {
		var  error
		if ,  = .finalize();  != nil {
			panic()
		}
	}
	 := .path + "/" + .name

	if .rtype != nil && !.rebuilding {
		return .rtype
	}
	if  := .defined[];  != nil {
		// We get here when we are a struct field, and our type name has already been
		// seen at least once in one of our englobing structs. i.e. there's at least one
		// level of type recursion.
		if .rtype != nil {
			.rtype = .rtype
			return .rtype
		}

		// The recursion has not been fully resolved yet.
		// To indicate that a rebuild is needed on the englobing struct,
		// return a dummy field type and create an empty entry.
		 := .refs[]
		.rect = 

		// We know we are used as a field by someone, but we don't know by who
		// at this point in the code, so we just mark it as an empty *itype for now.
		// We'll complete the *itype in the caller.
		.refs[] = append(, (*itype)(nil))
		return unsafe2.DummyType
	}
	if isGeneric() {
		return reflect.TypeOf((*generic)(nil)).Elem()
	}
	switch .cat {
	case linkedT:
		.rtype = .val.()
	case arrayT:
		.rtype = reflect.ArrayOf(.length, .val.())
	case sliceT, variadicT:
		.rtype = reflect.SliceOf(.val.())
	case chanT:
		.rtype = reflect.ChanOf(reflect.BothDir, .val.())
	case chanRecvT:
		.rtype = reflect.ChanOf(reflect.RecvDir, .val.())
	case chanSendT:
		.rtype = reflect.ChanOf(reflect.SendDir, .val.())
	case errorT:
		.rtype = reflect.TypeOf(new(error)).Elem()
	case funcT:
		 := false
		 := make([]reflect.Type, len(.arg))
		 := make([]reflect.Type, len(.ret))
		for ,  := range .arg {
			[] = .()
			 = .cat == variadicT
		}
		for ,  := range .ret {
			[] = .()
		}
		.rtype = reflect.FuncOf(, , )
	case interfaceT:
		if len(.field) == 0 {
			// empty interface, do not wrap it
			.rtype = emptyInterfaceType
			break
		}
		.rtype = valueInterfaceType
	case mapT:
		.rtype = reflect.MapOf(.key.(), .val.())
	case ptrT:
		 := .val.()
		if  == unsafe2.DummyType && .slevel > 1 {
			// We have a pointer to a recursive struct which is not yet fully computed.
			// Return it but do not yet store it in rtype, so the complete version can
			// be stored in future.
			return reflect.PtrTo()
		}
		.rtype = reflect.PtrTo()
	case structT:
		if .name != "" {
			.defined[] = 
		}
		.slevel++
		var  []reflect.StructField
		for ,  := range .field {
			 := reflect.StructField{
				Name: exportName(.name),
				Type: .typ.(),
				Tag:  reflect.StructTag(.tag),
			}
			if len(.field) == 1 && .embed {
				// Mark the field as embedded (anonymous) only if it is the
				// only one, to avoid a panic due to golang/go#15924 issue.
				.Anonymous = true
			}
			 = append(, )
			// Find any nil type refs that indicates a rebuild is needed on this field.
			for ,  := range .refs {
				for ,  := range  {
					if  == nil {
						[] = 
					}
				}
			}
		}
		.slevel--
		type  struct {
			  string
			 int
		}
		 := []{} // Slice of field indices to fix for recursivity.
		.rtype = reflect.StructOf()
		if .isComplete() {
			for ,  := range .defined {
				for  := 0;  < .rtype.NumField(); ++ {
					 := .rtype.Field()
					if strings.HasSuffix(.Type.String(), "unsafe2.dummy") {
						unsafe2.SetFieldType(.rtype, , .rect.fixDummy(.rtype.Field().Type))
						if  == .path+"/"+.name {
							 = append(, {.name, })
						}
						continue
					}
					if .Type.Kind() == reflect.Func && strings.Contains(.Type.String(), "unsafe2.dummy") {
						 = append(, {.name, })
					}
				}
			}
		}

		// The rtype has now been built, we can go back and rebuild
		// all the recursive types that relied on this type.
		// However, as we are keyed by type name, if two or more (recursive) fields at
		// the same depth level are of the same type, or a "variation" of the same type
		// (slice of, map of, etc), they "mask" each other, and only one
		// of them is in ctx.refs. That is why the code around here is a bit convoluted,
		// and we need both the loop above, around all the struct fields, and the loop
		// below, around the ctx.refs.
		for ,  := range .refs[] {
			for ,  := range  {
				if . == .name {
					 := .field[.].typ.(&refTypeContext{defined: .defined, rebuilding: true})
					unsafe2.SetFieldType(.rtype, ., )
				}
			}
		}
	default:
		if ,  := .zero(); .IsValid() {
			.rtype = .Type()
		}
	}
	return .rtype
}

// TypeOf returns the reflection type of dynamic interpreter type t.
func ( *itype) () reflect.Type {
	return .refType(nil)
}

func ( *itype) () ( reflect.Type) {
	var  error
	if ,  = .finalize();  != nil {
		panic()
	}
	switch .cat {
	case linkedT:
		 = .val.()
	case arrayT:
		 = reflect.ArrayOf(.length, .val.())
	case sliceT, variadicT:
		 = reflect.SliceOf(.val.())
	case interfaceT:
		if len(.field) == 0 {
			// empty interface, do not wrap it
			 = emptyInterfaceType
			break
		}
		 = valueInterfaceType
	case mapT:
		 = reflect.MapOf(.key.(), .val.())
	case ptrT:
		 = reflect.PtrTo(.val.())
	default:
		 = .TypeOf()
	}
	return 
}

func ( *itype) ( *itype) bool {
	if isBin() {
		// Note: in case of a valueInterfaceType, we
		// miss required data which will be available
		// later, so we optimistically return true to progress,
		// and additional checks will be hopefully performed at
		// runtime.
		if  := .TypeOf();  == valueInterfaceType {
			return true
		}
		return .TypeOf().Implements(.TypeOf())
	}
	return .methods().contains(.methods())
}

// defaultType returns the default type of an untyped type.
func ( *itype) ( reflect.Value,  *scope) *itype {
	if !.untyped {
		return 
	}

	 := 
	// The default type can also be derived from a constant value.
	if .IsValid() && .Type().Implements(constVal) {
		switch .Interface().(constant.Value).Kind() {
		case constant.String:
			 = .getType("string")
		case constant.Bool:
			 = .getType("bool")
		case constant.Int:
			switch .cat {
			case int32T:
				 = .getType("int32")
			default:
				 = .getType("int")
			}
		case constant.Float:
			 = .getType("float64")
		case constant.Complex:
			 = .getType("complex128")
		}
	}
	if .untyped {
		switch .cat {
		case stringT:
			 = .getType("string")
		case boolT:
			 = .getType("bool")
		case intT:
			 = .getType("int")
		case float64T:
			 = .getType("float64")
		case complex128T:
			 = .getType("complex128")
		default:
			* = *
			.untyped = false
		}
	}
	return 
}

func ( *itype) () bool { return .cat == nilT }

func ( *itype) () bool {
	switch  := .TypeOf(); .Kind() {
	case reflect.UnsafePointer:
		return true
	case reflect.Slice, reflect.Ptr, reflect.Func, reflect.Interface, reflect.Map, reflect.Chan:
		return true
	case reflect.Struct:
		if  == valueInterfaceType {
			return true
		}
	}
	return false
}

func ( *itype) () *itype {
	if .cat == valueT {
		return valueTOf(.rtype.Elem())
	}
	return .val
}

func hasElem( reflect.Type) bool {
	switch .Kind() {
	case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
		return true
	}
	return false
}

func constToInt( constant.Value) int {
	if constant.BitLen() > 64 {
		panic(fmt.Sprintf("constant %s overflows int64", .ExactString()))
	}
	,  := constant.Int64Val()
	return int()
}

func constToString( reflect.Value) string {
	 := .Interface().(constant.Value)
	return constant.StringVal()
}

func wrappedType( *node) *itype {
	if .typ.cat != valueT {
		return nil
	}
	return .typ.val
}

func isShiftNode( *node) bool {
	switch .action {
	case aShl, aShr, aShlAssign, aShrAssign:
		return true
	}
	return false
}

// chanElement returns the channel element type.
func chanElement( *itype) *itype {
	switch .cat {
	case linkedT:
		return (.val)
	case chanT, chanSendT, chanRecvT:
		return .val
	case valueT:
		return valueTOf(.rtype.Elem(), withNode(.node), withScope(.scope))
	}
	return nil
}

func isBool( *itype) bool { return .TypeOf().Kind() == reflect.Bool }
func isChan( *itype) bool { return .TypeOf().Kind() == reflect.Chan }
func isFunc( *itype) bool { return .TypeOf().Kind() == reflect.Func }
func isMap( *itype) bool  { return .TypeOf().Kind() == reflect.Map }
func isPtr( *itype) bool  { return .TypeOf().Kind() == reflect.Ptr }

func isEmptyInterface( *itype) bool {
	return  != nil && .cat == interfaceT && len(.field) == 0
}

func isGeneric( *itype) bool {
	return .cat == funcT && .node != nil && len(.node.child) > 0 && len(.node.child[0].child) > 0
}

func isNamedFuncSrc( *itype) bool {
	return isFuncSrc() && .node.anc.kind == funcDecl
}

func isFuncSrc( *itype) bool {
	return .cat == funcT || (.cat == linkedT && (.val))
}

func isPtrSrc( *itype) bool {
	return .cat == ptrT || (.cat == linkedT && (.val))
}

func isSendChan( *itype) bool {
	 := .TypeOf()
	return .Kind() == reflect.Chan && .ChanDir() == reflect.SendDir
}

func isArray( *itype) bool {
	if .cat == nilT {
		return false
	}
	 := .TypeOf().Kind()
	return  == reflect.Array ||  == reflect.Slice
}

func isInterfaceSrc( *itype) bool {
	return .cat == interfaceT || (.cat == linkedT && (.val))
}

func isInterfaceBin( *itype) bool {
	return .cat == valueT && .rtype.Kind() == reflect.Interface || .cat == errorT
}

func isInterface( *itype) bool {
	return isInterfaceSrc() || .TypeOf() == valueInterfaceType || .TypeOf() != nil && .TypeOf().Kind() == reflect.Interface
}

func isBin( *itype) bool {
	switch .cat {
	case valueT:
		return true
	case linkedT, ptrT:
		return (.val)
	default:
		return false
	}
}

func isStruct( *itype) bool {
	// Test first for a struct category, because a recursive interpreter struct may be
	// represented by an interface{} at reflect level.
	switch .cat {
	case structT:
		return true
	case linkedT, ptrT:
		return (.val)
	case valueT:
		 := .rtype.Kind()
		return  == reflect.Struct || ( == reflect.Ptr && .rtype.Elem().Kind() == reflect.Struct)
	default:
		return false
	}
}

func isConstType( *itype) bool {
	 := .TypeOf()
	return isBoolean() || isString() || isNumber()
}

func isInt( reflect.Type) bool {
	if  == nil {
		return false
	}
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return true
	}
	return false
}

func isUint( reflect.Type) bool {
	if  == nil {
		return false
	}
	switch .Kind() {
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return true
	}
	return false
}

func isComplex( reflect.Type) bool {
	if  == nil {
		return false
	}
	switch .Kind() {
	case reflect.Complex64, reflect.Complex128:
		return true
	}
	return false
}

func isFloat( reflect.Type) bool {
	if  == nil {
		return false
	}
	switch .Kind() {
	case reflect.Float32, reflect.Float64:
		return true
	}
	return false
}

func isByteArray( reflect.Type) bool {
	if  == nil {
		return false
	}
	 := .Kind()
	return ( == reflect.Array ||  == reflect.Slice) && .Elem().Kind() == reflect.Uint8
}

func isFloat32( reflect.Type) bool { return  != nil && .Kind() == reflect.Float32 }
func isFloat64( reflect.Type) bool { return  != nil && .Kind() == reflect.Float64 }
func isNumber( reflect.Type) bool {
	return isInt() || isFloat() || isComplex() || isConstantValue()
}
func isBoolean( reflect.Type) bool       { return  != nil && .Kind() == reflect.Bool }
func isString( reflect.Type) bool        { return  != nil && .Kind() == reflect.String }
func isConstantValue( reflect.Type) bool { return  != nil && .Implements(constVal) }