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

View as plain text