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

View as plain text