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

View as plain text