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

View as plain text