// Copyright 2013 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 type-checking of identifiers and type expressions.

package types

import (
	
	
	
	
	
)

// ident type-checks identifier e and initializes x with the value or type of e.
// If an error occurred, x.mode is set to invalid.
// For the meaning of def, see Checker.definedType, below.
// If wantType is set, the identifier e is expected to denote a type.
func ( *Checker) ( *operand,  *ast.Ident,  *Named,  bool) {
	.mode = invalid
	.expr = 

	// Note that we cannot use check.lookup here because the returned scope
	// may be different from obj.Parent(). See also Scope.LookupParent doc.
	,  := .scope.LookupParent(.Name, .pos)
	switch  {
	case nil:
		if .Name == "_" {
			// Blank identifiers are never declared, but the current identifier may
			// be a placeholder for a receiver type parameter. In this case we can
			// resolve its type and object from Checker.recvTParamMap.
			if  := .recvTParamMap[];  != nil {
				.mode = typexpr
				.typ = 
			} else {
				.error(, _InvalidBlank, "cannot use _ as value or type")
			}
		} else {
			.errorf(, _UndeclaredName, "undeclared name: %s", .Name)
		}
		return
	case universeAny, universeComparable:
		if !.allowVersion(.pkg, 1, 18) {
			.versionErrorf(, _UndeclaredName, "go1.18", "predeclared %s", .Name)
			return // avoid follow-on errors
		}
	}
	.recordUse(, )

	// Type-check the object.
	// Only call Checker.objDecl if the object doesn't have a type yet
	// (in which case we must actually determine it) or the object is a
	// TypeName and we also want a type (in which case we might detect
	// a cycle which needs to be reported). Otherwise we can skip the
	// call and avoid a possible cycle error in favor of the more
	// informative "not a type/value" error that this function's caller
	// will issue (see issue #25790).
	 := .Type()
	if ,  := .(*TypeName);  == nil ||  &&  {
		.objDecl(, )
		 = .Type() // type must have been assigned by Checker.objDecl
	}
	assert( != nil)

	// The object may have been dot-imported.
	// If so, mark the respective package as used.
	// (This code is only needed for dot-imports. Without them,
	// we only have to mark variables, see *Var case below).
	if  := .dotImportMap[dotImportKey{, .Name()}];  != nil {
		.used = true
	}

	switch obj := .(type) {
	case *PkgName:
		.errorf(, _InvalidPkgUse, "use of package %s not in selector", .name)
		return

	case *Const:
		.addDeclDep()
		if  == Typ[Invalid] {
			return
		}
		if  == universeIota {
			if .iota == nil {
				.errorf(, _InvalidIota, "cannot use iota outside constant declaration")
				return
			}
			.val = .iota
		} else {
			.val = .val
		}
		assert(.val != nil)
		.mode = constant_

	case *TypeName:
		if .isBrokenAlias() {
			.errorf(, _InvalidDeclCycle, "invalid use of type alias %s in recursive type (see issue #50729)", .name)
			return
		}
		.mode = typexpr

	case *Var:
		// It's ok to mark non-local variables, but ignore variables
		// from other packages to avoid potential race conditions with
		// dot-imported variables.
		if .pkg == .pkg {
			.used = true
		}
		.addDeclDep()
		if  == Typ[Invalid] {
			return
		}
		.mode = variable

	case *Func:
		.addDeclDep()
		.mode = value

	case *Builtin:
		.id = .id
		.mode = builtin

	case *Nil:
		.mode = value

	default:
		unreachable()
	}

	.typ = 
}

// typ type-checks the type expression e and returns its type, or Typ[Invalid].
// The type must not be an (uninstantiated) generic type.
func ( *Checker) ( ast.Expr) Type {
	return .definedType(, nil)
}

// varType type-checks the type expression e and returns its type, or Typ[Invalid].
// The type must not be an (uninstantiated) generic type and it must not be a
// constraint interface.
func ( *Checker) ( ast.Expr) Type {
	 := .definedType(, nil)
	.validVarType(, )
	return 
}

