// Copyright 2021 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.

package types

import (
	
	
	
	. 
	
	
)

// ----------------------------------------------------------------------------
// API

// A Signature represents a (non-builtin) function or method type.
// The receiver is ignored when comparing signatures for identity.
type Signature struct {
	// We need to keep the scope in Signature (rather than passing it around
	// and store it in the Func Object) because when type-checking a function
	// literal we call the general type checker which returns a general Type.
	// We then unpack the *Signature and use the scope for the literal body.
	rparams  *TypeParamList // receiver type parameters from left to right, or nil
	tparams  *TypeParamList // type parameters from left to right, or nil
	scope    *Scope         // function scope for package-local and non-instantiated signatures; nil otherwise
	recv     *Var           // nil if not a method
	params   *Tuple         // (incoming) parameters from left to right; or nil
	results  *Tuple         // (outgoing) results from left to right; or nil
	variadic bool           // true if the last parameter's type is of the form ...T (or string, for append built-in only)
}

// NewSignature returns a new function type for the given receiver, parameters,
// and results, either of which may be nil. If variadic is set, the function
// is variadic, it must have at least one parameter, and the last parameter
// must be of unnamed slice type.
//
// Deprecated: Use [NewSignatureType] instead which allows for type parameters.
func ( *Var, ,  *Tuple,  bool) *Signature {
	return NewSignatureType(, nil, nil, , , )
}

// NewSignatureType creates a new function type for the given receiver,
// receiver type parameters, type parameters, parameters, and results. If
// variadic is set, params must hold at least one parameter and the last
// parameter's core type must be of unnamed slice or bytestring type.
// If recv is non-nil, typeParams must be empty. If recvTypeParams is
// non-empty, recv must be non-nil.
func ( *Var, ,  []*TypeParam, ,  *Tuple,  bool) *Signature {
	if  {
		 := .Len()
		if  == 0 {
			panic("variadic function must have at least one parameter")
		}
		 := coreString(.At( - 1).typ)
		if ,  := .(*Slice); ! && !isString() {
			panic(fmt.Sprintf("got %s, want variadic parameter with unnamed slice type or string as core type", .String()))
		}
	}
	 := &Signature{recv: , params: , results: , variadic: }
	if len() != 0 {
		if  == nil {
			panic("function with receiver type parameters must have a receiver")
		}
		.rparams = bindTParams()
	}
	if len() != 0 {
		if  != nil {
			panic("function with type parameters cannot have a receiver")
		}
		.tparams = bindTParams()
	}
	return 
}

// Recv returns the receiver of signature s (if a method), or nil if a
// function. It is ignored when comparing signatures for identity.
//
// For an abstract method, Recv returns the enclosing interface either
// as a *[Named] or an *[Interface]. Due to embedding, an interface may
// contain methods whose receiver type is a different interface.
func ( *Signature) () *Var { return .recv }

// TypeParams returns the type parameters of signature s, or nil.
func ( *Signature) () *TypeParamList { return .tparams }

// RecvTypeParams returns the receiver type parameters of signature s, or nil.
func ( *Signature) () *TypeParamList { return .rparams }

// Params returns the parameters of signature s, or nil.
func ( *Signature) () *Tuple { return .params }

// Results returns the results of signature s, or nil.
func ( *Signature) () *Tuple { return .results }

// Variadic reports whether the signature s is variadic.
func ( *Signature) () bool { return .variadic }

func ( *Signature) () Type { return  }
func ( *Signature) () string   { return TypeString(, nil) }

// ----------------------------------------------------------------------------
// Implementation

