github.com/bir3/gocompiler@v0.9.2202/src/go/types/signature.go (about)

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