// validVarType reports an error if typ is a constraint interface.
// The expression e is used for error reporting, if any.
func ( *Checker) ( ast.Expr,  Type) {
	// If we have a type parameter there's nothing to do.
	if isTypeParam() {
		return
	}

	// We don't want to call under() or complete interfaces while we are in
	// the middle of type-checking parameter declarations that might belong
	// to interface methods. Delay this check to the end of type-checking.
	.later(func() {
		if ,  := under().(*Interface);  != nil {
			 := computeInterfaceTypeSet(, .Pos(), ) // TODO(gri) is this the correct position?
			if !.IsMethodSet() {
				if .comparable {
					.softErrorf(, _MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface is (or embeds) comparable", )
				} else {
					.softErrorf(, _MisplacedConstraintIface, "cannot use type %s outside a type constraint: interface contains type constraints", )
				}
			}
		}
	}).describef(, "check var type %s", )
}

// definedType is like typ but also accepts a type name def.
// If def != nil, e is the type specification for the defined type def, declared
// in a type declaration, and def.underlying will be set to the type of e before
// any components of e are type-checked.
func ( *Checker) ( ast.Expr,  *Named) Type {
	 := .typInternal(, )
	assert(isTyped())
	if isGeneric() {
		.errorf(, _WrongTypeArgCount, "cannot use generic type %s without instantiation", )
		 = Typ[Invalid]
	}
	.recordTypeAndValue(, typexpr, , nil)
	return 
}

// genericType is like typ but the type must be an (uninstantiated) generic
// type. If reason is non-nil and the type expression was a valid type but not
// generic, reason will be populated with a message describing the error.
func ( *Checker) ( ast.Expr,  *string) Type {
	 := .typInternal(, nil)
	assert(isTyped())
	if  != Typ[Invalid] && !isGeneric() {
		if  != nil {
			* = .sprintf("%s is not a generic type", )
		}
		 = Typ[Invalid]
	}
	// TODO(gri) what is the correct call below?
	.recordTypeAndValue(, typexpr, , nil)
	return 
}

// goTypeName returns the Go type name for typ and
// removes any occurrences of "types." from that name.
func goTypeName( Type) string {
	return strings.ReplaceAll(fmt.Sprintf("%T", ), "types.", "")
}

// typInternal drives type checking of types.
// Must only be called by definedType or genericType.
func ( *Checker) ( ast.Expr,  *Named) ( Type) {
	if trace {
		.trace(.Pos(), "-- type %s", )
		.indent++
		defer func() {
			.indent--
			var  Type
			if  != nil {
				// Calling under() here may lead to endless instantiations.
				// Test case: type T[P any] *T[P]
				 = safeUnderlying()
			}
			if  ==  {
				.trace(.Pos(), "=> %s // %s", , goTypeName())
			} else {
				.trace(.Pos(), "=> %s (under = %s) // %s", , , goTypeName())
			}
		}()
	}

	switch e := .(type) {
	case *ast.BadExpr:
		// ignore - error reported before

	case *ast.Ident:
		var  operand
		.ident(&, , , true)

		switch .mode {
		case typexpr:
			 := .typ
			.setUnderlying()
			return 
		case invalid:
			// ignore - error reported before
		case novalue:
			.errorf(&, _NotAType, "%s used as type", &)
		default:
			.errorf(&, _NotAType, "%s is not a type", &)
		}

	case *ast.SelectorExpr:
		var  operand
		.selector(&, , )

		switch .mode {
		case typexpr:
			 := .typ
			.setUnderlying()
			return 
		case invalid:
			// ignore - error reported before
		case novalue:
			.errorf(&, _NotAType, "%s used as type", &)
		default:
			.errorf(&, _NotAType, "%s is not a type", &)
		}

	case *ast.IndexExpr, *ast.IndexListExpr:
		 := typeparams.UnpackIndexExpr()
		if !.allowVersion(.pkg, 1, 18) {
			.softErrorf(inNode(, .Lbrack), _UnsupportedFeature, "type instantiation requires go1.18 or later")
		}
		return .instantiatedType(, )

	case *ast.ParenExpr:
		// Generic types must be instantiated before they can be used in any form.
		// Consequently, generic types cannot be parenthesized.
		return .definedType(.X, )

	case *ast.ArrayType:
		if .Len == nil {
			 := new(Slice)
			.setUnderlying()
			.elem = .varType(.Elt)
			return 
		}

		 := new(Array)
		.setUnderlying()
		.len = .arrayLength(.Len)
		.elem = .varType(.Elt)
		if .len >= 0 {
			return 
		}

	case *ast.Ellipsis:
		// dots are handled explicitly where they are legal
		// (array composite literals and parameter lists)
		.error(, _InvalidDotDotDot, "invalid use of '...'")
		.use(.Elt)

	case *ast.StructType:
		 := new(Struct)
		.setUnderlying()
		.structType(, )
		return 

	case *ast.StarExpr:
		 := new(Pointer)
		.base = Typ[Invalid] // avoid nil base in invalid recursive type declaration
		.setUnderlying()
		.base = .varType(.X)
		return 

	case *ast.FuncType:
		 := new(Signature)
		.setUnderlying()
		.funcType(, nil, )
		return 

	case *ast.InterfaceType:
		 := .newInterface()
		.setUnderlying()
		.interfaceType(, , )
		return 

	case *ast.MapType:
		 := new(Map)
		.setUnderlying()

		.key = .varType(.Key)
		.elem = .varType(.Value)

		// spec: "The comparison operators == and != must be fully defined
		// for operands of the key type; thus the key type must not be a
		// function, map, or slice."
		//
		// Delay this check because it requires fully setup types;
		// it is safe to continue in any case (was issue 6667).
		.later(func() {
			if !Comparable(.key) {
				var  string
				if isTypeParam(.key) {
					 = " (missing comparable constraint)"
				}
				.errorf(.Key, _IncomparableMapKey, "incomparable map key type %s%s", .key, )
			}
		}).describef(.Key, "check map key %s", .key)

		return 

	case *ast.ChanType:
		 := new(Chan)
		.setUnderlying()

		 := SendRecv
		switch .Dir {
		case ast.SEND | ast.RECV:
			// nothing to do
		case ast.SEND:
			 = SendOnly
		case ast.RECV:
			 = RecvOnly
		default:
			.invalidAST(, "unknown channel direction %d", .Dir)
			// ok to continue
		}

		.dir = 
		.elem = .varType(.Value)
		return 

	default:
		.errorf(, _NotAType, "%s is not a type", )
	}

	 := Typ[Invalid]
	.setUnderlying()
	return 
}

func ( *Checker) ( *typeparams.IndexExpr,  *Named) ( Type) {
	if trace {
		.trace(.Pos(), "-- instantiating type %s with %s", .X, .Indices)
		.indent++
		defer func() {
			.indent--
			// Don't format the underlying here. It will always be nil.
			.trace(.Pos(), "=> %s", )
		}()
	}

	var  string
	 := .genericType(.X, &)
	if  != "" {
		.invalidOp(.Orig, _NotAGenericType, "%s (%s)", .Orig, )
	}
	if  == Typ[Invalid] {
		return  // error already reported
	}

	,  := .(*Named)
	if  == nil {
		panic(fmt.Sprintf("%v: cannot instantiate %v", .Pos(), ))
	}

	// evaluate arguments
	 := .typeList(.Indices)
	if  == nil {
		.setUnderlying(Typ[Invalid]) // avoid errors later due to lazy instantiation
		return Typ[Invalid]
	}

	// create the instance
	 := .instance(.Pos(), , , nil, .context()).(*Named)
	.setUnderlying()

	// orig.tparams may not be set up, so we need to do expansion later.
	.later(func() {
		// This is an instance from the source, not from recursive substitution,
		// and so it must be resolved during type-checking so that we can report
		// errors.
		.recordInstance(.Orig, .TypeArgs().list(), )

		if .validateTArgLen(.Pos(), .TypeParams().Len(), .TypeArgs().Len()) {
			if ,  := .verify(.Pos(), .TypeParams().list(), .TypeArgs().list(), .context());  != nil {
				// best position for error reporting
				 := .Pos()
				if  < len(.Indices) {
					 = .Indices[].Pos()
				}
				.softErrorf(atPos(), _InvalidTypeArg, .Error())
			} else {
				.mono.recordInstance(.pkg, .Pos(), .TypeParams().list(), .TypeArgs().list(), .Indices)
			}
		}

		// TODO(rfindley): remove this call: we don't need to call validType here,
		// as cycles can only occur for types used inside a Named type declaration,
		// and so it suffices to call validType from declared types.
		.validType()
	}).describef(, "resolve instance %s", )

	return 
}

// arrayLength type-checks the array length expression e
// and returns the constant length >= 0, or a value < 0
// to indicate an error (and thus an unknown length).
func ( *Checker) ( ast.Expr) int64 {
	// If e is an identifier, the array declaration might be an
	// attempt at a parameterized type declaration with missing
	// constraint. Provide an error message that mentions array
	// length.
	if ,  := .(*ast.Ident);  != nil {
		 := .lookup(.Name)
		if  == nil {
			.errorf(, _InvalidArrayLen, "undeclared name %s for array length", .Name)
			return -1
		}
		if ,  := .(*Const); ! {
			.errorf(, _InvalidArrayLen, "invalid array length %s", .Name)
			return -1
		}
	}

	var  operand
	.expr(&, )
	if .mode != constant_ {
		if .mode != invalid {
			.errorf(&, _InvalidArrayLen, "array length %s must be constant", &)
		}
		return -1
	}

	if isUntyped(.typ) || isInteger(.typ) {
		if  := constant.ToInt(.val); .Kind() == constant.Int {
			if representableConst(, , Typ[Int], nil) {
				if ,  := constant.Int64Val();  &&  >= 0 {
					return 
				}
				.errorf(&, _InvalidArrayLen, "invalid array length %s", &)
				return -1
			}
		}
	}

	.errorf(&, _InvalidArrayLen, "array length %s must be integer", &)
	return -1
}

// typeList provides the list of types corresponding to the incoming expression list.
// If an error occurred, the result is nil, but all list elements were type-checked.
func ( *Checker) ( []ast.Expr) []Type {
	 := make([]Type, len()) // res != nil even if len(list) == 0
	for ,  := range  {
		 := .varType()
		if  == Typ[Invalid] {
			 = nil
		}
		if  != nil {
			[] = 
		}
	}
	return 
}