// funcType type-checks a function or method type.
func ( *Checker) ( *Signature,  *ast.FieldList,  *ast.FuncType) {
	.openScope(, "function")
	.scope.isFunc = true
	.recordScope(, .scope)
	.scope = .scope
	defer .closeScope()

	// collect method receiver, if any
	var  *Var
	var  *TypeParamList
	if  != nil && .NumFields() > 0 {
		// We have at least one receiver; make sure we don't have more than one.
		if  := len(.List);  > 1 {
			.error(.List[-1], InvalidRecv, "method has multiple receivers")
			// continue with first one
		}
		// all type parameters' scopes start after the method name
		 := .Pos()
		,  = .collectRecv(.List[0], )
	}

	// collect and declare function type parameters
	if .TypeParams != nil {
		// Always type-check method type parameters but complain that they are not allowed.
		// (A separate check is needed when type-checking interface method signatures because
		// they don't have a receiver specification.)
		if  != nil {
			.error(.TypeParams, InvalidMethodTypeParams, "methods cannot have type parameters")
		}
		.collectTypeParams(&.tparams, .TypeParams)
	}

	// collect ordinary and result parameters
	, ,  := .collectParams(.Params, true)
	, ,  := .collectParams(.Results, false)

	// declare named receiver, ordinary, and result parameters
	 := .End() // all parameter's scopes start after the signature
	if  != nil && .name != "" {
		.declare(.scope, .List[0].Names[0], , )
	}
	.declareParams(, , )
	.declareParams(, , )

	.recv = 
	.rparams = 
	.params = NewTuple(...)
	.results = NewTuple(...)
	.variadic = 
}

