github.com/bir3/gocompiler@v0.3.205/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  			tparams := check.declareTypeParams(nil, rparams)
   120  			sig.rparams = bindTParams(tparams)
   121  			// Blank identifiers don't get declared, so naive type-checking of the
   122  			// receiver type expression would fail in Checker.collectParams below,
   123  			// when Checker.ident cannot resolve the _ to a type.
   124  			//
   125  			// Checker.recvTParamMap maps these blank identifiers to their type parameter
   126  			// types, so that they may be resolved in Checker.ident when they fail
   127  			// lookup in the scope.
   128  			for i, p := range rparams {
   129  				if p.Name == "_" {
   130  					if check.recvTParamMap == nil {
   131  						check.recvTParamMap = make(map[*ast.Ident]*TypeParam)
   132  					}
   133  					check.recvTParamMap[p] = tparams[i]
   134  				}
   135  			}
   136  			// determine receiver type to get its type parameters
   137  			// and the respective type parameter bounds
   138  			var recvTParams []*TypeParam
   139  			if rname != nil {
   140  				// recv should be a Named type (otherwise an error is reported elsewhere)
   141  				// Also: Don't report an error via genericType since it will be reported
   142  				//       again when we type-check the signature.
   143  				// TODO(gri) maybe the receiver should be marked as invalid instead?
   144  				if recv, _ := check.genericType(rname, nil).(*Named); recv != nil {
   145  					recvTParams = recv.TypeParams().list()
   146  				}
   147  			}
   148  			// provide type parameter bounds
   149  			if len(tparams) == len(recvTParams) {
   150  				smap := makeRenameMap(recvTParams, tparams)
   151  				for i, tpar := range tparams {
   152  					recvTPar := recvTParams[i]
   153  					check.mono.recordCanon(tpar, recvTPar)
   154  					// recvTPar.bound is (possibly) parameterized in the context of the
   155  					// receiver type declaration. Substitute parameters for the current
   156  					// context.
   157  					tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil, check.context())
   158  				}
   159  			} else if len(tparams) < len(recvTParams) {
   160  				// Reporting an error here is a stop-gap measure to avoid crashes in the
   161  				// compiler when a type parameter/argument cannot be inferred later. It
   162  				// may lead to follow-on errors (see issues #51339, #51343).
   163  				// TODO(gri) find a better solution
   164  				got := measure(len(tparams), "type parameter")
   165  				check.errorf(recvPar, BadRecv, "got %s, but receiver base type declares %d", got, len(recvTParams))
   166  			}
   167  		}
   168  	}
   169  
   170  	if ftyp.TypeParams != nil {
   171  		check.collectTypeParams(&sig.tparams, ftyp.TypeParams)
   172  		// Always type-check method type parameters but complain that they are not allowed.
   173  		// (A separate check is needed when type-checking interface method signatures because
   174  		// they don't have a receiver specification.)
   175  		if recvPar != nil {
   176  			check.error(ftyp.TypeParams, InvalidMethodTypeParams, "methods cannot have type parameters")
   177  		}
   178  	}
   179  
   180  	// Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
   181  	// declarations and then squash that scope into the parent scope (and report any redeclarations at
   182  	// that time).
   183  	scope := NewScope(check.scope, token.NoPos, token.NoPos, "function body (temp. scope)")
   184  	recvList, _ := check.collectParams(scope, recvPar, false)
   185  	params, variadic := check.collectParams(scope, ftyp.Params, true)
   186  	results, _ := check.collectParams(scope, ftyp.Results, false)
   187  	scope.squash(func(obj, alt Object) {
   188  		check.errorf(obj, DuplicateDecl, "%s redeclared in this block", obj.Name())
   189  		check.reportAltDecl(alt)
   190  	})
   191  
   192  	if recvPar != nil {
   193  		// recv parameter list present (may be empty)
   194  		// spec: "The receiver is specified via an extra parameter section preceding the
   195  		// method name. That parameter section must declare a single parameter, the receiver."
   196  		var recv *Var
   197  		switch len(recvList) {
   198  		case 0:
   199  			// error reported by resolver
   200  			recv = NewParam(token.NoPos, nil, "", Typ[Invalid]) // ignore recv below
   201  		default:
   202  			// more than one receiver
   203  			check.error(recvList[len(recvList)-1], InvalidRecv, "method has multiple receivers")
   204  			fallthrough // continue with first receiver
   205  		case 1:
   206  			recv = recvList[0]
   207  		}
   208  		sig.recv = recv
   209  
   210  		// Delay validation of receiver type as it may cause premature expansion
   211  		// of types the receiver type is dependent on (see issues #51232, #51233).
   212  		check.later(func() {
   213  			// spec: "The receiver type must be of the form T or *T where T is a type name."
   214  			rtyp, _ := deref(recv.typ)
   215  			if rtyp == Typ[Invalid] {
   216  				return // error was reported before
   217  			}
   218  			// spec: "The type denoted by T is called the receiver base type; it must not
   219  			// be a pointer or interface type and it must be declared in the same package
   220  			// as the method."
   221  			switch T := rtyp.(type) {
   222  			case *Named:
   223  				// The receiver type may be an instantiated type referred to
   224  				// by an alias (which cannot have receiver parameters for now).
   225  				if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
   226  					check.errorf(recv, InvalidRecv, "cannot define new methods on instantiated type %s", rtyp)
   227  					break
   228  				}
   229  				if T.obj.pkg != check.pkg {
   230  					check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
   231  					break
   232  				}
   233  				var cause string
   234  				switch u := T.under().(type) {
   235  				case *Basic:
   236  					// unsafe.Pointer is treated like a regular pointer
   237  					if u.kind == UnsafePointer {
   238  						cause = "unsafe.Pointer"
   239  					}
   240  				case *Pointer, *Interface:
   241  					cause = "pointer or interface type"
   242  				case *TypeParam:
   243  					// The underlying type of a receiver base type cannot be a
   244  					// type parameter: "type T[P any] P" is not a valid declaration.
   245  					unreachable()
   246  				}
   247  				if cause != "" {
   248  					check.errorf(recv, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
   249  				}
   250  			case *Basic:
   251  				check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
   252  			default:
   253  				check.errorf(recv, InvalidRecv, "invalid receiver type %s", recv.typ)
   254  			}
   255  		}).describef(recv, "validate receiver %s", recv)
   256  	}
   257  
   258  	sig.params = NewTuple(params...)
   259  	sig.results = NewTuple(results...)
   260  	sig.variadic = variadic
   261  }
   262  
   263  // collectParams declares the parameters of list in scope and returns the corresponding
   264  // variable list.
   265  func (check *Checker) collectParams(scope *Scope, list *ast.FieldList, variadicOk bool) (params []*Var, variadic bool) {
   266  	if list == nil {
   267  		return
   268  	}
   269  
   270  	var named, anonymous bool
   271  	for i, field := range list.List {
   272  		ftype := field.Type
   273  		if t, _ := ftype.(*ast.Ellipsis); t != nil {
   274  			ftype = t.Elt
   275  			if variadicOk && i == len(list.List)-1 && len(field.Names) <= 1 {
   276  				variadic = true
   277  			} else {
   278  				check.softErrorf(t, MisplacedDotDotDot, "can only use ... with final parameter in list")
   279  				// ignore ... and continue
   280  			}
   281  		}
   282  		typ := check.varType(ftype)
   283  		// The parser ensures that f.Tag is nil and we don't
   284  		// care if a constructed AST contains a non-nil tag.
   285  		if len(field.Names) > 0 {
   286  			// named parameter
   287  			for _, name := range field.Names {
   288  				if name.Name == "" {
   289  					check.error(name, InvalidSyntaxTree, "anonymous parameter")
   290  					// ok to continue
   291  				}
   292  				par := NewParam(name.Pos(), check.pkg, name.Name, typ)
   293  				check.declare(scope, name, par, scope.pos)
   294  				params = append(params, par)
   295  			}
   296  			named = true
   297  		} else {
   298  			// anonymous parameter
   299  			par := NewParam(ftype.Pos(), check.pkg, "", typ)
   300  			check.recordImplicit(field, par)
   301  			params = append(params, par)
   302  			anonymous = true
   303  		}
   304  	}
   305  
   306  	if named && anonymous {
   307  		check.error(list, InvalidSyntaxTree, "list contains both named and anonymous parameters")
   308  		// ok to continue
   309  	}
   310  
   311  	// For a variadic function, change the last parameter's type from T to []T.
   312  	// Since we type-checked T rather than ...T, we also need to retro-actively
   313  	// record the type for ...T.
   314  	if variadic {
   315  		last := params[len(params)-1]
   316  		last.typ = &Slice{elem: last.typ}
   317  		check.recordTypeAndValue(list.List[len(list.List)-1].Type, typexpr, last.typ, nil)
   318  	}
   319  
   320  	return
   321  }