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

View as plain text