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

View as plain text