// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file implements commonly used type predicates.

package types

import 

// The isX predicates below report whether t is an X.
// If t is a type parameter the result is false; i.e.,
// these predicates don't look inside a type parameter.

func isBoolean( Type) bool        { return isBasic(, IsBoolean) }
func isInteger( Type) bool        { return isBasic(, IsInteger) }
func isUnsigned( Type) bool       { return isBasic(, IsUnsigned) }
func isFloat( Type) bool          { return isBasic(, IsFloat) }
func isComplex( Type) bool        { return isBasic(, IsComplex) }
func isNumeric( Type) bool        { return isBasic(, IsNumeric) }
func isString( Type) bool         { return isBasic(, IsString) }
func isIntegerOrFloat( Type) bool { return isBasic(, IsInteger|IsFloat) }
func isConstType( Type) bool      { return isBasic(, IsConstType) }

// isBasic reports whether under(t) is a basic type with the specified info.
// If t is a type parameter the result is false; i.e.,
// isBasic does not look inside a type parameter.
func isBasic( Type,  BasicInfo) bool {
	,  := under().(*Basic)
	return  != nil && .info& != 0
}

// The allX predicates below report whether t is an X.
// If t is a type parameter the result is true if isX is true
// for all specified types of the type parameter's type set.
// allX is an optimized version of isX(coreType(t)) (which
// is the same as underIs(t, isX)).

func allBoolean( Type) bool         { return allBasic(, IsBoolean) }
func allInteger( Type) bool         { return allBasic(, IsInteger) }
func allUnsigned( Type) bool        { return allBasic(, IsUnsigned) }
func allNumeric( Type) bool         { return allBasic(, IsNumeric) }
func allString( Type) bool          { return allBasic(, IsString) }
func allOrdered( Type) bool         { return allBasic(, IsOrdered) }
func allNumericOrString( Type) bool { return allBasic(, IsNumeric|IsString) }

// allBasic reports whether under(t) is a basic type with the specified info.
// If t is a type parameter, the result is true if isBasic(t, info) is true
// for all specific types of the type parameter's type set.
// allBasic(t, info) is an optimized version of isBasic(coreType(t), info).
func allBasic( Type,  BasicInfo) bool {
	if ,  := .(*TypeParam);  != nil {
		return .is(func( *term) bool { return  != nil && isBasic(.typ, ) })
	}
	return isBasic(, )
}

// hasName reports whether t has a name. This includes
// predeclared types, defined types, and type parameters.
// hasName may be called with types that are not fully set up.
func hasName( Type) bool {
	switch .(type) {
	case *Basic, *Named, *TypeParam:
		return true
	}
	return false
}

// isTyped reports whether t is typed; i.e., not an untyped
// constant or boolean. isTyped may be called with types that
// are not fully set up.
func isTyped( Type) bool {
	// isTyped is called with types that are not fully
	// set up. Must not call under()!
	,  := .(*Basic)
	return  == nil || .info&IsUntyped == 0
}

// isUntyped(t) is the same as !isTyped(t).
func isUntyped( Type) bool {
	return !isTyped()
}

// IsInterface reports whether t is an interface type.
func ( Type) bool {
	,  := under().(*Interface)
	return 
}

// isTypeParam reports whether t is a type parameter.
func isTypeParam( Type) bool {
	,  := .(*TypeParam)
	return 
}

// isGeneric reports whether a type is a generic, uninstantiated type
// (generic signatures are not included).
// TODO(gri) should we include signatures or assert that they are not present?
func isGeneric( Type) bool {
	// A parameterized type is only generic if it doesn't have an instantiation already.
	,  := .(*Named)
	return  != nil && .obj != nil && .targs == nil && .TypeParams() != nil
}

// Comparable reports whether values of type T are comparable.
func ( Type) bool {
	return comparable(, true, nil, nil)
}

// If dynamic is set, non-type parameter interfaces are always comparable.
// If reportf != nil, it may be used to report why T is not comparable.
func comparable( Type,  bool,  map[Type]bool,  func(string, ...interface{})) bool {
	if [] {
		return true
	}
	if  == nil {
		 = make(map[Type]bool)
	}
	[] = true

	switch t := under().(type) {
	case *Basic:
		// assume invalid types to be comparable
		// to avoid follow-up errors
		return .kind != UntypedNil
	case *Pointer, *Chan:
		return true
	case *Struct:
		for ,  := range .fields {
			if !(.typ, , , nil) {
				if  != nil {
					("struct containing %s cannot be compared", .typ)
				}
				return false
			}
		}
		return true
	case *Array:
		if !(.elem, , , nil) {
			if  != nil {
				("%s cannot be compared", )
			}
			return false
		}
		return true
	case *Interface:
		return  && !isTypeParam() || .typeSet().IsComparable()
	}
	return false
}

