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

View as plain text