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

View as plain text