// hasNil reports whether type t includes the nil value.
func hasNil( Type) bool {
	switch u := under().(type) {
	case *Basic:
		return .kind == UnsafePointer
	case *Slice, *Pointer, *Signature, *Map, *Chan:
		return true
	case *Interface:
		return !isTypeParam() || .typeSet().underIs(func( Type) bool {
			return  != nil && ()
		})
	}
	return false
}

// An ifacePair is a node in a stack of interface type pairs compared for identity.
type ifacePair struct {
	x, y *Interface
	prev *ifacePair
}

func ( *ifacePair) ( *ifacePair) bool {
	return .x == .x && .y == .y || .x == .y && .y == .x
}

// For changes to this code the corresponding changes should be made to unifier.nify.
func identical(,  Type,  bool,  *ifacePair) bool {
	if  ==  {
		return true
	}

	switch x := .(type) {
	case *Basic:
		// Basic types are singletons except for the rune and byte
		// aliases, thus we cannot solely rely on the x == y check
		// above. See also comment in TypeName.IsAlias.
		if ,  := .(*Basic);  {
			return .kind == .kind
		}

	case *Array:
		// Two array types are identical if they have identical element types
		// and the same array length.
		if ,  := .(*Array);  {
			// If one or both array lengths are unknown (< 0) due to some error,
			// assume they are the same to avoid spurious follow-on errors.
			return (.len < 0 || .len < 0 || .len == .len) && (.elem, .elem, , )
		}

	case *Slice:
		// Two slice types are identical if they have identical element types.
		if ,  := .(*Slice);  {
			return (.elem, .elem, , )
		}

	case *Struct:
		// Two struct types are identical if they have the same sequence of fields,
		// and if corresponding fields have the same names, and identical types,
		// and identical tags. Two embedded fields are considered to have the same
		// name. Lower-case field names from different packages are always different.
		if ,  := .(*Struct);  {
			if .NumFields() == .NumFields() {
				for ,  := range .fields {
					 := .fields[]
					if .embedded != .embedded ||
						 && .Tag() != .Tag() ||
						!.sameId(.pkg, .name) ||
						!(.typ, .typ, , ) {
						return false
					}
				}
				return true
			}
		}

	case *Pointer:
		// Two pointer types are identical if they have identical base types.
		if ,  := .(*Pointer);  {
			return (.base, .base, , )
		}

	case *Tuple:
		// Two tuples types are identical if they have the same number of elements
		// and corresponding elements have identical types.
		if ,  := .(*Tuple);  {
			if .Len() == .Len() {
				if  != nil {
					for ,  := range .vars {
						 := .vars[]
						if !(.typ, .typ, , ) {
							return false
						}
					}
				}
				return true
			}
		}

	case *Signature:
		,  := .(*Signature)
		if  == nil {
			return false
		}

		// Two function types are identical if they have the same number of
		// parameters and result values, corresponding parameter and result types
		// are identical, and either both functions are variadic or neither is.
		// Parameter and result names are not required to match, and type
		// parameters are considered identical modulo renaming.

		if .TypeParams().Len() != .TypeParams().Len() {
			return false
		}

		// In the case of generic signatures, we will substitute in yparams and
		// yresults.
		 := .params
		 := .results

		if .TypeParams().Len() > 0 {
			// We must ignore type parameter names when comparing x and y. The
			// easiest way to do this is to substitute x's type parameters for y's.
			 := .TypeParams().list()
			 := .TypeParams().list()

			var  []Type
			for  := range  {
				 = append(, .TypeParams().At())
			}
			 := makeSubstMap(, )

			var  *Checker // ok to call subst on a nil *Checker

			// Constraints must be pair-wise identical, after substitution.
			for ,  := range  {
				 := .subst(token.NoPos, [].bound, , nil)
				if !(.bound, , , ) {
					return false
				}
			}

			 = .subst(token.NoPos, .params, , nil).(*Tuple)
			 = .subst(token.NoPos, .results, , nil).(*Tuple)
		}

		return .variadic == .variadic &&
			(.params, , , ) &&
			(.results, , , )

	case *Union:
		if ,  := .(*Union);  != nil {
			// TODO(rfindley): can this be reached during type checking? If so,
			// consider passing a type set map.
			 := make(map[*Union]*_TypeSet)
			 := computeUnionTypeSet(nil, , token.NoPos, )
			 := computeUnionTypeSet(nil, , token.NoPos, )
			return .terms.equal(.terms)
		}

	case *Interface:
		// Two interface types are identical if they describe the same type sets.
		// With the existing implementation restriction, this simplifies to:
		//
		// Two interface types are identical if they have the same set of methods with
		// the same names and identical function types, and if any type restrictions
		// are the same. Lower-case method names from different packages are always
		// different. The order of the methods is irrelevant.
		if ,  := .(*Interface);  {
			 := .typeSet()
			 := .typeSet()
			if .comparable != .comparable {
				return false
			}
			if !.terms.equal(.terms) {
				return false
			}
			 := .methods
			 := .methods
			if len() == len() {
				// Interface types are the only types where cycles can occur
				// that are not "terminated" via named types; and such cycles
				// can only be created via method parameter types that are
				// anonymous interfaces (directly or indirectly) embedding
				// the current interface. Example:
				//
				//    type T interface {
				//        m() interface{T}
				//    }
				//
				// If two such (differently named) interfaces are compared,
				// endless recursion occurs if the cycle is not detected.
				//
				// If x and y were compared before, they must be equal
				// (if they were not, the recursion would have stopped);
				// search the ifacePair stack for the same pair.
				//
				// This is a quadratic algorithm, but in practice these stacks
				// are extremely short (bounded by the nesting depth of interface
				// type declarations that recur via parameter types, an extremely
				// rare occurrence). An alternative implementation might use a
				// "visited" map, but that is probably less efficient overall.
				 := &ifacePair{, , }
				for  != nil {
					if .identical() {
						return true // same pair was compared before
					}
					 = .prev
				}
				if debug {
					assertSortedMethods()
					assertSortedMethods()
				}
				for ,  := range  {
					 := []
					if .Id() != .Id() || !(.typ, .typ, , ) {
						return false
					}
				}
				return true
			}
		}

	case *Map:
		// Two map types are identical if they have identical key and value types.
		if ,  := .(*Map);  {
			return (.key, .key, , ) && (.elem, .elem, , )
		}

	case *Chan:
		// Two channel types are identical if they have identical value types
		// and the same direction.
		if ,  := .(*Chan);  {
			return .dir == .dir && (.elem, .elem, , )
		}

	case *Named:
		// Two named types are identical if their type names originate
		// in the same type declaration.
		if ,  := .(*Named);  {
			 := .TypeArgs().list()
			 := .TypeArgs().list()

			if len() != len() {
				return false
			}

			if len() > 0 {
				// Instances are identical if their original type and type arguments
				// are identical.
				if !Identical(.orig, .orig) {
					return false
				}
				for ,  := range  {
					if !Identical(, []) {
						return false
					}
				}
				return true
			}

			// TODO(gri) Why is x == y not sufficient? And if it is,
			//           we can just return false here because x == y
			//           is caught in the very beginning of this function.
			return .obj == .obj
		}

	case *TypeParam:
		// nothing to do (x and y being equal is caught in the very beginning of this function)

	case nil:
		// avoid a crash in case of nil type

	default:
		unreachable()
	}

	return false
}

// identicalInstance reports if two type instantiations are identical.
// Instantiations are identical if their origin and type arguments are
// identical.
func identicalInstance( Type,  []Type,  Type,  []Type) bool {
	if len() != len() {
		return false
	}

	for ,  := range  {
		if !Identical(, []) {
			return false
		}
	}

	return Identical(, )
}

// Default returns the default "typed" type for an "untyped" type;
// it returns the incoming type for all other types. The default type
// for untyped nil is untyped nil.
func ( Type) Type {
	if ,  := .(*Basic);  {
		switch .kind {
		case UntypedBool:
			return Typ[Bool]
		case UntypedInt:
			return Typ[Int]
		case UntypedRune:
			return universeRune // use 'rune' name
		case UntypedFloat:
			return Typ[Float64]
		case UntypedComplex:
			return Typ[Complex128]
		case UntypedString:
			return Typ[String]
		}
	}
	return 
}