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

View as plain text