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

View as plain text