// 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 (
	
)

// isNamed reports whether typ has a name.
// isNamed may be called with types that are not fully set up.
func isNamed( Type) bool {
	switch .(type) {
	case *Basic, *Named, *_TypeParam, *instance:
		return true
	}
	return false
}

// isGeneric reports whether a type is a generic, uninstantiated type (generic
// signatures are not included).
func isGeneric( Type) bool {
	// A parameterized type is only instantiated if it doesn't have an instantiation already.
	,  := .(*Named)
	return  != nil && .obj != nil && .tparams != nil && .targs == nil
}

func is( Type,  BasicInfo) bool {
	switch t := optype().(type) {
	case *Basic:
		return .info& != 0
	case *_Sum:
		return .is(func( Type) bool { return (, ) })
	}
	return false
}

func isBoolean( Type) bool  { return is(, IsBoolean) }
func isInteger( Type) bool  { return is(, IsInteger) }
func isUnsigned( Type) bool { return is(, IsUnsigned) }
func isFloat( Type) bool    { return is(, IsFloat) }
func isComplex( Type) bool  { return is(, IsComplex) }
func isNumeric( Type) bool  { return is(, IsNumeric) }
func isString( Type) bool   { return is(, IsString) }

// Note that if typ is a type parameter, isInteger(typ) || isFloat(typ) does not
// produce the expected result because a type list that contains both an integer
// and a floating-point type is neither (all) integers, nor (all) floats.
// Use isIntegerOrFloat instead.
func isIntegerOrFloat( Type) bool { return is(, IsInteger|IsFloat) }

// isNumericOrString is the equivalent of isIntegerOrFloat for isNumeric(typ) || isString(typ).
func isNumericOrString( Type) bool { return is(, IsNumeric|IsString) }

// isTyped reports whether typ 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 asBasic()!
	// A *Named or *instance type is always typed, so
	// we only need to check if we have a true *Basic
	// type.
	,  := .(*Basic)
	return  == nil || .info&IsUntyped == 0
}

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

func isOrdered( Type) bool { return is(, IsOrdered) }

func isConstType( Type) bool {
	// Type parameters are never const types.
	,  := under().(*Basic)
	return  != nil && .info&IsConstType != 0
}

// IsInterface reports whether typ is an interface type.
func ( Type) bool {
	return asInterface() != nil
}

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

func comparable( Type,  map[Type]bool) bool {
	if [] {
		return true
	}
	if  == nil {
		 = make(map[Type]bool)
	}
	[] = true

	// If T is a type parameter not constrained by any type
	// list (i.e., it's underlying type is the top type),
	// T is comparable if it has the == method. Otherwise,
	// the underlying type "wins". For instance
	//
	//     interface{ comparable; type []byte }
	//
	// is not comparable because []byte is not comparable.
	if  := asTypeParam();  != nil && optype() == theTop {
		return .Bound()._IsComparable()
	}

	switch t := optype().(type) {
	case *Basic:
		// assume invalid types to be comparable
		// to avoid follow-up errors
		return .kind != UntypedNil
	case *Pointer, *Interface, *Chan:
		return true
	case *Struct:
		for ,  := range .fields {
			if !(.typ, ) {
				return false
			}
		}
		return true
	case *Array:
		return (.elem, )
	case *_Sum:
		 := func( Type) bool {
			return (, )
		}
		return .is()
	case *_TypeParam:
		return .Bound()._IsComparable()
	}
	return false
}

// hasNil reports whether a type includes the nil value.
func hasNil( Type) bool {
	switch t := optype().(type) {
	case *Basic:
		return .kind == UnsafePointer
	case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan:
		return true
	case *_Sum:
		return .is()
	}
	return false
}

// identical reports whether x and y are identical types.
// Receivers of Signature types are ignored.
func ( *Checker) (,  Type) bool {
	return .identical0(, , true, nil)
}

// identicalIgnoreTags reports whether x and y are identical types if tags are ignored.
// Receivers of Signature types are ignored.
func ( *Checker) (,  Type) bool {
	return .identical0(, , false, nil)
}

// 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 ( *Checker) (,  Type,  bool,  *ifacePair) bool {
	// types must be expanded for comparison
	 = expandf()
	 = expandf()

	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:
		// 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.
		// Generic functions must also have matching type parameter lists, but for the
		// parameter names.
		if ,  := .(*Signature);  {
			return .variadic == .variadic &&
				.identicalTParams(.tparams, .tparams, , ) &&
				.(.params, .params, , ) &&
				.(.results, .results, , )
		}

	case *_Sum:
		// Two sum types are identical if they contain the same types.
		// (Sum types always consist of at least two types. Also, the
		// the set (list) of types in a sum type consists of unique
		// types - each type appears exactly once. Thus, two sum types
		// must contain the same number of types to have chance of
		// being equal.
		if ,  := .(*_Sum);  && len(.types) == len(.types) {
			// Every type in x.types must be in y.types.
			// Quadratic algorithm, but probably good enough for now.
			// TODO(gri) we need a fast quick type ID/hash for all types.
		:
			for ,  := range .types {
				for ,  := range .types {
					if Identical(, ) {
						continue  // x is in y.types
					}
				}
				return false // x is not in y.types
			}
			return true
		}

	case *Interface:
		// Two interface types are identical if they have the same set of methods with
		// the same names and identical function types. Lower-case method names from
		// different packages are always different. The order of the methods is irrelevant.
		if ,  := .(*Interface);  {
			// If identical0 is called (indirectly) via an external API entry point
			// (such as Identical, IdenticalIgnoreTags, etc.), check is nil. But in
			// that case, interfaces are expected to be complete and lazy completion
			// here is not needed.
			if  != nil {
				.completeInterface(token.NoPos, )
				.completeInterface(token.NoPos, )
			}
			 := .allMethods
			 := .allMethods
			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);  {
			// 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 *instance:
	//	unreachable since types are expanded

	case *bottom, *top:
		// Either both types are theBottom, or both are theTop in which
		// case the initial x == y check will have caught them. Otherwise
		// they are not identical.

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

	default:
		unreachable()
	}

	return false
}

func ( *Checker) (,  []*TypeName,  bool,  *ifacePair) bool {
	if len() != len() {
		return false
	}
	for ,  := range  {
		 := []
		if !.identical0(.typ.(*_TypeParam).bound, .typ.(*_TypeParam).bound, , ) {
			return false
		}
	}
	return true
}

// 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 
}