Source file src/cmd/compile/internal/types2/call.go

     1  // Copyright 2013 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  // This file implements typechecking of call and selector expressions.
     6  
     7  package types2
     8  
     9  import (
    10  	"cmd/compile/internal/syntax"
    11  	. "internal/types/errors"
    12  	"strings"
    13  )
    14  
    15  // funcInst type-checks a function instantiation.
    16  // The incoming x must be a generic function.
    17  // If inst != nil, it provides some or all of the type arguments (inst.Index).
    18  // If target != nil, it may be used to infer missing type arguments of x, if any.
    19  // At least one of T or inst must be provided.
    20  //
    21  // There are two modes of operation:
    22  //
    23  //  1. If infer == true, funcInst infers missing type arguments as needed and
    24  //     instantiates the function x. The returned results are nil.
    25  //
    26  //  2. If infer == false and inst provides all type arguments, funcInst
    27  //     instantiates the function x. The returned results are nil.
    28  //     If inst doesn't provide enough type arguments, funcInst returns the
    29  //     available arguments; x remains unchanged.
    30  //
    31  // If an error (other than a version error) occurs in any case, it is reported
    32  // and x.mode is set to invalid.
    33  func (check *Checker) funcInst(T *target, pos syntax.Pos, x *operand, inst *syntax.IndexExpr, infer bool) []Type {
    34  	Tsig := T.sig()
    35  	assert(Tsig != nil || inst != nil)
    36  
    37  	var instErrPos poser
    38  	if inst != nil {
    39  		instErrPos = inst.Pos()
    40  		x.expr = inst // if we don't have an index expression, keep the existing expression of x
    41  	} else {
    42  		instErrPos = pos
    43  	}
    44  	versionErr := !check.verifyVersionf(instErrPos, go1_18, "function instantiation")
    45  
    46  	// targs and xlist are the type arguments and corresponding type expressions, or nil.
    47  	var targs []Type
    48  	var xlist []syntax.Expr
    49  	if inst != nil {
    50  		xlist = syntax.UnpackListExpr(inst.Index)
    51  		targs = check.typeList(xlist)
    52  		if targs == nil {
    53  			x.invalidate()
    54  			return nil
    55  		}
    56  		assert(len(targs) == len(xlist))
    57  	}
    58  
    59  	// Check the number of type arguments (got) vs number of type parameters (want).
    60  	// Note that x is a function value, not a type expression, so we don't need to
    61  	// call Underlying below.
    62  	sig := x.typ().(*Signature)
    63  	got, want := len(targs), sig.TypeParams().Len()
    64  	if got > want {
    65  		// Providing too many type arguments is always an error.
    66  		check.errorf(xlist[got-1], WrongTypeArgCount, "got %d type arguments but want %d", got, want)
    67  		x.invalidate()
    68  		return nil
    69  	}
    70  
    71  	if got < want {
    72  		if !infer {
    73  			return targs
    74  		}
    75  
    76  		// If the uninstantiated or partially instantiated function x is used in
    77  		// an assignment (tsig != nil), infer missing type arguments by treating
    78  		// the assignment
    79  		//
    80  		//    var tvar tsig = x
    81  		//
    82  		// like a call g(tvar) of the synthetic generic function g
    83  		//
    84  		//    func g[type_parameters_of_x](func_type_of_x)
    85  		//
    86  		var args []*operand
    87  		var params []*Var
    88  		var reverse bool
    89  		if Tsig != nil && sig.tparams != nil {
    90  			if !versionErr && !check.allowVersion(go1_21) {
    91  				if inst != nil {
    92  					check.versionErrorf(instErrPos, go1_21, "partially instantiated function in assignment")
    93  				} else {
    94  					check.versionErrorf(instErrPos, go1_21, "implicitly instantiated function in assignment")
    95  				}
    96  			}
    97  			gsig := NewSignatureType(nil, nil, nil, sig.params, sig.results, sig.variadic)
    98  			params = []*Var{NewParam(x.Pos(), check.pkg, "", gsig)}
    99  			// The type of the argument operand is tsig, which is the type of the LHS in an assignment
   100  			// or the result type in a return statement. Create a pseudo-expression for that operand
   101  			// that makes sense when reported in error messages from infer, below.
   102  			expr := newIdent(x.Pos(), T.desc)
   103  			args = []*operand{{mode_: value, expr: expr, typ_: Tsig}}
   104  			reverse = true
   105  		}
   106  
   107  		// Rename type parameters to avoid problems with recursive instantiations.
   108  		// Note that NewTuple(params...) below is (*Tuple)(nil) if len(params) == 0, as desired.
   109  		tparams, params2 := check.renameTParams(pos, sig.TypeParams().list(), NewTuple(params...))
   110  
   111  		err := check.newError(CannotInferTypeArgs)
   112  		targs = check.infer(pos, tparams, targs, params2.(*Tuple), args, reverse, err)
   113  		if targs == nil {
   114  			if !err.empty() {
   115  				err.report()
   116  			}
   117  			x.invalidate()
   118  			return nil
   119  		}
   120  		got = len(targs)
   121  	}
   122  	assert(got == want)
   123  
   124  	// instantiate function signature
   125  	sig = check.instantiateSignature(x.Pos(), x.expr, sig, targs, xlist)
   126  
   127  	x.typ_ = sig
   128  	x.mode_ = value
   129  	return nil
   130  }
   131  
   132  func (check *Checker) instantiateSignature(pos syntax.Pos, expr syntax.Expr, typ *Signature, targs []Type, xlist []syntax.Expr) (res *Signature) {
   133  	assert(check != nil)
   134  	assert(len(targs) == typ.TypeParams().Len())
   135  
   136  	if check.conf.Trace {
   137  		check.trace(pos, "-- instantiating signature %s with %s", typ, targs)
   138  		check.indent++
   139  		defer func() {
   140  			check.indent--
   141  			check.trace(pos, "=> %s (under = %s)", res, res.Underlying())
   142  		}()
   143  	}
   144  
   145  	// For signatures, Checker.instance will always succeed because the type argument
   146  	// count is correct at this point (see assertion above); hence the type assertion
   147  	// to *Signature will always succeed.
   148  	inst := check.instance(pos, typ, targs, nil, check.context()).(*Signature)
   149  	assert(inst.TypeParams().Len() == 0) // signature is not generic anymore
   150  	check.recordInstance(expr, targs, inst)
   151  	assert(len(xlist) <= len(targs))
   152  
   153  	// verify instantiation lazily (was go.dev/issue/50450)
   154  	check.later(func() {
   155  		tparams := typ.TypeParams().list()
   156  		// check type constraints
   157  		if i, err := check.verify(pos, tparams, targs, check.context()); err != nil {
   158  			// best position for error reporting
   159  			pos := pos
   160  			if i < len(xlist) {
   161  				pos = syntax.StartPos(xlist[i])
   162  			}
   163  			check.softErrorf(pos, InvalidTypeArg, "%s", err)
   164  		} else {
   165  			check.mono.recordInstance(check.pkg, pos, tparams, targs, xlist)
   166  		}
   167  	}).describef(pos, "verify instantiation")
   168  
   169  	return inst
   170  }
   171  
   172  func (check *Checker) callExpr(x *operand, call *syntax.CallExpr) exprKind {
   173  	var inst *syntax.IndexExpr // function instantiation, if any
   174  	if iexpr, _ := call.Fun.(*syntax.IndexExpr); iexpr != nil {
   175  		if check.indexExpr(x, iexpr) {
   176  			// Delay function instantiation to argument checking,
   177  			// where we combine type and value arguments for type
   178  			// inference.
   179  			assert(x.mode() == value)
   180  			inst = iexpr
   181  		}
   182  		x.expr = iexpr
   183  		check.record(x)
   184  	} else {
   185  		check.exprOrType(x, call.Fun, true)
   186  	}
   187  	// x.typ may be generic
   188  
   189  	switch x.mode() {
   190  	case invalid:
   191  		check.use(call.ArgList...)
   192  		x.expr = call
   193  		return statement
   194  
   195  	case typexpr:
   196  		// conversion
   197  		check.nonGeneric(nil, x)
   198  		if !x.isValid() {
   199  			return conversion
   200  		}
   201  		T := x.typ()
   202  		x.invalidate()
   203  		// We cannot convert a value to an incomplete type; make sure it's complete.
   204  		if !check.isComplete(T) {
   205  			x.expr = call
   206  			return conversion
   207  		}
   208  		switch n := len(call.ArgList); n {
   209  		case 0:
   210  			check.errorf(call, WrongArgCount, "missing argument in conversion to %s", T)
   211  		case 1:
   212  			check.expr(newTarget(T, "conversion"), x, call.ArgList[0])
   213  			if x.isValid() {
   214  				if t, _ := T.Underlying().(*Interface); t != nil && !isTypeParam(T) {
   215  					if !t.IsMethodSet() {
   216  						check.errorf(call, MisplacedConstraintIface, "cannot use interface %s in conversion (contains specific type constraints or is comparable)", T)
   217  						break
   218  					}
   219  				}
   220  				if hasDots(call) {
   221  					check.errorf(call.ArgList[0], BadDotDotDotSyntax, "invalid use of ... in conversion to %s", T)
   222  					break
   223  				}
   224  				check.conversion(x, T)
   225  			}
   226  		default:
   227  			check.use(call.ArgList...)
   228  			check.errorf(call.ArgList[n-1], WrongArgCount, "too many arguments in conversion to %s", T)
   229  		}
   230  		x.expr = call
   231  		return conversion
   232  
   233  	case builtin:
   234  		// no need to check for non-genericity here
   235  		fdesc := &predeclaredFuncs[x.id]
   236  		x.invalidate()
   237  		// append is the only built-in that permits the use of ... for the last argument.
   238  		// Check it here for all built-ins except append.
   239  		if hasDots(call) && x.id != _Append {
   240  			check.errorf(dddErrPos(call),
   241  				InvalidDotDotDot,
   242  				invalidOp+"invalid use of ... with built-in %s", fdesc.name)
   243  			check.use(call.ArgList...)
   244  		} else {
   245  			fdesc.builtin(check, x, call)
   246  		}
   247  		x.expr = call
   248  		// a non-constant result implies a function call or receive
   249  		if x.isValid() && x.mode() != constant_ {
   250  			check.hasCallOrRecv = true
   251  		}
   252  		return fdesc.kind
   253  	}
   254  
   255  	// ordinary function/method call
   256  	// signature may be generic
   257  	cgocall := x.mode() == cgofunc
   258  
   259  	// If the operand type is a type parameter, all types in its type set
   260  	// must have a common underlying type, which must be a signature.
   261  	u, err := commonUnder(x.typ(), func(t, u Type) *typeError {
   262  		if _, ok := u.(*Signature); u != nil && !ok {
   263  			return typeErrorf("%s is not a function", t)
   264  		}
   265  		return nil
   266  	})
   267  	if err != nil {
   268  		check.errorf(x, InvalidCall, invalidOp+"cannot call %s: %s", x, err.format(check))
   269  		x.invalidate()
   270  		x.expr = call
   271  		return statement
   272  	}
   273  	sig := u.(*Signature) // u must be a signature per the commonUnder condition
   274  
   275  	// Capture wasGeneric before sig is potentially instantiated below.
   276  	wasGeneric := sig.TypeParams().Len() > 0
   277  
   278  	// evaluate type arguments, if any
   279  	var xlist []syntax.Expr
   280  	var targs []Type
   281  	if inst != nil {
   282  		xlist = syntax.UnpackListExpr(inst.Index)
   283  		targs = check.typeList(xlist)
   284  		if targs == nil {
   285  			check.use(call.ArgList...)
   286  			x.invalidate()
   287  			x.expr = call
   288  			return statement
   289  		}
   290  		assert(len(targs) == len(xlist))
   291  
   292  		// check number of type arguments (got) vs number of type parameters (want)
   293  		got, want := len(targs), sig.TypeParams().Len()
   294  		if got > want {
   295  			check.errorf(xlist[want], WrongTypeArgCount, "got %d type arguments but want %d", got, want)
   296  			check.use(call.ArgList...)
   297  			x.invalidate()
   298  			x.expr = call
   299  			return statement
   300  		}
   301  
   302  		// If sig is generic and all type arguments are provided, preempt function
   303  		// argument type inference by explicitly instantiating the signature. This
   304  		// ensures that we record accurate type information for sig, even if there
   305  		// is an error checking its arguments (for example, if an incorrect number
   306  		// of arguments is supplied).
   307  		if got == want && want > 0 {
   308  			check.verifyVersionf(inst, go1_18, "function instantiation")
   309  			sig = check.instantiateSignature(inst.Pos(), inst, sig, targs, xlist)
   310  			// targs have been consumed; proceed with checking arguments of the
   311  			// non-generic signature.
   312  			targs = nil
   313  			xlist = nil
   314  		}
   315  	}
   316  
   317  	// evaluate arguments
   318  	targetAt := func(i int) *target { return newTarget(sig.argType(i), "function parameter") }
   319  	args, atargs := check.genericExprList(targetAt, call.ArgList)
   320  	sig = check.arguments(call, sig, targs, xlist, args, atargs)
   321  
   322  	if wasGeneric && sig.TypeParams().Len() == 0 {
   323  		// update the recorded type of call.Fun to its instantiated type
   324  		check.recordTypeAndValue(call.Fun, value, sig, nil)
   325  	}
   326  
   327  	// determine result
   328  	switch sig.results.Len() {
   329  	case 0:
   330  		x.mode_ = novalue
   331  	case 1:
   332  		if cgocall {
   333  			x.mode_ = commaerr
   334  		} else {
   335  			x.mode_ = value
   336  		}
   337  		typ := sig.results.vars[0].typ // unpack tuple
   338  		// We cannot return a value of an incomplete type; make sure it's complete.
   339  		if !check.isComplete(typ) {
   340  			x.invalidate()
   341  			x.expr = call
   342  			return statement
   343  		}
   344  		x.typ_ = typ
   345  	default:
   346  		x.mode_ = value
   347  		x.typ_ = sig.results
   348  	}
   349  	x.expr = call
   350  	check.hasCallOrRecv = true
   351  
   352  	// if type inference failed, a parameterized result must be invalidated
   353  	// (operands cannot have a parameterized type)
   354  	if x.mode() == value && sig.TypeParams().Len() > 0 && isParameterized(sig.TypeParams().list(), x.typ()) {
   355  		x.invalidate()
   356  	}
   357  
   358  	return statement
   359  }
   360  
   361  // exprList evaluates a list of expressions and returns the corresponding operands.
   362  // A single-element expression list may evaluate to multiple operands.
   363  func (check *Checker) exprList(elist []syntax.Expr) (xlist []*operand) {
   364  	if n := len(elist); n == 1 {
   365  		xlist, _ = check.multiExpr(elist[0], false)
   366  	} else if n > 1 {
   367  		// multiple (possibly invalid) values
   368  		xlist = make([]*operand, n)
   369  		for i, e := range elist {
   370  			var x operand
   371  			check.expr(nil, &x, e)
   372  			xlist[i] = &x
   373  		}
   374  	}
   375  	return
   376  }
   377  
   378  // genericExprList is like exprList but result operands may be uninstantiated or partially
   379  // instantiated generic functions (where constraint information is insufficient to infer
   380  // the missing type arguments) for Go 1.21 and later. Additionally, typeAt must return the
   381  // corresponding target type for each operand, or nil if none exists.
   382  // For each non-generic or uninstantiated generic operand, the corresponding targsList and
   383  // elements do not exist (targsList is nil) or the elements are nil.
   384  // For each partially instantiated generic function operand, the corresponding
   385  // targsList elements are the operand's partial type arguments.
   386  func (check *Checker) genericExprList(targetAt func(int) *target, elist []syntax.Expr) (resList []*operand, targsList [][]Type) {
   387  	if debug {
   388  		defer func() {
   389  			// type arguments must only exist for partially instantiated functions
   390  			for i, x := range resList {
   391  				if i < len(targsList) {
   392  					if n := len(targsList[i]); n > 0 {
   393  						// x must be a partially instantiated function
   394  						assert(n < x.typ().(*Signature).TypeParams().Len())
   395  					}
   396  				}
   397  			}
   398  		}()
   399  	}
   400  
   401  	// Before Go 1.21, uninstantiated or partially instantiated argument functions are
   402  	// not permitted. Checker.funcInst must infer missing type arguments in that case.
   403  	infer := true // for -lang < go1.21
   404  	n := len(elist)
   405  	if n > 0 && check.allowVersion(go1_21) {
   406  		infer = false
   407  	}
   408  
   409  	if n == 1 {
   410  		// single value (possibly a partially instantiated function), or a multi-valued expression
   411  		e := elist[0]
   412  		var x operand
   413  		if inst, _ := e.(*syntax.IndexExpr); inst != nil && check.indexExpr(&x, inst) {
   414  			// x is a generic function.
   415  			targs := check.funcInst(nil, x.Pos(), &x, inst, infer)
   416  			if targs != nil {
   417  				// x was not instantiated: collect the (partial) type arguments.
   418  				targsList = [][]Type{targs}
   419  				// Update x.expr so that we can record the partially instantiated function.
   420  				x.expr = inst
   421  			} else {
   422  				// x was instantiated: we must record it here because we didn't
   423  				// use the usual expression evaluators.
   424  				check.record(&x)
   425  			}
   426  			resList = []*operand{&x}
   427  		} else {
   428  			// x is not a function instantiation (it may still be a generic function).
   429  			check.rawExpr(targetAt(0), &x, e, true)
   430  			check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
   431  			if t, ok := x.typ().(*Tuple); ok && x.isValid() {
   432  				// x is a function call returning multiple values; it cannot be generic.
   433  				resList = make([]*operand, t.Len())
   434  				for i, v := range t.vars {
   435  					resList[i] = &operand{mode_: value, expr: e, typ_: v.typ}
   436  				}
   437  			} else {
   438  				// x is exactly one value (possibly invalid or uninstantiated generic function).
   439  				resList = []*operand{&x}
   440  			}
   441  		}
   442  	} else if n > 1 {
   443  		// multiple values
   444  		resList = make([]*operand, n)
   445  		targsList = make([][]Type, n)
   446  		for i, e := range elist {
   447  			var x operand
   448  			if inst, _ := e.(*syntax.IndexExpr); inst != nil && check.indexExpr(&x, inst) {
   449  				// x is a generic function.
   450  				targs := check.funcInst(nil, x.Pos(), &x, inst, infer)
   451  				if targs != nil {
   452  					// x was not instantiated: collect the (partial) type arguments.
   453  					targsList[i] = targs
   454  					// Update x.expr so that we can record the partially instantiated function.
   455  					x.expr = inst
   456  				} else {
   457  					// x was instantiated: we must record it here because we didn't
   458  					// use the usual expression evaluators.
   459  					check.record(&x)
   460  				}
   461  			} else {
   462  				// x is exactly one value (possibly invalid or uninstantiated generic function).
   463  				check.genericExpr(targetAt(i), &x, e)
   464  			}
   465  			resList[i] = &x
   466  		}
   467  	}
   468  
   469  	return
   470  }
   471  
   472  // arguments type-checks arguments passed to a function call with the given signature.
   473  // The function and its arguments may be generic, and possibly partially instantiated.
   474  // targs and xlist are the function's type arguments (and corresponding expressions).
   475  // args are the function arguments. If an argument args[i] is a partially instantiated
   476  // generic function, atargs[i] are the corresponding type arguments.
   477  // If the callee is variadic, arguments adjusts its signature to match the provided
   478  // arguments. The type parameters and arguments of the callee and all its arguments
   479  // are used together to infer any missing type arguments, and the callee and argument
   480  // functions are instantiated as necessary.
   481  // The result signature is the (possibly adjusted and instantiated) function signature.
   482  // If an error occurred, the result signature is the incoming sig.
   483  func (check *Checker) arguments(call *syntax.CallExpr, sig *Signature, targs []Type, xlist []syntax.Expr, args []*operand, atargs [][]Type) (rsig *Signature) {
   484  	rsig = sig
   485  
   486  	// Function call argument/parameter count requirements
   487  	//
   488  	//               | standard call    | dotdotdot call |
   489  	// --------------+------------------+----------------+
   490  	// standard func | nargs == npars   | invalid        |
   491  	// --------------+------------------+----------------+
   492  	// variadic func | nargs >= npars-1 | nargs == npars |
   493  	// --------------+------------------+----------------+
   494  
   495  	nargs := len(args)
   496  	npars := sig.params.Len()
   497  	ddd := hasDots(call)
   498  
   499  	// set up parameters
   500  	sigParams := sig.params // adjusted for variadic functions (may be nil for empty parameter lists!)
   501  	adjusted := false       // indicates if sigParams is different from sig.params
   502  	if sig.variadic {
   503  		if ddd {
   504  			// variadic_func(a, b, c...)
   505  			if len(call.ArgList) == 1 && nargs > 1 {
   506  				// f()... is not permitted if f() is multi-valued
   507  				//check.errorf(call.Ellipsis, "cannot use ... with %d-valued %s", nargs, call.ArgList[0])
   508  				check.errorf(call, InvalidDotDotDot, "cannot use ... with %d-valued %s", nargs, call.ArgList[0])
   509  				return
   510  			}
   511  		} else {
   512  			// variadic_func(a, b, c)
   513  			if nargs >= npars-1 {
   514  				// Create custom parameters for arguments: keep
   515  				// the first npars-1 parameters and add one for
   516  				// each argument mapping to the ... parameter.
   517  				vars := make([]*Var, npars-1) // npars > 0 for variadic functions
   518  				copy(vars, sig.params.vars)
   519  				last := sig.params.vars[npars-1]
   520  				typ := last.typ.(*Slice).elem
   521  				for len(vars) < nargs {
   522  					vars = append(vars, NewParam(last.pos, last.pkg, last.name, typ))
   523  				}
   524  				sigParams = NewTuple(vars...) // possibly nil!
   525  				adjusted = true
   526  				npars = nargs
   527  			} else {
   528  				// nargs < npars-1
   529  				npars-- // for correct error message below
   530  			}
   531  		}
   532  	} else {
   533  		if ddd {
   534  			// standard_func(a, b, c...)
   535  			//check.errorf(call.Ellipsis, "cannot use ... in call to non-variadic %s", call.Fun)
   536  			check.errorf(call, NonVariadicDotDotDot, "cannot use ... in call to non-variadic %s", call.Fun)
   537  			return
   538  		}
   539  		// standard_func(a, b, c)
   540  	}
   541  
   542  	// check argument count
   543  	if nargs != npars {
   544  		var at poser = call
   545  		qualifier := "not enough"
   546  		if nargs > npars {
   547  			at = args[npars].expr // report at first extra argument
   548  			qualifier = "too many"
   549  		} else if nargs > 0 {
   550  			at = args[nargs-1].expr // report at last argument
   551  		}
   552  		// take care of empty parameter lists represented by nil tuples
   553  		var params []*Var
   554  		if sig.params != nil {
   555  			params = sig.params.vars
   556  		}
   557  		err := check.newError(WrongArgCount)
   558  		err.addf(at, "%s arguments in call to %s", qualifier, call.Fun)
   559  		err.addf(nopos, "have %s", check.typesSummary(operandTypes(args), false, ddd))
   560  		err.addf(nopos, "want %s", check.typesSummary(varTypes(params), sig.variadic, false))
   561  		err.report()
   562  		return
   563  	}
   564  
   565  	// collect type parameters of callee and generic function arguments
   566  	var tparams []*TypeParam
   567  
   568  	// collect type parameters of callee
   569  	n := sig.TypeParams().Len()
   570  	if n > 0 {
   571  		if !check.allowVersion(go1_18) {
   572  			if iexpr, _ := call.Fun.(*syntax.IndexExpr); iexpr != nil {
   573  				check.versionErrorf(iexpr, go1_18, "function instantiation")
   574  			} else {
   575  				check.versionErrorf(call, go1_18, "implicit function instantiation")
   576  			}
   577  		}
   578  		// rename type parameters to avoid problems with recursive calls
   579  		var tmp Type
   580  		tparams, tmp = check.renameTParams(call.Pos(), sig.TypeParams().list(), sigParams)
   581  		sigParams = tmp.(*Tuple)
   582  		// make sure targs and tparams have the same length
   583  		for len(targs) < len(tparams) {
   584  			targs = append(targs, nil)
   585  		}
   586  	}
   587  	assert(len(tparams) == len(targs))
   588  
   589  	// collect type parameters from generic function arguments
   590  	var genericArgs []int // indices of generic function arguments
   591  	if enableReverseTypeInference {
   592  		for i, arg := range args {
   593  			// generic arguments cannot have a defined (*Named) type - no need for underlying type below
   594  			if asig, _ := arg.typ().(*Signature); asig != nil && asig.TypeParams().Len() > 0 {
   595  				// The argument type is a generic function signature. This type is
   596  				// pointer-identical with (it's copied from) the type of the generic
   597  				// function argument and thus the function object.
   598  				// Before we change the type (type parameter renaming, below), make
   599  				// a clone of it as otherwise we implicitly modify the object's type
   600  				// (go.dev/issues/63260).
   601  				asig = clone(asig)
   602  				// Rename type parameters for cases like f(g, g); this gives each
   603  				// generic function argument a unique type identity (go.dev/issues/59956).
   604  				// TODO(gri) Consider only doing this if a function argument appears
   605  				//           multiple times, which is rare (possible optimization).
   606  				atparams, tmp := check.renameTParams(call.Pos(), asig.TypeParams().list(), asig)
   607  				asig = tmp.(*Signature)
   608  				asig.tparams = &TypeParamList{atparams} // renameTParams doesn't touch associated type parameters
   609  				arg.typ_ = asig                         // new type identity for the function argument
   610  				tparams = append(tparams, atparams...)
   611  				// add partial list of type arguments, if any
   612  				if i < len(atargs) {
   613  					targs = append(targs, atargs[i]...)
   614  				}
   615  				// make sure targs and tparams have the same length
   616  				for len(targs) < len(tparams) {
   617  					targs = append(targs, nil)
   618  				}
   619  				genericArgs = append(genericArgs, i)
   620  			}
   621  		}
   622  	}
   623  	assert(len(tparams) == len(targs))
   624  
   625  	// at the moment we only support implicit instantiations of argument functions
   626  	_ = len(genericArgs) > 0 && check.verifyVersionf(args[genericArgs[0]], go1_21, "implicitly instantiated function as argument")
   627  
   628  	// tparams holds the type parameters of the callee and generic function arguments, if any:
   629  	// the first n type parameters belong to the callee, followed by mi type parameters for each
   630  	// of the generic function arguments, where mi = args[i].typ.(*Signature).TypeParams().Len().
   631  
   632  	// infer missing type arguments of callee and function arguments
   633  	if len(tparams) > 0 {
   634  		err := check.newError(CannotInferTypeArgs)
   635  		targs = check.infer(call.Pos(), tparams, targs, sigParams, args, false, err)
   636  		if targs == nil {
   637  			// TODO(gri) If infer inferred the first targs[:n], consider instantiating
   638  			//           the call signature for better error messages/gopls behavior.
   639  			//           Perhaps instantiate as much as we can, also for arguments.
   640  			//           This will require changes to how infer returns its results.
   641  			if !err.empty() {
   642  				check.errorf(err.pos(), CannotInferTypeArgs, "in call to %s, %s", call.Fun, err.msg())
   643  			}
   644  			return
   645  		}
   646  
   647  		// update result signature: instantiate if needed
   648  		if n > 0 {
   649  			rsig = check.instantiateSignature(call.Pos(), call.Fun, sig, targs[:n], xlist)
   650  			// If the callee's parameter list was adjusted we need to update (instantiate)
   651  			// it separately. Otherwise we can simply use the result signature's parameter
   652  			// list.
   653  			if adjusted {
   654  				sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(tparams[:n], targs[:n]), nil, check.context()).(*Tuple)
   655  			} else {
   656  				sigParams = rsig.params
   657  			}
   658  		}
   659  
   660  		// compute argument signatures: instantiate if needed
   661  		j := n
   662  		for _, i := range genericArgs {
   663  			arg := args[i]
   664  			asig := arg.typ().(*Signature)
   665  			k := j + asig.TypeParams().Len()
   666  			// targs[j:k] are the inferred type arguments for asig
   667  			arg.typ_ = check.instantiateSignature(call.Pos(), arg.expr, asig, targs[j:k], nil) // TODO(gri) provide xlist if possible (partial instantiations)
   668  			check.record(arg)                                                                  // record here because we didn't use the usual expr evaluators
   669  			j = k
   670  		}
   671  	}
   672  
   673  	// check arguments
   674  	if len(args) > 0 {
   675  		context := check.sprintf("argument to %s", call.Fun)
   676  		for i, a := range args {
   677  			check.assignment(a, sigParams.vars[i].typ, context)
   678  		}
   679  	}
   680  
   681  	return
   682  }
   683  
   684  var cgoPrefixes = [...]string{
   685  	"_Ciconst_",
   686  	"_Cfconst_",
   687  	"_Csconst_",
   688  	"_Ctype_",
   689  	"_Cvar_", // actually a pointer to the var
   690  	"_Cfpvar_fp_",
   691  	"_Cfunc_",
   692  	"_Cmacro_", // function to evaluate the expanded expression
   693  }
   694  
   695  func (check *Checker) selector(x *operand, e *syntax.SelectorExpr, wantType bool) {
   696  	// these must be declared before the "goto Error" statements
   697  	var (
   698  		obj      Object
   699  		index    []int
   700  		indirect bool
   701  	)
   702  
   703  	sel := e.Sel.Value
   704  	// If the identifier refers to a package, handle everything here
   705  	// so we don't need a "package" mode for operands: package names
   706  	// can only appear in qualified identifiers which are mapped to
   707  	// selector expressions.
   708  	if ident, ok := e.X.(*syntax.Name); ok {
   709  		obj := check.lookup(ident.Value)
   710  		if pname, _ := obj.(*PkgName); pname != nil {
   711  			assert(pname.pkg == check.pkg)
   712  			check.recordUse(ident, pname)
   713  			check.usedPkgNames[pname] = true
   714  			pkg := pname.imported
   715  
   716  			var exp Object
   717  			funcMode := value
   718  			if pkg.cgo {
   719  				// cgo special cases C.malloc: it's
   720  				// rewritten to _CMalloc and does not
   721  				// support two-result calls.
   722  				if sel == "malloc" {
   723  					sel = "_CMalloc"
   724  				} else {
   725  					funcMode = cgofunc
   726  				}
   727  				for _, prefix := range cgoPrefixes {
   728  					// cgo objects are part of the current package (in file
   729  					// _cgo_gotypes.go). Use regular lookup.
   730  					exp = check.lookup(prefix + sel)
   731  					if exp != nil {
   732  						break
   733  					}
   734  				}
   735  				if exp == nil {
   736  					if isValidName(sel) {
   737  						check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s", syntax.Expr(e)) // cast to syntax.Expr to silence vet
   738  					}
   739  					goto Error
   740  				}
   741  				check.objDecl(exp)
   742  			} else {
   743  				exp = pkg.scope.Lookup(sel)
   744  				if exp == nil {
   745  					if !pkg.fake && isValidName(sel) {
   746  						// Try to give a better error message when selector matches an object name ignoring case.
   747  						exps := pkg.scope.lookupIgnoringCase(sel, true)
   748  						if len(exps) >= 1 {
   749  							// report just the first one
   750  							check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s (but have %s)", syntax.Expr(e), exps[0].Name())
   751  						} else {
   752  							check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s", syntax.Expr(e))
   753  						}
   754  					}
   755  					goto Error
   756  				}
   757  				if !exp.Exported() {
   758  					check.errorf(e.Sel, UnexportedName, "name %s not exported by package %s", sel, pkg.name)
   759  					// ok to continue
   760  				}
   761  			}
   762  			check.recordUse(e.Sel, exp)
   763  
   764  			// Simplified version of the code for *syntax.Names:
   765  			// - imported objects are always fully initialized
   766  			switch exp := exp.(type) {
   767  			case *Const:
   768  				assert(exp.Val() != nil)
   769  				x.mode_ = constant_
   770  				x.typ_ = exp.typ
   771  				x.val = exp.val
   772  			case *TypeName:
   773  				x.mode_ = typexpr
   774  				x.typ_ = exp.typ
   775  			case *Var:
   776  				x.mode_ = variable
   777  				x.typ_ = exp.typ
   778  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
   779  					x.typ_ = x.typ().(*Pointer).base
   780  				}
   781  			case *Func:
   782  				x.mode_ = funcMode
   783  				x.typ_ = exp.typ
   784  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
   785  					x.mode_ = value
   786  					x.typ_ = x.typ().(*Signature).results.vars[0].typ
   787  				}
   788  			case *Builtin:
   789  				x.mode_ = builtin
   790  				x.typ_ = exp.typ
   791  				x.id = exp.id
   792  			default:
   793  				check.dump("%v: unexpected object %v", atPos(e.Sel), exp)
   794  				panic("unreachable")
   795  			}
   796  			x.expr = e
   797  			return
   798  		}
   799  	}
   800  
   801  	check.exprOrType(x, e.X, false)
   802  	switch x.mode() {
   803  	case builtin:
   804  		check.errorf(e.Pos(), UncalledBuiltin, "invalid use of %s in selector expression", x)
   805  		goto Error
   806  	case invalid:
   807  		goto Error
   808  	}
   809  
   810  	// We cannot select on an incomplete type; make sure it's complete.
   811  	if !check.isComplete(x.typ()) {
   812  		goto Error
   813  	}
   814  
   815  	// Avoid crashing when checking an invalid selector in a method declaration.
   816  	//
   817  	//   type S[T any] struct{}
   818  	//   type V = S[any]
   819  	//   func (fs *S[T]) M(x V.M) {}
   820  	//
   821  	// All codepaths below return a non-type expression. If we get here while
   822  	// expecting a type expression, it is an error.
   823  	//
   824  	// See go.dev/issue/57522 for more details.
   825  	if wantType {
   826  		check.errorf(e.Sel, NotAType, "%s is not a type", syntax.Expr(e))
   827  		goto Error
   828  	}
   829  
   830  	// Additionally, if x.typ is a pointer type, selecting implicitly dereferences the value, meaning
   831  	// its base type must also be complete.
   832  	if p, ok := x.typ().Underlying().(*Pointer); ok && !check.isComplete(p.base) {
   833  		goto Error
   834  	}
   835  
   836  	obj, index, indirect = lookupFieldOrMethod(x.typ(), x.mode() == variable, check.pkg, sel, false)
   837  	if obj == nil {
   838  		// Don't report another error if the underlying type was invalid (go.dev/issue/49541).
   839  		if !isValid(x.typ().Underlying()) {
   840  			goto Error
   841  		}
   842  
   843  		if index != nil {
   844  			// TODO(gri) should provide actual type where the conflict happens
   845  			check.errorf(e.Sel, AmbiguousSelector, "ambiguous selector %s.%s", x.expr, sel)
   846  			goto Error
   847  		}
   848  
   849  		if indirect {
   850  			if x.mode() == typexpr {
   851  				check.errorf(e.Sel, InvalidMethodExpr, "invalid method expression %s.%s (needs pointer receiver (*%s).%s)", x.typ(), sel, x.typ(), sel)
   852  			} else {
   853  				check.errorf(e.Sel, InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ())
   854  			}
   855  			goto Error
   856  		}
   857  
   858  		var why string
   859  		if isInterfacePtr(x.typ()) {
   860  			why = check.interfacePtrError(x.typ())
   861  		} else {
   862  			alt, _, _ := lookupFieldOrMethod(x.typ(), x.mode() == variable, check.pkg, sel, true)
   863  			why = check.lookupError(x.typ(), sel, alt, false)
   864  		}
   865  		check.errorf(e.Sel, MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why)
   866  		goto Error
   867  	}
   868  	// obj != nil
   869  
   870  	switch obj := obj.(type) {
   871  	case *Var:
   872  		if x.mode() == typexpr {
   873  			check.errorf(e.X, MissingFieldOrMethod, "operand for field selector %s must be value of type %s", sel, x.typ())
   874  			goto Error
   875  		}
   876  
   877  		// field value
   878  		check.recordSelection(e, FieldVal, x.typ(), obj, index, indirect)
   879  		if x.mode() == variable || indirect {
   880  			x.mode_ = variable
   881  		} else {
   882  			x.mode_ = value
   883  		}
   884  		x.typ_ = obj.typ
   885  
   886  	case *Func:
   887  		check.objDecl(obj) // ensure fully set-up signature
   888  		check.addDeclDep(obj)
   889  		// TODO(mark): Assert that sig.rparams is nil here?
   890  
   891  		if x.mode() == typexpr {
   892  			// method expression
   893  			check.recordSelection(e, MethodExpr, x.typ(), obj, index, indirect)
   894  
   895  			sig := obj.typ.(*Signature)
   896  			if sig.recv == nil {
   897  				check.error(e, InvalidDeclCycle, "illegal cycle in method declaration")
   898  				goto Error
   899  			}
   900  
   901  			// The receiver type becomes the type of the first function
   902  			// argument of the method expression's function type.
   903  			var params []*Var
   904  			if sig.params != nil {
   905  				params = sig.params.vars
   906  			}
   907  			// Be consistent about named/unnamed parameters. This is not needed
   908  			// for type-checking, but the newly constructed signature may appear
   909  			// in an error message and then have mixed named/unnamed parameters.
   910  			// (An alternative would be to not print parameter names in errors,
   911  			// but it's useful to see them; this is cheap and method expressions
   912  			// are rare.)
   913  			name := ""
   914  			if len(params) > 0 && params[0].name != "" {
   915  				// name needed
   916  				name = sig.recv.name
   917  				if name == "" {
   918  					name = "_"
   919  				}
   920  			}
   921  			params = append([]*Var{NewParam(sig.recv.pos, sig.recv.pkg, name, x.typ())}, params...)
   922  			x.mode_ = value
   923  			x.typ_ = &Signature{
   924  				tparams:  sig.tparams,
   925  				recvold:  methodExprSentinel,
   926  				params:   NewTuple(params...),
   927  				results:  sig.results,
   928  				variadic: sig.variadic,
   929  			}
   930  		} else {
   931  			// method value
   932  
   933  			// TODO(gri) If we needed to take into account the receiver's
   934  			// addressability, should we report the type &(x.typ) instead?
   935  			check.recordSelection(e, MethodVal, x.typ(), obj, index, indirect)
   936  
   937  			x.mode_ = value
   938  
   939  			// remove/stash receiver
   940  			sig := *obj.typ.(*Signature)
   941  			sig.recvold = sig.recv
   942  			sig.recv = nil
   943  			x.typ_ = &sig
   944  		}
   945  
   946  	default:
   947  		panic("unreachable")
   948  	}
   949  
   950  	// everything went well
   951  	x.expr = e
   952  	return
   953  
   954  Error:
   955  	x.invalidate()
   956  	x.typ_ = Typ[Invalid]
   957  	x.expr = e
   958  }
   959  
   960  // use type-checks each argument.
   961  // Useful to make sure expressions are evaluated
   962  // (and variables are "used") in the presence of
   963  // other errors. Arguments may be nil.
   964  // Reports if all arguments evaluated without error.
   965  func (check *Checker) use(args ...syntax.Expr) bool { return check.useN(args, false) }
   966  
   967  // useLHS is like use, but doesn't "use" top-level identifiers.
   968  // It should be called instead of use if the arguments are
   969  // expressions on the lhs of an assignment.
   970  func (check *Checker) useLHS(args ...syntax.Expr) bool { return check.useN(args, true) }
   971  
   972  func (check *Checker) useN(args []syntax.Expr, lhs bool) bool {
   973  	ok := true
   974  	for _, e := range args {
   975  		if !check.use1(e, lhs) {
   976  			ok = false
   977  		}
   978  	}
   979  	return ok
   980  }
   981  
   982  func (check *Checker) use1(e syntax.Expr, lhs bool) bool {
   983  	var x operand
   984  	x.mode_ = value // anything but invalid
   985  	switch n := syntax.Unparen(e).(type) {
   986  	case nil:
   987  		// nothing to do
   988  	case *syntax.Name:
   989  		// don't report an error evaluating blank
   990  		if n.Value == "_" {
   991  			break
   992  		}
   993  		// If the lhs is an identifier denoting a variable v, this assignment
   994  		// is not a 'use' of v. Remember current value of v.used and restore
   995  		// after evaluating the lhs via check.rawExpr.
   996  		var v *Var
   997  		var v_used bool
   998  		if lhs {
   999  			if obj := check.lookup(n.Value); obj != nil {
  1000  				// It's ok to mark non-local variables, but ignore variables
  1001  				// from other packages to avoid potential race conditions with
  1002  				// dot-imported variables.
  1003  				if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg {
  1004  					v = w
  1005  					v_used = check.usedVars[v]
  1006  				}
  1007  			}
  1008  		}
  1009  		check.exprOrType(&x, n, true)
  1010  		if v != nil {
  1011  			check.usedVars[v] = v_used // restore v.used
  1012  		}
  1013  	case *syntax.ListExpr:
  1014  		return check.useN(n.ElemList, lhs)
  1015  	default:
  1016  		check.rawExpr(nil, &x, e, true)
  1017  	}
  1018  	return x.isValid()
  1019  }
  1020  

View as plain text