...

Source file src/go/types/signature.go

Documentation: go/types

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

View as plain text