Source file src/go/types/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 types
     6  
     7  import (
     8  	"go/ast"
     9  	"go/token"
    10  )
    11  
    12  // ----------------------------------------------------------------------------
    13  // API
    14  
    15  // A Signature represents a (non-builtin) function or method type.
    16  // The receiver is ignored when comparing signatures for identity.
    17  type Signature struct {
    18  	// We need to keep the scope in Signature (rather than passing it around
    19  	// and store it in the Func Object) because when type-checking a function
    20  	// literal we call the general type checker which returns a general Type.
    21  	// We then unpack the *Signature and use the scope for the literal body.
    22  	rparams  *TypeParamList // receiver type parameters from left to right, or nil
    23  	tparams  *TypeParamList // type parameters from left to right, or nil
    24  	scope    *Scope         // function scope for package-local and non-instantiated signatures; nil otherwise
    25  	recv     *Var           // nil if not a method
    26  	params   *Tuple         // (incoming) parameters from left to right; or nil
    27  	results  *Tuple         // (outgoing) results from left to right; or nil
    28  	variadic bool           // true if the last parameter's type is of the form ...T (or string, for append built-in only)
    29  }
    30  
    31  // NewSignature returns a new function type for the given receiver, parameters,
    32  // and results, either of which may be nil. If variadic is set, the function
    33  // is variadic, it must have at least one parameter, and the last parameter
    34  // must be of unnamed slice type.
    35  //
    36  // Deprecated: Use NewSignatureType instead which allows for type parameters.
    37  func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
    38  	return NewSignatureType(recv, nil, nil, params, results, variadic)
    39  }
    40  
    41  // NewSignatureType creates a new function type for the given receiver,
    42  // receiver type parameters, type parameters, parameters, and results. If
    43  // variadic is set, params must hold at least one parameter and the last
    44  // parameter must be of unnamed slice type. If recv is non-nil, typeParams must
    45  // be empty. If recvTypeParams is non-empty, recv must be non-nil.
    46  func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
    47  	if variadic {
    48  		n := params.Len()
    49  		if n == 0 {
    50  			panic("variadic function must have at least one parameter")
    51  		}
    52  		if _, ok := params.At(n - 1).typ.(*Slice); !ok {
    53  			panic("variadic parameter must be of unnamed slice type")
    54  		}
    55  	}
    56  	sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
    57  	if len(recvTypeParams) != 0 {
    58  		if recv == nil {
    59  			panic("function with receiver type parameters must have a receiver")
    60  		}
    61  		sig.rparams = bindTParams(recvTypeParams)
    62  	}
    63  	if len(typeParams) != 0 {
    64  		if recv != nil {
    65  			panic("function with type parameters cannot have a receiver")
    66  		}
    67  		sig.tparams = bindTParams(typeParams)
    68  	}
    69  	return sig
    70  }
    71  
    72  // Recv returns the receiver of signature s (if a method), or nil if a
    73  // function. It is ignored when comparing signatures for identity.
    74  //
    75  // For an abstract method, Recv returns the enclosing interface either
    76  // as a *Named or an *Interface. Due to embedding, an interface may
    77  // contain methods whose receiver type is a different interface.
    78  func (s *Signature) Recv() *Var { return s.recv }
    79  
    80  // TypeParams returns the type parameters of signature s, or nil.
    81  func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
    82  
    83  // RecvTypeParams returns the receiver type parameters of signature s, or nil.
    84  func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
    85  
    86  // Params returns the parameters of signature s, or nil.
    87  func (s *Signature) Params() *Tuple { return s.params }
    88  
    89  // Results returns the results of signature s, or nil.
    90  func (s *Signature) Results() *Tuple { return s.results }
    91  
    92  // Variadic reports whether the signature s is variadic.
    93  func (s *Signature) Variadic() bool { return s.variadic }
    94  
    95  func (t *Signature) Underlying() Type { return t }
    96  func (t *Signature) String() string   { return TypeString(t, nil) }
    97  
    98  // ----------------------------------------------------------------------------
    99  // Implementation
   100  
   101  // funcType type-checks a function or method type.
   102  func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) {
   103  	check.openScope(ftyp, "function")
   104  	check.scope.isFunc = true
   105  	check.recordScope(ftyp, check.scope)
   106  	sig.scope = check.scope
   107  	defer check.closeScope()
   108  
   109  	if recvPar != nil && len(recvPar.List) > 0 {
   110  		// collect generic receiver type parameters, if any
   111  		// - a receiver type parameter is like any other type parameter, except that it is declared implicitly
   112  		// - the receiver specification acts as local declaration for its type parameters, which may be blank
   113  		_, rname, rparams := check.unpackRecv(recvPar.List[0].Type, true)
   114  		if len(rparams) > 0 {
   115  			tparams := check.declareTypeParams(nil, rparams)
   116  			sig.rparams = bindTParams(tparams)
   117  			// Blank identifiers don't get declared, so naive type-checking of the
   118  			// receiver type expression would fail in Checker.collectParams below,
   119  			// when Checker.ident cannot resolve the _ to a type.
   120  			//
   121  			// Checker.recvTParamMap maps these blank identifiers to their type parameter
   122  			// types, so that they may be resolved in Checker.ident when they fail
   123  			// lookup in the scope.
   124  			for i, p := range rparams {
   125  				if p.Name == "_" {
   126  					if check.recvTParamMap == nil {
   127  						check.recvTParamMap = make(map[*ast.Ident]*TypeParam)
   128  					}
   129  					check.recvTParamMap[p] = tparams[i]
   130  				}
   131  			}
   132  			// determine receiver type to get its type parameters
   133  			// and the respective type parameter bounds
   134  			var recvTParams []*TypeParam
   135  			if rname != nil {
   136  				// recv should be a Named type (otherwise an error is reported elsewhere)
   137  				// Also: Don't report an error via genericType since it will be reported
   138  				//       again when we type-check the signature.
   139  				// TODO(gri) maybe the receiver should be marked as invalid instead?
   140  				if recv, _ := check.genericType(rname, nil).(*Named); recv != nil {
   141  					recvTParams = recv.TypeParams().list()
   142  				}
   143  			}
   144  			// provide type parameter bounds
   145  			if len(tparams) == len(recvTParams) {
   146  				smap := makeRenameMap(recvTParams, tparams)
   147  				for i, tpar := range tparams {
   148  					recvTPar := recvTParams[i]
   149  					check.mono.recordCanon(tpar, recvTPar)
   150  					// recvTPar.bound is (possibly) parameterized in the context of the
   151  					// receiver type declaration. Substitute parameters for the current
   152  					// context.
   153  					tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil)
   154  				}
   155  			} else if len(tparams) < len(recvTParams) {
   156  				// Reporting an error here is a stop-gap measure to avoid crashes in the
   157  				// compiler when a type parameter/argument cannot be inferred later. It
   158  				// may lead to follow-on errors (see issues #51339, #51343).
   159  				// TODO(gri) find a better solution
   160  				got := measure(len(tparams), "type parameter")
   161  				check.errorf(recvPar, _BadRecv, "got %s, but receiver base type declares %d", got, len(recvTParams))
   162  			}
   163  		}
   164  	}
   165  
   166  	if ftyp.TypeParams != nil {
   167  		check.collectTypeParams(&sig.tparams, ftyp.TypeParams)
   168  		// Always type-check method type parameters but complain that they are not allowed.
   169  		// (A separate check is needed when type-checking interface method signatures because
   170  		// they don't have a receiver specification.)
   171  		if recvPar != nil {
   172  			check.errorf(ftyp.TypeParams, _InvalidMethodTypeParams, "methods cannot have type parameters")
   173  		}
   174  	}
   175  
   176  	// Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
   177  	// declarations and then squash that scope into the parent scope (and report any redeclarations at
   178  	// that time).
   179  	scope := NewScope(check.scope, token.NoPos, token.NoPos, "function body (temp. scope)")
   180  	recvList, _ := check.collectParams(scope, recvPar, false)
   181  	params, variadic := check.collectParams(scope, ftyp.Params, true)
   182  	results, _ := check.collectParams(scope, ftyp.Results, false)
   183  	scope.squash(func(obj, alt Object) {
   184  		check.errorf(obj, _DuplicateDecl, "%s redeclared in this block", obj.Name())
   185  		check.reportAltDecl(alt)
   186  	})
   187  
   188  	if recvPar != nil {
   189  		// recv parameter list present (may be empty)
   190  		// spec: "The receiver is specified via an extra parameter section preceding the
   191  		// method name. That parameter section must declare a single parameter, the receiver."
   192  		var recv *Var
   193  		switch len(recvList) {
   194  		case 0:
   195  			// error reported by resolver
   196  			recv = NewParam(token.NoPos, nil, "", Typ[Invalid]) // ignore recv below
   197  		default:
   198  			// more than one receiver
   199  			check.error(recvList[len(recvList)-1], _InvalidRecv, "method must have exactly one receiver")
   200  			fallthrough // continue with first receiver
   201  		case 1:
   202  			recv = recvList[0]
   203  		}
   204  		sig.recv = recv
   205  
   206  		// Delay validation of receiver type as it may cause premature expansion
   207  		// of types the receiver type is dependent on (see issues #51232, #51233).
   208  		check.later(func() {
   209  			rtyp, _ := deref(recv.typ)
   210  
   211  			// spec: "The receiver type must be of the form T or *T where T is a type name."
   212  			// (ignore invalid types - error was reported before)
   213  			if rtyp != Typ[Invalid] {
   214  				var err string
   215  				switch T := rtyp.(type) {
   216  				case *Named:
   217  					T.resolve(check.bestContext(nil))
   218  					// The receiver type may be an instantiated type referred to
   219  					// by an alias (which cannot have receiver parameters for now).
   220  					if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
   221  						check.errorf(recv, _InvalidRecv, "cannot define methods on instantiated type %s", recv.typ)
   222  						break
   223  					}
   224  					// spec: "The type denoted by T is called the receiver base type; it must not
   225  					// be a pointer or interface type and it must be declared in the same package
   226  					// as the method."
   227  					if T.obj.pkg != check.pkg {
   228  						err = "type not defined in this package"
   229  						if compilerErrorMessages {
   230  							check.errorf(recv, _InvalidRecv, "cannot define new methods on non-local type %s", recv.typ)
   231  							err = ""
   232  						}
   233  					} else {
   234  						// The underlying type of a receiver base type can be a type parameter;
   235  						// e.g. for methods with a generic receiver T[P] with type T[P any] P.
   236  						// TODO(gri) Such declarations are currently disallowed.
   237  						//           Revisit the need for underIs.
   238  						underIs(T, func(u Type) bool {
   239  							switch u := u.(type) {
   240  							case *Basic:
   241  								// unsafe.Pointer is treated like a regular pointer
   242  								if u.kind == UnsafePointer {
   243  									err = "unsafe.Pointer"
   244  									return false
   245  								}
   246  							case *Pointer, *Interface:
   247  								err = "pointer or interface type"
   248  								return false
   249  							}
   250  							return true
   251  						})
   252  					}
   253  				case *Basic:
   254  					err = "basic or unnamed type"
   255  					if compilerErrorMessages {
   256  						check.errorf(recv, _InvalidRecv, "cannot define new methods on non-local type %s", recv.typ)
   257  						err = ""
   258  					}
   259  				default:
   260  					check.errorf(recv, _InvalidRecv, "invalid receiver type %s", recv.typ)
   261  				}
   262  				if err != "" {
   263  					check.errorf(recv, _InvalidRecv, "invalid receiver type %s (%s)", recv.typ, err)
   264  				}
   265  			}
   266  		}).describef(recv, "validate receiver %s", recv)
   267  	}
   268  
   269  	sig.params = NewTuple(params...)
   270  	sig.results = NewTuple(results...)
   271  	sig.variadic = variadic
   272  }
   273  
   274  // collectParams declares the parameters of list in scope and returns the corresponding
   275  // variable list.
   276  func (check *Checker) collectParams(scope *Scope, list *ast.FieldList, variadicOk bool) (params []*Var, variadic bool) {
   277  	if list == nil {
   278  		return
   279  	}
   280  
   281  	var named, anonymous bool
   282  	for i, field := range list.List {
   283  		ftype := field.Type
   284  		if t, _ := ftype.(*ast.Ellipsis); t != nil {
   285  			ftype = t.Elt
   286  			if variadicOk && i == len(list.List)-1 && len(field.Names) <= 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  		// The parser ensures that f.Tag is nil and we don't
   295  		// care if a constructed AST contains a non-nil tag.
   296  		if len(field.Names) > 0 {
   297  			// named parameter
   298  			for _, name := range field.Names {
   299  				if name.Name == "" {
   300  					check.invalidAST(name, "anonymous parameter")
   301  					// ok to continue
   302  				}
   303  				par := NewParam(name.Pos(), check.pkg, name.Name, typ)
   304  				check.declare(scope, name, par, scope.pos)
   305  				params = append(params, par)
   306  			}
   307  			named = true
   308  		} else {
   309  			// anonymous parameter
   310  			par := NewParam(ftype.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.invalidAST(list, "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.List[len(list.List)-1].Type, typexpr, last.typ, nil)
   329  	}
   330  
   331  	return
   332  }
   333  

View as plain text