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

View as plain text