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

View as plain text