// collectRecv extracts the method receiver and its type parameters (if any) from rparam.
// It declares the type parameters (but not the receiver) in the current scope, and
// returns the receiver variable and its type parameter list (if any).
func ( *Checker) ( *ast.Field,  token.Pos) (*Var, *TypeParamList) {
	// Unpack the receiver parameter which is of the form
	//
	//	"(" [rfield] ["*"] rbase ["[" rtparams "]"] ")"
	//
	// The receiver name rname, the pointer indirection, and the
	// receiver type parameters rtparams may not be present.
	, ,  := .unpackRecv(.Type, true)

	// Determine the receiver base type.
	var  Type = Typ[Invalid]
	var  *TypeParamList
	if  == nil {
		// If there are no type parameters, we can simply typecheck rparam.Type.
		// If that is a generic type, varType will complain.
		// Further receiver constraints will be checked later, with validRecv.
		// We use rparam.Type (rather than base) to correctly record pointer
		// and parentheses in types.Info (was bug, see go.dev/issue/68639).
		 = .varType(.Type)
		// Defining new methods on instantiated (alias or defined) types is not permitted.
		// Follow literal pointer/alias type chain and check.
		// (Correct code permits at most one pointer indirection, but for this check it
		// doesn't matter if we have multiple pointers.)
		,  := unpointer().(*Alias) // recvType is not generic per above
		for  != nil {
			 := unpointer(.fromRHS)
			if ,  := .(genericType);  != nil && .TypeParams() != nil {
				.errorf(, InvalidRecv, "cannot define new methods on instantiated type %s", )
				 = Typ[Invalid] // avoid follow-on errors by Checker.validRecv
				break
			}
			, _ = .(*Alias)
		}
	} else {
		// If there are type parameters, rbase must denote a generic base type.
		// Important: rbase must be resolved before declaring any receiver type
		// parameters (wich may have the same name, see below).
		var  *Named // nil if not valid
		var  string
		if  := .genericType(, &); isValid() {
			switch t := .(type) {
			case *Named:
				 = 
			case *Alias:
				// Methods on generic aliases are not permitted.
				// Only report an error if the alias type is valid.
				if isValid(unalias()) {
					.errorf(, InvalidRecv, "cannot define new methods on generic alias type %s", )
				}
				// Ok to continue but do not set basetype in this case so that
				// recvType remains invalid (was bug, see go.dev/issue/70417).
			default:
				panic("unreachable")
			}
		} else {
			if  != "" {
				.errorf(, InvalidRecv, "%s", )
			}
			// Ok to continue but do not set baseType (see comment above).
		}

		// Collect the type parameters declared by the receiver (see also
		// Checker.collectTypeParams). The scope of the type parameter T in
		// "func (r T[T]) f() {}" starts after f, not at r, so we declare it
		// after typechecking rbase (see go.dev/issue/52038).
		 := make([]*TypeParam, len())
		for ,  := range  {
			 := .declareTypeParam(, )
			[] = 
			// For historic reasons, type parameters in receiver type expressions
			// are considered both definitions and uses and thus must be recorded
			// in the Info.Uses and Info.Types maps (see go.dev/issue/68670).
			.recordUse(, .obj)
			.recordTypeAndValue(, typexpr, , nil)
		}
		 = bindTParams()

		// Get the type parameter bounds from the receiver base type
		// and set them for the respective (local) receiver type parameters.
		if  != nil {
			 := .TypeParams().list()
			if len() == len() {
				 := makeRenameMap(, )
				for ,  := range  {
					 := []
					.mono.recordCanon(, )
					// baseTPar.bound is possibly parameterized by other type parameters
					// defined by the generic base type. Substitute those parameters with
					// the receiver type parameters declared by the current method.
					.bound = .subst(.obj.pos, .bound, , nil, .context())
				}
			} else {
				 := measure(len(), "type parameter")
				.errorf(, BadRecv, "receiver declares %s, but receiver base type declares %d", , len())
			}

			// The type parameters declared by the receiver also serve as
			// type arguments for the receiver type. Instantiate the receiver.
			.verifyVersionf(, go1_18, "type instantiation")
			 := make([]Type, len())
			for ,  := range  {
				[] = 
			}
			 = .instance(.Type.Pos(), , , nil, .context())
			.recordInstance(, , )

			// Reestablish pointerness if needed (but avoid a pointer to an invalid type).
			if  && isValid() {
				 = NewPointer()
			}

			.recordParenthesizedRecvTypes(.Type, )
		}
	}

	// Make sure we have no more than one receiver name.
	var  *ast.Ident
	if  := len(.Names);  >= 1 {
		if  > 1 {
			.error(.Names[-1], InvalidRecv, "method has multiple receivers")
		}
		 = .Names[0]
	}

	// Create the receiver parameter.
	// recvType is invalid if baseType was never set.
	var  *Var
	if  != nil && .Name != "" {
		// named receiver
		 = NewParam(.Pos(), .pkg, .Name, )
		// In this case, the receiver is declared by the caller
		// because it must be declared after any type parameters
		// (otherwise it might shadow one of them).
	} else {
		// anonymous receiver
		 = NewParam(.Pos(), .pkg, "", )
		.recordImplicit(, )
	}

	// Delay validation of receiver type as it may cause premature expansion of types
	// the receiver type is dependent on (see go.dev/issue/51232, go.dev/issue/51233).
	.later(func() {
		.validRecv(, )
	}).describef(, "validRecv(%s)", )

	return , 
}

func unpointer( Type) Type {
	for {
		,  := .(*Pointer)
		if  == nil {
			return 
		}
		 = .base
	}
}

// recordParenthesizedRecvTypes records parenthesized intermediate receiver type
// expressions that all map to the same type, by recursively unpacking expr and
// recording the corresponding type for it. Example:
//
//	expression  -->  type
//	----------------------
//	(*(T[P]))        *T[P]
//	 *(T[P])         *T[P]
//	  (T[P])          T[P]
//	   T[P]           T[P]
func ( *Checker) ( ast.Expr,  Type) {
	for {
		.recordTypeAndValue(, typexpr, , nil)
		switch e := .(type) {
		case *ast.ParenExpr:
			 = .X
		case *ast.StarExpr:
			 = .X
			// In a correct program, typ must be an unnamed
			// pointer type. But be careful and don't panic.
			,  := .(*Pointer)
			if  == nil {
				return // something is wrong
			}
			 = .base
		default:
			return // cannot unpack any further
		}
	}
}

