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

View as plain text