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

View as plain text