Source file src/go/types/signature.go

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package types
     6  
     7  import (
     8  	"fmt"
     9  	"go/ast"
    10  	"go/token"
    11  	. "internal/types/errors"
    12  	"path/filepath"
    13  	"strings"
    14  )
    15  
    16  // ----------------------------------------------------------------------------
    17  // API
    18  
    19  // A Signature represents a (non-builtin) function or method type.
    20  // The receiver is ignored when comparing signatures for identity.
    21  type Signature struct {
    22  	// We need to keep the scope in Signature (rather than passing it around
    23  	// and store it in the Func Object) because when type-checking a function
    24  	// literal we call the general type checker which returns a general Type.
    25  	// We then unpack the *Signature and use the scope for the literal body.
    26  	rparams  *TypeParamList // receiver type parameters from left to right, or nil
    27  	tparams  *TypeParamList // type parameters from left to right, or nil
    28  	scope    *Scope         // function scope for package-local and non-instantiated signatures; nil otherwise
    29  	recv     *Var           // nil if not a method
    30  	recvold  *Var           // receiver dropped via method selection; or nil
    31  	params   *Tuple         // (incoming) parameters from left to right; or nil
    32  	results  *Tuple         // (outgoing) results from left to right; or nil
    33  	variadic bool           // true if the last parameter's type is of the form ...T
    34  
    35  	// If recvold is the sentinel value [methExpr], then recvold should
    36  	// instead be sourced from params[0]. Otherwise, recvold points to
    37  	// the receiver of the original method signature from which this
    38  	// function signature was cloned via a selector expression.
    39  
    40  	// If variadic, the last element of params ordinarily has an
    41  	// unnamed Slice type. As a special case, in a call to append,
    42  	// it may be string, or a TypeParam T whose typeset ⊇ {string, []byte}.
    43  	// It may even be a named []byte type if a client instantiates
    44  	// T at such a type.
    45  }
    46  
    47  // sentinel value for detecting method expressions
    48  var methodExprSentinel = &Var{}
    49  
    50  // NewSignature returns a new function type for the given receiver, parameters,
    51  // and results, either of which may be nil. If variadic is set, the function
    52  // is variadic, it must have at least one parameter, and the last parameter
    53  // must be of unnamed slice type.
    54  //
    55  // Deprecated: Use [NewSignatureType] instead which allows for type parameters.
    56  //
    57  //go:fix inline
    58  func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
    59  	return NewSignatureType(recv, nil, nil, params, results, variadic)
    60  }
    61  
    62  // NewSignatureType creates a new function type for the given receiver,
    63  // receiver type parameters, type parameters, parameters, and results.
    64  //
    65  // If variadic is set, params must hold at least one parameter and the
    66  // last parameter must be an unnamed slice or a type parameter whose
    67  // type set has an unnamed slice as common underlying type.
    68  //
    69  // As a special case, to support append([]byte, str...), for variadic
    70  // signatures the last parameter may also be a string type, or a type
    71  // parameter containing a mix of byte slices and string types in its
    72  // type set. It may even be a named []byte slice type resulting from
    73  // instantiation of such a type parameter.
    74  //
    75  // If recvTypeParams is non-empty, recv must be non-nil.
    76  func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
    77  	if variadic {
    78  		n := params.Len()
    79  		if n == 0 {
    80  			panic("variadic function must have at least one parameter")
    81  		}
    82  		last := params.At(n - 1).typ
    83  		var S *Slice
    84  		for t := range typeset(last) {
    85  			if t == nil {
    86  				break
    87  			}
    88  			var s *Slice
    89  			if isString(t) {
    90  				s = NewSlice(universeByte)
    91  			} else {
    92  				// Variadic Go functions have a last parameter of type []T,
    93  				// suggesting we should reject a named slice type B here.
    94  				//
    95  				// However, a call to built-in append(slice, x...)
    96  				// where x has a TypeParam type [T ~string | ~[]byte],
    97  				// has the type func([]byte, T). Since a client may
    98  				// instantiate this type at T=B, we must permit
    99  				// named slice types, even when this results in a
   100  				// signature func([]byte, B) where type B []byte.
   101  				//
   102  				// (The caller of NewSignatureType may have no way to
   103  				// know that it is dealing with the append special case.)
   104  				s, _ = t.Underlying().(*Slice)
   105  			}
   106  			if S == nil {
   107  				S = s
   108  			} else if s == nil || !Identical(S, s) {
   109  				S = nil
   110  				break
   111  			}
   112  		}
   113  		if S == nil {
   114  			panic(fmt.Sprintf("got %s, want variadic parameter of slice or string type", last))
   115  		}
   116  	}
   117  	sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
   118  	if len(recvTypeParams) != 0 {
   119  		if recv == nil {
   120  			panic("function with receiver type parameters must have a receiver")
   121  		}
   122  		sig.rparams = bindTParams(recvTypeParams)
   123  	}
   124  	if len(typeParams) != 0 {
   125  		sig.tparams = bindTParams(typeParams)
   126  	}
   127  	return sig
   128  }
   129  
   130  // Recv returns the receiver of signature s (if a method), or nil if a
   131  // function. It is ignored when comparing signatures for identity.
   132  //
   133  // For an abstract method, Recv returns the enclosing interface either
   134  // as a *[Named] or an *[Interface]. Due to embedding, an interface may
   135  // contain methods whose receiver type is a different interface.
   136  func (s *Signature) Recv() *Var { return s.recv }
   137  
   138  // TypeParams returns the type parameters of signature s, or nil.
   139  func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
   140  
   141  // RecvTypeParams returns the receiver type parameters of signature s, or nil.
   142  func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
   143  
   144  // Params returns the parameters of signature s, or nil.
   145  // See [NewSignatureType] for details of variadic functions.
   146  func (s *Signature) Params() *Tuple { return s.params }
   147  
   148  // Results returns the results of signature s, or nil.
   149  func (s *Signature) Results() *Tuple { return s.results }
   150  
   151  // Variadic reports whether the signature s is variadic.
   152  func (s *Signature) Variadic() bool { return s.variadic }
   153  
   154  func (s *Signature) Underlying() Type { return s }
   155  func (s *Signature) String() string   { return TypeString(s, nil) }
   156  
   157  // ----------------------------------------------------------------------------
   158  // Implementation
   159  
   160  // funcType type-checks a function or method type.
   161  func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) {
   162  	check.openScope(ftyp, "function")
   163  	check.scope.isFunc = true
   164  	check.recordScope(ftyp, check.scope)
   165  	sig.scope = check.scope
   166  	defer check.closeScope()
   167  
   168  	// collect method receiver, if any
   169  	var recv *Var
   170  	var rparams *TypeParamList
   171  	if recvPar != nil && recvPar.NumFields() > 0 {
   172  		// We have at least one receiver; make sure we don't have more than one.
   173  		if n := len(recvPar.List); n > 1 {
   174  			check.error(recvPar.List[n-1], InvalidRecv, "method has multiple receivers")
   175  			// continue with first one
   176  		}
   177  		// all type parameters' scopes start after the method name
   178  		scopePos := ftyp.Pos()
   179  		recv, rparams = check.collectRecv(recvPar.List[0], scopePos)
   180  	}
   181  
   182  	// collect and declare function type parameters
   183  	if ftyp.TypeParams != nil {
   184  		check.collectTypeParams(&sig.tparams, ftyp.TypeParams)
   185  	}
   186  
   187  	// collect ordinary and result parameters
   188  	pnames, params, variadic := check.collectParams(ParamVar, ftyp.Params)
   189  	rnames, results, _ := check.collectParams(ResultVar, ftyp.Results)
   190  
   191  	// declare named receiver, ordinary, and result parameters
   192  	scopePos := ftyp.End() // all parameter's scopes start after the signature
   193  	if recv != nil && recv.name != "" {
   194  		check.declare(check.scope, recvPar.List[0].Names[0], recv, scopePos)
   195  	}
   196  	check.declareParams(pnames, params, scopePos)
   197  	check.declareParams(rnames, results, scopePos)
   198  
   199  	sig.recv = recv
   200  	sig.rparams = rparams
   201  	sig.params = NewTuple(params...)
   202  	sig.results = NewTuple(results...)
   203  	sig.variadic = variadic
   204  }
   205  
   206  // collectRecv extracts the method receiver and its type parameters (if any) from rparam.
   207  // It declares the type parameters (but not the receiver) in the current scope, and
   208  // returns the receiver variable and its type parameter list (if any).
   209  func (check *Checker) collectRecv(rparam *ast.Field, scopePos token.Pos) (*Var, *TypeParamList) {
   210  	// Unpack the receiver parameter which is of the form
   211  	//
   212  	//	"(" [rfield] ["*"] rbase ["[" rtparams "]"] ")"
   213  	//
   214  	// The receiver name rname, the pointer indirection, and the
   215  	// receiver type parameters rtparams may not be present.
   216  	rptr, rbase, rtparams := check.unpackRecv(rparam.Type, true)
   217  
   218  	// Determine the receiver base type.
   219  	var recvType Type = Typ[Invalid]
   220  	var recvTParamsList *TypeParamList
   221  	if rtparams == nil {
   222  		// If there are no type parameters, we can simply typecheck rparam.Type.
   223  		// If that is a generic type, varType will complain.
   224  		// Further receiver constraints will be checked later, with validRecv.
   225  		// We use rparam.Type (rather than base) to correctly record pointer
   226  		// and parentheses in types.Info (was bug, see go.dev/issue/68639).
   227  		recvType = check.varType(rparam.Type)
   228  		// Defining new methods on instantiated (alias or defined) types is not permitted.
   229  		// Follow literal pointer/alias type chain and check.
   230  		// (Correct code permits at most one pointer indirection, but for this check it
   231  		// doesn't matter if we have multiple pointers.)
   232  		a, _ := unpointer(recvType).(*Alias) // recvType is not generic per above
   233  		for a != nil {
   234  			baseType := unpointer(a.fromRHS)
   235  			if g, _ := baseType.(genericType); g != nil && g.TypeParams() != nil {
   236  				check.errorf(rbase, InvalidRecv, "cannot define new methods on instantiated type %s", g)
   237  				recvType = Typ[Invalid] // avoid follow-on errors by Checker.validRecv
   238  				break
   239  			}
   240  			a, _ = baseType.(*Alias)
   241  		}
   242  	} else {
   243  		// If there are type parameters, rbase must denote a generic base type.
   244  		// Important: rbase must be resolved before declaring any receiver type
   245  		// parameters (which may have the same name, see below).
   246  		var baseType *Named // nil if not valid
   247  		var cause string
   248  		if t := check.genericType(rbase, &cause); isValid(t) {
   249  			switch t := t.(type) {
   250  			case *Named:
   251  				baseType = t
   252  			case *Alias:
   253  				// Methods on generic aliases are not permitted.
   254  				// Only report an error if the alias type is valid.
   255  				if isValid(t) {
   256  					check.errorf(rbase, InvalidRecv, "cannot define new methods on generic alias type %s", t)
   257  				}
   258  				// Ok to continue but do not set basetype in this case so that
   259  				// recvType remains invalid (was bug, see go.dev/issue/70417).
   260  			default:
   261  				panic("unreachable")
   262  			}
   263  		} else {
   264  			if cause != "" {
   265  				check.errorf(rbase, InvalidRecv, "%s", cause)
   266  			}
   267  			// Ok to continue but do not set baseType (see comment above).
   268  		}
   269  
   270  		// Collect the type parameters declared by the receiver (see also
   271  		// Checker.collectTypeParams). The scope of the type parameter T in
   272  		// "func (r T[T]) f() {}" starts after f, not at r, so we declare it
   273  		// after typechecking rbase (see go.dev/issue/52038).
   274  		recvTParams := make([]*TypeParam, len(rtparams))
   275  		for i, rparam := range rtparams {
   276  			tpar := check.declareTypeParam(rparam, scopePos)
   277  			recvTParams[i] = tpar
   278  			// For historic reasons, type parameters in receiver type expressions
   279  			// are considered both definitions and uses and thus must be recorded
   280  			// in the Info.Uses and Info.Types maps (see go.dev/issue/68670).
   281  			check.recordUse(rparam, tpar.obj)
   282  			check.recordTypeAndValue(rparam, typexpr, tpar, nil)
   283  		}
   284  		recvTParamsList = bindTParams(recvTParams)
   285  
   286  		// Get the type parameter bounds from the receiver base type
   287  		// and set them for the respective (local) receiver type parameters.
   288  		if baseType != nil {
   289  			baseTParams := baseType.TypeParams().list()
   290  			if len(recvTParams) == len(baseTParams) {
   291  				smap := makeRenameMap(baseTParams, recvTParams)
   292  				for i, recvTPar := range recvTParams {
   293  					baseTPar := baseTParams[i]
   294  					check.mono.recordCanon(recvTPar, baseTPar)
   295  					// baseTPar.bound is possibly parameterized by other type parameters
   296  					// defined by the generic base type. Substitute those parameters with
   297  					// the receiver type parameters declared by the current method.
   298  					recvTPar.bound = check.subst(recvTPar.obj.pos, baseTPar.bound, smap, nil, check.context())
   299  				}
   300  			} else {
   301  				got := measure(len(recvTParams), "type parameter")
   302  				check.errorf(rbase, BadRecv, "receiver declares %s, but receiver base type declares %d", got, len(baseTParams))
   303  			}
   304  
   305  			// The type parameters declared by the receiver also serve as
   306  			// type arguments for the receiver type. Instantiate the receiver.
   307  			check.verifyVersionf(rbase, go1_18, "type instantiation")
   308  			targs := make([]Type, len(recvTParams))
   309  			for i, targ := range recvTParams {
   310  				targs[i] = targ
   311  			}
   312  			recvType = check.instance(rparam.Type.Pos(), baseType, targs, nil, check.context())
   313  			check.recordInstance(rbase, targs, recvType)
   314  
   315  			// Reestablish pointerness if needed (but avoid a pointer to an invalid type).
   316  			if rptr && isValid(recvType) {
   317  				recvType = NewPointer(recvType)
   318  			}
   319  
   320  			check.recordParenthesizedRecvTypes(rparam.Type, recvType)
   321  		}
   322  	}
   323  
   324  	// Make sure we have no more than one receiver name.
   325  	var rname *ast.Ident
   326  	if n := len(rparam.Names); n >= 1 {
   327  		if n > 1 {
   328  			check.error(rparam.Names[n-1], InvalidRecv, "method has multiple receivers")
   329  		}
   330  		rname = rparam.Names[0]
   331  	}
   332  
   333  	// Create the receiver parameter.
   334  	// recvType is invalid if baseType was never set.
   335  	var recv *Var
   336  	if rname != nil && rname.Name != "" {
   337  		// named receiver
   338  		recv = newVar(RecvVar, rname.Pos(), check.pkg, rname.Name, recvType)
   339  		// In this case, the receiver is declared by the caller
   340  		// because it must be declared after any type parameters
   341  		// (otherwise it might shadow one of them).
   342  	} else {
   343  		// anonymous receiver
   344  		recv = newVar(RecvVar, rparam.Pos(), check.pkg, "", recvType)
   345  		check.recordImplicit(rparam, recv)
   346  	}
   347  
   348  	// Delay validation of receiver type as it may cause premature expansion of types
   349  	// the receiver type is dependent on (see go.dev/issue/51232, go.dev/issue/51233).
   350  	check.later(func() {
   351  		check.validRecv(rbase, recv)
   352  	}).describef(recv, "validRecv(%s)", recv)
   353  
   354  	return recv, recvTParamsList
   355  }
   356  
   357  func unpointer(t Type) Type {
   358  	for {
   359  		p, _ := t.(*Pointer)
   360  		if p == nil {
   361  			return t
   362  		}
   363  		t = p.base
   364  	}
   365  }
   366  
   367  // recordParenthesizedRecvTypes records parenthesized intermediate receiver type
   368  // expressions that all map to the same type, by recursively unpacking expr and
   369  // recording the corresponding type for it. Example:
   370  //
   371  //	expression  -->  type
   372  //	----------------------
   373  //	(*(T[P]))        *T[P]
   374  //	 *(T[P])         *T[P]
   375  //	  (T[P])          T[P]
   376  //	   T[P]           T[P]
   377  func (check *Checker) recordParenthesizedRecvTypes(expr ast.Expr, typ Type) {
   378  	for {
   379  		check.recordTypeAndValue(expr, typexpr, typ, nil)
   380  		switch e := expr.(type) {
   381  		case *ast.ParenExpr:
   382  			expr = e.X
   383  		case *ast.StarExpr:
   384  			expr = e.X
   385  			// In a correct program, typ must be an unnamed
   386  			// pointer type. But be careful and don't panic.
   387  			ptr, _ := typ.(*Pointer)
   388  			if ptr == nil {
   389  				return // something is wrong
   390  			}
   391  			typ = ptr.base
   392  		default:
   393  			return // cannot unpack any further
   394  		}
   395  	}
   396  }
   397  
   398  // collectParams collects (but does not declare) all parameter/result
   399  // variables of list and returns the list of names and corresponding
   400  // variables, and whether the (parameter) list is variadic.
   401  // Anonymous parameters are recorded with nil names.
   402  func (check *Checker) collectParams(kind VarKind, list *ast.FieldList) (names []*ast.Ident, params []*Var, variadic bool) {
   403  	if list == nil {
   404  		return
   405  	}
   406  
   407  	var named, anonymous bool
   408  	for i, field := range list.List {
   409  		ftype := field.Type
   410  		if t, _ := ftype.(*ast.Ellipsis); t != nil {
   411  			ftype = t.Elt
   412  			if kind == ParamVar && i == len(list.List)-1 && len(field.Names) <= 1 {
   413  				variadic = true
   414  			} else {
   415  				check.softErrorf(t, InvalidSyntaxTree, "invalid use of ...")
   416  				// ignore ... and continue
   417  			}
   418  		}
   419  		typ := check.varType(ftype)
   420  		// The parser ensures that f.Tag is nil and we don't
   421  		// care if a constructed AST contains a non-nil tag.
   422  		if len(field.Names) > 0 {
   423  			// named parameter
   424  			for _, name := range field.Names {
   425  				if name.Name == "" {
   426  					check.error(name, InvalidSyntaxTree, "anonymous parameter")
   427  					// ok to continue
   428  				}
   429  				par := newVar(kind, name.Pos(), check.pkg, name.Name, typ)
   430  				// named parameter is declared by caller
   431  				names = append(names, name)
   432  				params = append(params, par)
   433  			}
   434  			named = true
   435  		} else {
   436  			// anonymous parameter
   437  			par := newVar(kind, ftype.Pos(), check.pkg, "", typ)
   438  			check.recordImplicit(field, par)
   439  			names = append(names, nil)
   440  			params = append(params, par)
   441  			anonymous = true
   442  		}
   443  	}
   444  
   445  	if named && anonymous {
   446  		check.error(list, InvalidSyntaxTree, "list contains both named and anonymous parameters")
   447  		// ok to continue
   448  	}
   449  
   450  	// For a variadic function, change the last parameter's type from T to []T.
   451  	// Since we type-checked T rather than ...T, we also need to retro-actively
   452  	// record the type for ...T.
   453  	if variadic {
   454  		last := params[len(params)-1]
   455  		last.typ = &Slice{elem: last.typ}
   456  		check.recordTypeAndValue(list.List[len(list.List)-1].Type, typexpr, last.typ, nil)
   457  	}
   458  
   459  	return
   460  }
   461  
   462  // declareParams declares each named parameter in the current scope.
   463  func (check *Checker) declareParams(names []*ast.Ident, params []*Var, scopePos token.Pos) {
   464  	for i, name := range names {
   465  		if name != nil && name.Name != "" {
   466  			check.declare(check.scope, name, params[i], scopePos)
   467  		}
   468  	}
   469  }
   470  
   471  // validRecv verifies that the receiver satisfies its respective spec requirements
   472  // and reports an error otherwise.
   473  func (check *Checker) validRecv(pos positioner, recv *Var) {
   474  	// spec: "The receiver type must be of the form T or *T where T is a type name."
   475  	rtyp, _ := deref(recv.typ)
   476  	atyp := Unalias(rtyp)
   477  	if !isValid(atyp) {
   478  		return // error was reported before
   479  	}
   480  	// spec: "The type denoted by T is called the receiver base type; it must not
   481  	// be a pointer or interface type and it must be declared in the same package
   482  	// as the method."
   483  	switch T := atyp.(type) {
   484  	case *Named:
   485  		if T.obj.pkg != check.pkg || isCGoTypeObj(check.fset, T.obj) {
   486  			check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
   487  			break
   488  		}
   489  		var cause string
   490  		switch u := T.Underlying().(type) {
   491  		case *Basic:
   492  			// unsafe.Pointer is treated like a regular pointer
   493  			if u.kind == UnsafePointer {
   494  				cause = "unsafe.Pointer"
   495  			}
   496  		case *Pointer, *Interface:
   497  			cause = "pointer or interface type"
   498  		case *TypeParam:
   499  			// The underlying type of a receiver base type cannot be a
   500  			// type parameter: "type T[P any] P" is not a valid declaration.
   501  			panic("unreachable")
   502  		}
   503  		if cause != "" {
   504  			check.errorf(pos, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
   505  		}
   506  	case *Basic:
   507  		check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
   508  	default:
   509  		check.errorf(pos, InvalidRecv, "invalid receiver type %s", recv.typ)
   510  	}
   511  }
   512  
   513  // isCGoTypeObj reports whether the given type name was created by cgo.
   514  func isCGoTypeObj(fset *token.FileSet, obj *TypeName) bool {
   515  	return strings.HasPrefix(obj.name, "_Ctype_") ||
   516  		strings.HasPrefix(filepath.Base(fset.File(obj.pos).Name()), "_cgo_")
   517  }
   518  

View as plain text