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  // SetTypeParams sets the type parameters of signature s.
    77  func (s *Signature) SetTypeParams(tparams []*TypeParam) { s.tparams = bindTParams(tparams) }
    78  
    79  // RecvTypeParams returns the receiver type parameters of signature s, or nil.
    80  func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
    81  
    82  // Params returns the parameters of signature s, or nil.
    83  func (s *Signature) Params() *Tuple { return s.params }
    84  
    85  // Results returns the results of signature s, or nil.
    86  func (s *Signature) Results() *Tuple { return s.results }
    87  
    88  // Variadic reports whether the signature s is variadic.
    89  func (s *Signature) Variadic() bool { return s.variadic }
    90  
    91  func (s *Signature) Underlying() Type { return s }
    92  func (s *Signature) String() string   { return TypeString(s, nil) }
    93  
    94  // ----------------------------------------------------------------------------
    95  // Implementation
    96  
    97  // funcType type-checks a function or method type.
    98  func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
    99  	check.openScope(ftyp, "function")
   100  	check.scope.isFunc = true
   101  	check.recordScope(ftyp, check.scope)
   102  	sig.scope = check.scope
   103  	defer check.closeScope()
   104  
   105  	if recvPar != nil {
   106  		// collect generic receiver type parameters, if any
   107  		// - a receiver type parameter is like any other type parameter, except that it is declared implicitly
   108  		// - the receiver specification acts as local declaration for its type parameters, which may be blank
   109  		_, rname, rparams := check.unpackRecv(recvPar.Type, true)
   110  		if len(rparams) > 0 {
   111  			// The scope of the type parameter T in "func (r T[T]) f()"
   112  			// starts after f, not at "r"; see #52038.
   113  			scopePos := ftyp.Pos()
   114  			tparams := make([]*TypeParam, len(rparams))
   115  			for i, rparam := range rparams {
   116  				tparams[i] = check.declareTypeParam(rparam, scopePos)
   117  			}
   118  			sig.rparams = bindTParams(tparams)
   119  			// Blank identifiers don't get declared, so naive type-checking of the
   120  			// receiver type expression would fail in Checker.collectParams below,
   121  			// when Checker.ident cannot resolve the _ to a type.
   122  			//
   123  			// Checker.recvTParamMap maps these blank identifiers to their type parameter
   124  			// types, so that they may be resolved in Checker.ident when they fail
   125  			// lookup in the scope.
   126  			for i, p := range rparams {
   127  				if p.Value == "_" {
   128  					if check.recvTParamMap == nil {
   129  						check.recvTParamMap = make(map[*syntax.Name]*TypeParam)
   130  					}
   131  					check.recvTParamMap[p] = tparams[i]
   132  				}
   133  			}
   134  			// determine receiver type to get its type parameters
   135  			// and the respective type parameter bounds
   136  			var recvTParams []*TypeParam
   137  			if rname != nil {
   138  				// recv should be a Named type (otherwise an error is reported elsewhere)
   139  				// Also: Don't report an error via genericType since it will be reported
   140  				//       again when we type-check the signature.
   141  				// TODO(gri) maybe the receiver should be marked as invalid instead?
   142  				if recv := asNamed(check.genericType(rname, nil)); recv != nil {
   143  					recvTParams = recv.TypeParams().list()
   144  				}
   145  			}
   146  			// provide type parameter bounds
   147  			if len(tparams) == len(recvTParams) {
   148  				smap := makeRenameMap(recvTParams, tparams)
   149  				for i, tpar := range tparams {
   150  					recvTPar := recvTParams[i]
   151  					check.mono.recordCanon(tpar, recvTPar)
   152  					// recvTPar.bound is (possibly) parameterized in the context of the
   153  					// receiver type declaration. Substitute parameters for the current
   154  					// context.
   155  					tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil, check.context())
   156  				}
   157  			} else if len(tparams) < len(recvTParams) {
   158  				// Reporting an error here is a stop-gap measure to avoid crashes in the
   159  				// compiler when a type parameter/argument cannot be inferred later. It
   160  				// may lead to follow-on errors (see issues go.dev/issue/51339, go.dev/issue/51343).
   161  				// TODO(gri) find a better solution
   162  				got := measure(len(tparams), "type parameter")
   163  				check.errorf(recvPar, BadRecv, "got %s, but receiver base type declares %d", got, len(recvTParams))
   164  			}
   165  		}
   166  	}
   167  
   168  	if tparams != nil {
   169  		// The parser will complain about invalid type parameters for methods.
   170  		check.collectTypeParams(&sig.tparams, tparams)
   171  	}
   172  
   173  	// Use a temporary scope for all parameter declarations and then
   174  	// squash that scope into the parent scope (and report any
   175  	// redeclarations at that time).
   176  	//
   177  	// TODO(adonovan): now that each declaration has the correct
   178  	// scopePos, there should be no need for scope squashing.
   179  	// Audit to ensure all lookups honor scopePos and simplify.
   180  	scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
   181  	scopePos := syntax.EndPos(ftyp) // all parameters' scopes start after the signature
   182  	var recvList []*Var             // TODO(gri) remove the need for making a list here
   183  	if recvPar != nil {
   184  		recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, false, scopePos) // use rewritten receiver type, if any
   185  	}
   186  	params, variadic := check.collectParams(scope, ftyp.ParamList, true, scopePos)
   187  	results, _ := check.collectParams(scope, ftyp.ResultList, false, scopePos)
   188  	scope.Squash(func(obj, alt Object) {
   189  		var err error_
   190  		err.code = DuplicateDecl
   191  		err.errorf(obj, "%s redeclared in this block", obj.Name())
   192  		err.recordAltDecl(alt)
   193  		check.report(&err)
   194  	})
   195  
   196  	if recvPar != nil {
   197  		// recv parameter list present (may be empty)
   198  		// spec: "The receiver is specified via an extra parameter section preceding the
   199  		// method name. That parameter section must declare a single parameter, the receiver."
   200  		var recv *Var
   201  		switch len(recvList) {
   202  		case 0:
   203  			// error reported by resolver
   204  			recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
   205  		default:
   206  			// more than one receiver
   207  			check.error(recvList[len(recvList)-1].Pos(), InvalidRecv, "method must have exactly one receiver")
   208  			fallthrough // continue with first receiver
   209  		case 1:
   210  			recv = recvList[0]
   211  		}
   212  		sig.recv = recv
   213  
   214  		// Delay validation of receiver type as it may cause premature expansion
   215  		// of types the receiver type is dependent on (see issues go.dev/issue/51232, go.dev/issue/51233).
   216  		check.later(func() {
   217  			// spec: "The receiver type must be of the form T or *T where T is a type name."
   218  			rtyp, _ := deref(recv.typ)
   219  			atyp := Unalias(rtyp)
   220  			if !isValid(atyp) {
   221  				return // error was reported before
   222  			}
   223  			// spec: "The type denoted by T is called the receiver base type; it must not
   224  			// be a pointer or interface type and it must be declared in the same package
   225  			// as the method."
   226  			switch T := atyp.(type) {
   227  			case *Named:
   228  				// The receiver type may be an instantiated type referred to
   229  				// by an alias (which cannot have receiver parameters for now).
   230  				if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
   231  					check.errorf(recv, InvalidRecv, "cannot define new methods on instantiated type %s", rtyp)
   232  					break
   233  				}
   234  				if T.obj.pkg != check.pkg {
   235  					check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
   236  					break
   237  				}
   238  				var cause string
   239  				switch u := T.under().(type) {
   240  				case *Basic:
   241  					// unsafe.Pointer is treated like a regular pointer
   242  					if u.kind == UnsafePointer {
   243  						cause = "unsafe.Pointer"
   244  					}
   245  				case *Pointer, *Interface:
   246  					cause = "pointer or interface type"
   247  				case *TypeParam:
   248  					// The underlying type of a receiver base type cannot be a
   249  					// type parameter: "type T[P any] P" is not a valid declaration.
   250  					unreachable()
   251  				}
   252  				if cause != "" {
   253  					check.errorf(recv, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
   254  				}
   255  			case *Basic:
   256  				check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
   257  			default:
   258  				check.errorf(recv, InvalidRecv, "invalid receiver type %s", recv.typ)
   259  			}
   260  		}).describef(recv, "validate receiver %s", recv)
   261  	}
   262  
   263  	sig.params = NewTuple(params...)
   264  	sig.results = NewTuple(results...)
   265  	sig.variadic = variadic
   266  }
   267  
   268  // collectParams declares the parameters of list in scope and returns the corresponding
   269  // variable list.
   270  func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, variadicOk bool, scopePos syntax.Pos) (params []*Var, variadic bool) {
   271  	if list == nil {
   272  		return
   273  	}
   274  
   275  	var named, anonymous bool
   276  
   277  	var typ Type
   278  	var prev syntax.Expr
   279  	for i, field := range list {
   280  		ftype := field.Type
   281  		// type-check type of grouped fields only once
   282  		if ftype != prev {
   283  			prev = ftype
   284  			if t, _ := ftype.(*syntax.DotsType); t != nil {
   285  				ftype = t.Elem
   286  				if variadicOk && i == len(list)-1 {
   287  					variadic = true
   288  				} else {
   289  					check.softErrorf(t, MisplacedDotDotDot, "can only use ... with final parameter in list")
   290  					// ignore ... and continue
   291  				}
   292  			}
   293  			typ = check.varType(ftype)
   294  		}
   295  		// The parser ensures that f.Tag is nil and we don't
   296  		// care if a constructed AST contains a non-nil tag.
   297  		if field.Name != nil {
   298  			// named parameter
   299  			name := field.Name.Value
   300  			if name == "" {
   301  				check.error(field.Name, InvalidSyntaxTree, "anonymous parameter")
   302  				// ok to continue
   303  			}
   304  			par := NewParam(field.Name.Pos(), check.pkg, name, typ)
   305  			check.declare(scope, field.Name, par, scopePos)
   306  			params = append(params, par)
   307  			named = true
   308  		} else {
   309  			// anonymous parameter
   310  			par := NewParam(field.Pos(), check.pkg, "", typ)
   311  			check.recordImplicit(field, par)
   312  			params = append(params, par)
   313  			anonymous = true
   314  		}
   315  	}
   316  
   317  	if named && anonymous {
   318  		check.error(list[0], InvalidSyntaxTree, "list contains both named and anonymous parameters")
   319  		// ok to continue
   320  	}
   321  
   322  	// For a variadic function, change the last parameter's type from T to []T.
   323  	// Since we type-checked T rather than ...T, we also need to retro-actively
   324  	// record the type for ...T.
   325  	if variadic {
   326  		last := params[len(params)-1]
   327  		last.typ = &Slice{elem: last.typ}
   328  		check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
   329  	}
   330  
   331  	return
   332  }
   333  

View as plain text