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

View as plain text