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

View as plain text