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

View as plain text