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

View as plain text