// collectParams collects (but does not declare) all parameters of list and returns
// the list of parameter names, corresponding parameter variables, and whether the
// parameter list is variadic. Anonymous parameters are recorded with nil names.
func ( *Checker) ( *ast.FieldList,  bool) ( []*ast.Ident,  []*Var,  bool) {
	if  == nil {
		return
	}

	var ,  bool
	for ,  := range .List {
		 := .Type
		if ,  := .(*ast.Ellipsis);  != nil {
			 = .Elt
			if  &&  == len(.List)-1 && len(.Names) <= 1 {
				 = true
			} else {
				.softErrorf(, MisplacedDotDotDot, "can only use ... with final parameter in list")
				// ignore ... and continue
			}
		}
		 := .varType()
		// The parser ensures that f.Tag is nil and we don't
		// care if a constructed AST contains a non-nil tag.
		if len(.Names) > 0 {
			// named parameter
			for ,  := range .Names {
				if .Name == "" {
					.error(, InvalidSyntaxTree, "anonymous parameter")
					// ok to continue
				}
				 := NewParam(.Pos(), .pkg, .Name, )
				// named parameter is declared by caller
				 = append(, )
				 = append(, )
			}
			 = true
		} else {
			// anonymous parameter
			 := NewParam(.Pos(), .pkg, "", )
			.recordImplicit(, )
			 = append(, nil)
			 = append(, )
			 = true
		}
	}

	if  &&  {
		.error(, InvalidSyntaxTree, "list contains both named and anonymous parameters")
		// ok to continue
	}

	// For a variadic function, change the last parameter's type from T to []T.
	// Since we type-checked T rather than ...T, we also need to retro-actively
	// record the type for ...T.
	if  {
		 := [len()-1]
		.typ = &Slice{elem: .typ}
		.recordTypeAndValue(.List[len(.List)-1].Type, typexpr, .typ, nil)
	}

	return
}

// declareParams declares each named parameter in the current scope.
func ( *Checker) ( []*ast.Ident,  []*Var,  token.Pos) {
	for ,  := range  {
		if  != nil && .Name != "" {
			.declare(.scope, , [], )
		}
	}
}

// validRecv verifies that the receiver satisfies its respective spec requirements
// and reports an error otherwise.
func ( *Checker) ( positioner,  *Var) {
	// spec: "The receiver type must be of the form T or *T where T is a type name."
	,  := deref(.typ)
	 := Unalias()
	if !isValid() {
		return // error was reported before
	}
	// spec: "The type denoted by T is called the receiver base type; it must not
	// be a pointer or interface type and it must be declared in the same package
	// as the method."
	switch T := .(type) {
	case *Named:
		if .obj.pkg != .pkg || isCGoTypeObj(.fset, .obj) {
			.errorf(, InvalidRecv, "cannot define new methods on non-local type %s", )
			break
		}
		var  string
		switch u := .under().(type) {
		case *Basic:
			// unsafe.Pointer is treated like a regular pointer
			if .kind == UnsafePointer {
				 = "unsafe.Pointer"
			}
		case *Pointer, *Interface:
			 = "pointer or interface type"
		case *TypeParam:
			// The underlying type of a receiver base type cannot be a
			// type parameter: "type T[P any] P" is not a valid declaration.
			panic("unreachable")
		}
		if  != "" {
			.errorf(, InvalidRecv, "invalid receiver type %s (%s)", , )
		}
	case *Basic:
		.errorf(, InvalidRecv, "cannot define new methods on non-local type %s", )
	default:
		.errorf(, InvalidRecv, "invalid receiver type %s", .typ)
	}
}

// isCGoTypeObj reports whether the given type name was created by cgo.
func isCGoTypeObj( *token.FileSet,  *TypeName) bool {
	return strings.HasPrefix(.name, "_Ctype_") ||
		strings.HasPrefix(filepath.Base(.File(.pos).Name()), "_cgo_")
}