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/token"
    12  	. "internal/types/errors"
    13  	"strings"
    14  )
    15  
    16  // funcInst type-checks a function instantiation.
    17  // The incoming x must be a generic function.
    18  // If ix != nil, it provides some or all of the type arguments (ix.Indices).
    19  // If target != nil, it may be used to infer missing type arguments of x, if any.
    20  // At least one of T or ix must be provided.
    21  //
    22  // There are two modes of operation:
    23  //
    24  //  1. If infer == true, funcInst infers missing type arguments as needed and
    25  //     instantiates the function x. The returned results are nil.
    26  //
    27  //  2. If infer == false and inst provides all type arguments, funcInst
    28  //     instantiates the function x. The returned results are nil.
    29  //     If inst doesn't provide enough type arguments, funcInst returns the
    30  //     available arguments; x remains unchanged.
    31  //
    32  // If an error (other than a version error) occurs in any case, it is reported
    33  // and x.mode is set to invalid.
    34  func (check *Checker) funcInst(T *target, pos token.Pos, x *operand, ix *indexedExpr, infer bool) []Type {
    35  	assert(T != nil || ix != nil)
    36  
    37  	var instErrPos positioner
    38  	if ix != nil {
    39  		instErrPos = inNode(ix.orig, ix.lbrack)
    40  		x.expr = ix.orig // if we don't have an index expression, keep the existing expression of x
    41  	} else {
    42  		instErrPos = atPos(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 []ast.Expr
    49  	if ix != nil {
    50  		xlist = ix.indices
    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(ix.indices[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 T != nil && sig.tparams != nil {
    90  			if !versionErr && !check.allowVersion(go1_21) {
    91  				if ix != 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 := ast.NewIdent(T.desc)
   103  			expr.NamePos = x.Pos() // correct position
   104  			args = []*operand{{mode_: value, expr: expr, typ_: T.sig}}
   105  			reverse = true
   106  		}
   107  
   108  		// Rename type parameters to avoid problems with recursive instantiations.
   109  		// Note that NewTuple(params...) below is (*Tuple)(nil) if len(params) == 0, as desired.
   110  		tparams, params2 := check.renameTParams(pos, sig.TypeParams().list(), NewTuple(params...))
   111  
   112  		err := check.newError(CannotInferTypeArgs)
   113  		targs = check.infer(atPos(pos), tparams, targs, params2.(*Tuple), args, reverse, err)
   114  		if targs == nil {
   115  			if !err.empty() {
   116  				err.report()
   117  			}
   118  			x.invalidate()
   119  			return nil
   120  		}
   121  		got = len(targs)
   122  	}
   123  	assert(got == want)
   124  
   125  	// instantiate function signature
   126  	sig = check.instantiateSignature(x.Pos(), x.expr, sig, targs, xlist)
   127  	x.typ_ = sig
   128  	x.mode_ = value
   129  	return nil
   130  }
   131  
   132  func (check *Checker) instantiateSignature(pos token.Pos, expr ast.Expr, typ *Signature, targs []Type, xlist []ast.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 = xlist[i].Pos()
   162  			}
   163  			check.softErrorf(atPos(pos), InvalidTypeArg, "%s", err)
   164  		} else {
   165  			check.mono.recordInstance(check.pkg, pos, tparams, targs, xlist)
   166  		}
   167  	}).describef(atPos(pos), "verify instantiation")
   168  
   169  	return inst
   170  }
   171  
   172  func (check *Checker) callExpr(x *operand, call *ast.CallExpr) exprKind {
   173  	ix := unpackIndexedExpr(call.Fun)
   174  	if ix != nil {
   175  		if check.indexExpr(x, ix) {
   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  		} else {
   181  			ix = nil
   182  		}
   183  		x.expr = call.Fun
   184  		check.record(x)
   185  	} else {
   186  		check.exprOrType(x, call.Fun, true)
   187  	}
   188  	// x.typ may be generic
   189  
   190  	switch x.mode() {
   191  	case invalid:
   192  		check.use(call.Args...)
   193  		x.expr = call
   194  		return statement
   195  
   196  	case typexpr:
   197  		// conversion
   198  		check.nonGeneric(nil, x)
   199  		if !x.isValid() {
   200  			return conversion
   201  		}
   202  		T := x.typ()
   203  		x.invalidate()
   204  		// We cannot convert a value to an incomplete type; make sure it's complete.
   205  		if !check.isComplete(T) {
   206  			x.expr = call
   207  			return conversion
   208  		}
   209  		switch n := len(call.Args); n {
   210  		case 0:
   211  			check.errorf(inNode(call, call.Rparen), WrongArgCount, "missing argument in conversion to %s", T)
   212  		case 1:
   213  			check.expr(nil, x, call.Args[0])
   214  			if x.isValid() {
   215  				if hasDots(call) {
   216  					check.errorf(call.Args[0], BadDotDotDotSyntax, "invalid use of ... in conversion to %s", T)
   217  					break
   218  				}
   219  				if t, _ := T.Underlying().(*Interface); t != nil && !isTypeParam(T) {
   220  					if !t.IsMethodSet() {
   221  						check.errorf(call, MisplacedConstraintIface, "cannot use interface %s in conversion (contains specific type constraints or is comparable)", T)
   222  						break
   223  					}
   224  				}
   225  				check.conversion(x, T)
   226  			}
   227  		default:
   228  			check.use(call.Args...)
   229  			check.errorf(call.Args[n-1], WrongArgCount, "too many arguments in conversion to %s", T)
   230  		}
   231  		x.expr = call
   232  		return conversion
   233  
   234  	case builtin:
   235  		// no need to check for non-genericity here
   236  		id := x.id
   237  		if !check.builtin(x, call, id) {
   238  			x.invalidate()
   239  		}
   240  		x.expr = call
   241  		// a non-constant result implies a function call
   242  		if x.isValid() && x.mode() != constant_ {
   243  			check.hasCallOrRecv = true
   244  		}
   245  		return predeclaredFuncs[id].kind
   246  	}
   247  
   248  	// ordinary function/method call
   249  	// signature may be generic
   250  	cgocall := x.mode() == cgofunc
   251  
   252  	// If the operand type is a type parameter, all types in its type set
   253  	// must have a common underlying type, which must be a signature.
   254  	u, err := commonUnder(x.typ(), func(t, u Type) *typeError {
   255  		if _, ok := u.(*Signature); u != nil && !ok {
   256  			return typeErrorf("%s is not a function", t)
   257  		}
   258  		return nil
   259  	})
   260  	if err != nil {
   261  		check.errorf(x, InvalidCall, invalidOp+"cannot call %s: %s", x, err.format(check))
   262  		x.invalidate()
   263  		x.expr = call
   264  		return statement
   265  	}
   266  	sig := u.(*Signature) // u must be a signature per the commonUnder condition
   267  
   268  	// Capture wasGeneric before sig is potentially instantiated below.
   269  	wasGeneric := sig.TypeParams().Len() > 0
   270  
   271  	// evaluate type arguments, if any
   272  	var xlist []ast.Expr
   273  	var targs []Type
   274  	if ix != nil {
   275  		xlist = ix.indices
   276  		targs = check.typeList(xlist)
   277  		if targs == nil {
   278  			check.use(call.Args...)
   279  			x.invalidate()
   280  			x.expr = call
   281  			return statement
   282  		}
   283  		assert(len(targs) == len(xlist))
   284  
   285  		// check number of type arguments (got) vs number of type parameters (want)
   286  		got, want := len(targs), sig.TypeParams().Len()
   287  		if got > want {
   288  			check.errorf(xlist[want], WrongTypeArgCount, "got %d type arguments but want %d", got, want)
   289  			check.use(call.Args...)
   290  			x.invalidate()
   291  			x.expr = call
   292  			return statement
   293  		}
   294  
   295  		// If sig is generic and all type arguments are provided, preempt function
   296  		// argument type inference by explicitly instantiating the signature. This
   297  		// ensures that we record accurate type information for sig, even if there
   298  		// is an error checking its arguments (for example, if an incorrect number
   299  		// of arguments is supplied).
   300  		if got == want && want > 0 {
   301  			check.verifyVersionf(atPos(ix.lbrack), go1_18, "function instantiation")
   302  			sig = check.instantiateSignature(ix.Pos(), ix.orig, sig, targs, xlist)
   303  			// targs have been consumed; proceed with checking arguments of the
   304  			// non-generic signature.
   305  			targs = nil
   306  			xlist = nil
   307  		}
   308  	}
   309  
   310  	// evaluate arguments
   311  	args, atargs := check.genericExprList(call.Args)
   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 []ast.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.
   373  // For each non-generic or uninstantiated generic operand, the corresponding targsList and
   374  // elements do not exist (targsList is nil) or the elements are nil.
   375  // For each partially instantiated generic function operand, the corresponding
   376  // targsList elements are the operand's partial type arguments.
   377  func (check *Checker) genericExprList(elist []ast.Expr) (resList []*operand, targsList [][]Type) {
   378  	if debug {
   379  		defer func() {
   380  			// type arguments must only exist for partially instantiated functions
   381  			for i, x := range resList {
   382  				if i < len(targsList) {
   383  					if n := len(targsList[i]); n > 0 {
   384  						// x must be a partially instantiated function
   385  						assert(n < x.typ().(*Signature).TypeParams().Len())
   386  					}
   387  				}
   388  			}
   389  		}()
   390  	}
   391  
   392  	// Before Go 1.21, uninstantiated or partially instantiated argument functions are
   393  	// nor permitted. Checker.funcInst must infer missing type arguments in that case.
   394  	infer := true // for -lang < go1.21
   395  	n := len(elist)
   396  	if n > 0 && check.allowVersion(go1_21) {
   397  		infer = false
   398  	}
   399  
   400  	if n == 1 {
   401  		// single value (possibly a partially instantiated function), or a multi-valued expression
   402  		e := elist[0]
   403  		var x operand
   404  		if ix := unpackIndexedExpr(e); ix != nil && check.indexExpr(&x, ix) {
   405  			// x is a generic function.
   406  			targs := check.funcInst(nil, x.Pos(), &x, ix, infer)
   407  			if targs != nil {
   408  				// x was not instantiated: collect the (partial) type arguments.
   409  				targsList = [][]Type{targs}
   410  				// Update x.expr so that we can record the partially instantiated function.
   411  				x.expr = ix.orig
   412  			} else {
   413  				// x was instantiated: we must record it here because we didn't
   414  				// use the usual expression evaluators.
   415  				check.record(&x)
   416  			}
   417  			resList = []*operand{&x}
   418  		} else {
   419  			// x is not a function instantiation (it may still be a generic function).
   420  			check.rawExpr(nil, &x, e, nil, true)
   421  			check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
   422  			if t, ok := x.typ().(*Tuple); ok && x.isValid() {
   423  				// x is a function call returning multiple values; it cannot be generic.
   424  				resList = make([]*operand, t.Len())
   425  				for i, v := range t.vars {
   426  					resList[i] = &operand{mode_: value, expr: e, typ_: v.typ}
   427  				}
   428  			} else {
   429  				// x is exactly one value (possibly invalid or uninstantiated generic function).
   430  				resList = []*operand{&x}
   431  			}
   432  		}
   433  	} else if n > 1 {
   434  		// multiple values
   435  		resList = make([]*operand, n)
   436  		targsList = make([][]Type, n)
   437  		for i, e := range elist {
   438  			var x operand
   439  			if ix := unpackIndexedExpr(e); ix != nil && check.indexExpr(&x, ix) {
   440  				// x is a generic function.
   441  				targs := check.funcInst(nil, x.Pos(), &x, ix, infer)
   442  				if targs != nil {
   443  					// x was not instantiated: collect the (partial) type arguments.
   444  					targsList[i] = targs
   445  					// Update x.expr so that we can record the partially instantiated function.
   446  					x.expr = ix.orig
   447  				} else {
   448  					// x was instantiated: we must record it here because we didn't
   449  					// use the usual expression evaluators.
   450  					check.record(&x)
   451  				}
   452  			} else {
   453  				// x is exactly one value (possibly invalid or uninstantiated generic function).
   454  				check.genericExpr(&x, e)
   455  			}
   456  			resList[i] = &x
   457  		}
   458  	}
   459  
   460  	return
   461  }
   462  
   463  // arguments type-checks arguments passed to a function call with the given signature.
   464  // The function and its arguments may be generic, and possibly partially instantiated.
   465  // targs and xlist are the function's type arguments (and corresponding expressions).
   466  // args are the function arguments. If an argument args[i] is a partially instantiated
   467  // generic function, atargs[i] are the corresponding type arguments.
   468  // If the callee is variadic, arguments adjusts its signature to match the provided
   469  // arguments. The type parameters and arguments of the callee and all its arguments
   470  // are used together to infer any missing type arguments, and the callee and argument
   471  // functions are instantiated as necessary.
   472  // The result signature is the (possibly adjusted and instantiated) function signature.
   473  // If an error occurred, the result signature is the incoming sig.
   474  func (check *Checker) arguments(call *ast.CallExpr, sig *Signature, targs []Type, xlist []ast.Expr, args []*operand, atargs [][]Type) (rsig *Signature) {
   475  	rsig = sig
   476  
   477  	// Function call argument/parameter count requirements
   478  	//
   479  	//               | standard call    | dotdotdot call |
   480  	// --------------+------------------+----------------+
   481  	// standard func | nargs == npars   | invalid        |
   482  	// --------------+------------------+----------------+
   483  	// variadic func | nargs >= npars-1 | nargs == npars |
   484  	// --------------+------------------+----------------+
   485  
   486  	nargs := len(args)
   487  	npars := sig.params.Len()
   488  	ddd := hasDots(call)
   489  
   490  	// set up parameters
   491  	sigParams := sig.params // adjusted for variadic functions (may be nil for empty parameter lists!)
   492  	adjusted := false       // indicates if sigParams is different from sig.params
   493  	if sig.variadic {
   494  		if ddd {
   495  			// variadic_func(a, b, c...)
   496  			if len(call.Args) == 1 && nargs > 1 {
   497  				// f()... is not permitted if f() is multi-valued
   498  				check.errorf(inNode(call, call.Ellipsis), InvalidDotDotDot, "cannot use ... with %d-valued %s", nargs, call.Args[0])
   499  				return
   500  			}
   501  		} else {
   502  			// variadic_func(a, b, c)
   503  			if nargs >= npars-1 {
   504  				// Create custom parameters for arguments: keep
   505  				// the first npars-1 parameters and add one for
   506  				// each argument mapping to the ... parameter.
   507  				vars := make([]*Var, npars-1) // npars > 0 for variadic functions
   508  				copy(vars, sig.params.vars)
   509  				last := sig.params.vars[npars-1]
   510  				typ := last.typ.(*Slice).elem
   511  				for len(vars) < nargs {
   512  					vars = append(vars, NewParam(last.pos, last.pkg, last.name, typ))
   513  				}
   514  				sigParams = NewTuple(vars...) // possibly nil!
   515  				adjusted = true
   516  				npars = nargs
   517  			} else {
   518  				// nargs < npars-1
   519  				npars-- // for correct error message below
   520  			}
   521  		}
   522  	} else {
   523  		if ddd {
   524  			// standard_func(a, b, c...)
   525  			check.errorf(inNode(call, call.Ellipsis), NonVariadicDotDotDot, "cannot use ... in call to non-variadic %s", call.Fun)
   526  			return
   527  		}
   528  		// standard_func(a, b, c)
   529  	}
   530  
   531  	// check argument count
   532  	if nargs != npars {
   533  		var at positioner = call
   534  		qualifier := "not enough"
   535  		if nargs > npars {
   536  			at = args[npars].expr // report at first extra argument
   537  			qualifier = "too many"
   538  		} else {
   539  			at = atPos(call.Rparen) // report at closing )
   540  		}
   541  		// take care of empty parameter lists represented by nil tuples
   542  		var params []*Var
   543  		if sig.params != nil {
   544  			params = sig.params.vars
   545  		}
   546  		err := check.newError(WrongArgCount)
   547  		err.addf(at, "%s arguments in call to %s", qualifier, call.Fun)
   548  		err.addf(noposn, "have %s", check.typesSummary(operandTypes(args), false, ddd))
   549  		err.addf(noposn, "want %s", check.typesSummary(varTypes(params), sig.variadic, false))
   550  		err.report()
   551  		return
   552  	}
   553  
   554  	// collect type parameters of callee and generic function arguments
   555  	var tparams []*TypeParam
   556  
   557  	// collect type parameters of callee
   558  	n := sig.TypeParams().Len()
   559  	if n > 0 {
   560  		if !check.allowVersion(go1_18) {
   561  			switch call.Fun.(type) {
   562  			case *ast.IndexExpr, *ast.IndexListExpr:
   563  				ix := unpackIndexedExpr(call.Fun)
   564  				check.versionErrorf(inNode(call.Fun, ix.lbrack), go1_18, "function instantiation")
   565  			default:
   566  				check.versionErrorf(inNode(call, call.Lparen), go1_18, "implicit function instantiation")
   567  			}
   568  		}
   569  		// rename type parameters to avoid problems with recursive calls
   570  		var tmp Type
   571  		tparams, tmp = check.renameTParams(call.Pos(), sig.TypeParams().list(), sigParams)
   572  		sigParams = tmp.(*Tuple)
   573  		// make sure targs and tparams have the same length
   574  		for len(targs) < len(tparams) {
   575  			targs = append(targs, nil)
   576  		}
   577  	}
   578  	assert(len(tparams) == len(targs))
   579  
   580  	// collect type parameters from generic function arguments
   581  	var genericArgs []int // indices of generic function arguments
   582  	if enableReverseTypeInference {
   583  		for i, arg := range args {
   584  			// generic arguments cannot have a defined (*Named) type - no need for underlying type below
   585  			if asig, _ := arg.typ().(*Signature); asig != nil && asig.TypeParams().Len() > 0 {
   586  				// The argument type is a generic function signature. This type is
   587  				// pointer-identical with (it's copied from) the type of the generic
   588  				// function argument and thus the function object.
   589  				// Before we change the type (type parameter renaming, below), make
   590  				// a clone of it as otherwise we implicitly modify the object's type
   591  				// (go.dev/issues/63260).
   592  				asig = clone(asig)
   593  				// Rename type parameters for cases like f(g, g); this gives each
   594  				// generic function argument a unique type identity (go.dev/issues/59956).
   595  				// TODO(gri) Consider only doing this if a function argument appears
   596  				//           multiple times, which is rare (possible optimization).
   597  				atparams, tmp := check.renameTParams(call.Pos(), asig.TypeParams().list(), asig)
   598  				asig = tmp.(*Signature)
   599  				asig.tparams = &TypeParamList{atparams} // renameTParams doesn't touch associated type parameters
   600  				arg.typ_ = asig                         // new type identity for the function argument
   601  				tparams = append(tparams, atparams...)
   602  				// add partial list of type arguments, if any
   603  				if i < len(atargs) {
   604  					targs = append(targs, atargs[i]...)
   605  				}
   606  				// make sure targs and tparams have the same length
   607  				for len(targs) < len(tparams) {
   608  					targs = append(targs, nil)
   609  				}
   610  				genericArgs = append(genericArgs, i)
   611  			}
   612  		}
   613  	}
   614  	assert(len(tparams) == len(targs))
   615  
   616  	// at the moment we only support implicit instantiations of argument functions
   617  	_ = len(genericArgs) > 0 && check.verifyVersionf(args[genericArgs[0]], go1_21, "implicitly instantiated function as argument")
   618  
   619  	// tparams holds the type parameters of the callee and generic function arguments, if any:
   620  	// the first n type parameters belong to the callee, followed by mi type parameters for each
   621  	// of the generic function arguments, where mi = args[i].typ.(*Signature).TypeParams().Len().
   622  
   623  	// infer missing type arguments of callee and function arguments
   624  	if len(tparams) > 0 {
   625  		err := check.newError(CannotInferTypeArgs)
   626  		targs = check.infer(call, tparams, targs, sigParams, args, false, err)
   627  		if targs == nil {
   628  			// TODO(gri) If infer inferred the first targs[:n], consider instantiating
   629  			//           the call signature for better error messages/gopls behavior.
   630  			//           Perhaps instantiate as much as we can, also for arguments.
   631  			//           This will require changes to how infer returns its results.
   632  			if !err.empty() {
   633  				check.errorf(err.posn(), CannotInferTypeArgs, "in call to %s, %s", call.Fun, err.msg())
   634  			}
   635  			return
   636  		}
   637  
   638  		// update result signature: instantiate if needed
   639  		if n > 0 {
   640  			rsig = check.instantiateSignature(call.Pos(), call.Fun, sig, targs[:n], xlist)
   641  			// If the callee's parameter list was adjusted we need to update (instantiate)
   642  			// it separately. Otherwise we can simply use the result signature's parameter
   643  			// list.
   644  			if adjusted {
   645  				sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(tparams[:n], targs[:n]), nil, check.context()).(*Tuple)
   646  			} else {
   647  				sigParams = rsig.params
   648  			}
   649  		}
   650  
   651  		// compute argument signatures: instantiate if needed
   652  		j := n
   653  		for _, i := range genericArgs {
   654  			arg := args[i]
   655  			asig := arg.typ().(*Signature)
   656  			k := j + asig.TypeParams().Len()
   657  			// targs[j:k] are the inferred type arguments for asig
   658  			arg.typ_ = check.instantiateSignature(call.Pos(), arg.expr, asig, targs[j:k], nil) // TODO(gri) provide xlist if possible (partial instantiations)
   659  			check.record(arg)                                                                  // record here because we didn't use the usual expr evaluators
   660  			j = k
   661  		}
   662  	}
   663  
   664  	// check arguments
   665  	if len(args) > 0 {
   666  		context := check.sprintf("argument to %s", call.Fun)
   667  		for i, a := range args {
   668  			check.assignment(a, sigParams.vars[i].typ, context)
   669  		}
   670  	}
   671  
   672  	return
   673  }
   674  
   675  var cgoPrefixes = [...]string{
   676  	"_Ciconst_",
   677  	"_Cfconst_",
   678  	"_Csconst_",
   679  	"_Ctype_",
   680  	"_Cvar_", // actually a pointer to the var
   681  	"_Cfpvar_fp_",
   682  	"_Cfunc_",
   683  	"_Cmacro_", // function to evaluate the expanded expression
   684  }
   685  
   686  func (check *Checker) selector(x *operand, e *ast.SelectorExpr, wantType bool) {
   687  	// these must be declared before the "goto Error" statements
   688  	var (
   689  		obj      Object
   690  		index    []int
   691  		indirect bool
   692  	)
   693  
   694  	sel := e.Sel.Name
   695  	// If the identifier refers to a package, handle everything here
   696  	// so we don't need a "package" mode for operands: package names
   697  	// can only appear in qualified identifiers which are mapped to
   698  	// selector expressions.
   699  	if ident, ok := e.X.(*ast.Ident); ok {
   700  		obj := check.lookup(ident.Name)
   701  		if pname, _ := obj.(*PkgName); pname != nil {
   702  			assert(pname.pkg == check.pkg)
   703  			check.recordUse(ident, pname)
   704  			check.usedPkgNames[pname] = true
   705  			pkg := pname.imported
   706  
   707  			var exp Object
   708  			funcMode := value
   709  			if pkg.cgo {
   710  				// cgo special cases C.malloc: it's
   711  				// rewritten to _CMalloc and does not
   712  				// support two-result calls.
   713  				if sel == "malloc" {
   714  					sel = "_CMalloc"
   715  				} else {
   716  					funcMode = cgofunc
   717  				}
   718  				for _, prefix := range cgoPrefixes {
   719  					// cgo objects are part of the current package (in file
   720  					// _cgo_gotypes.go). Use regular lookup.
   721  					exp = check.lookup(prefix + sel)
   722  					if exp != nil {
   723  						break
   724  					}
   725  				}
   726  				if exp == nil {
   727  					if isValidName(sel) {
   728  						check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s", ast.Expr(e)) // cast to ast.Expr to silence vet
   729  					}
   730  					goto Error
   731  				}
   732  				check.objDecl(exp)
   733  			} else {
   734  				exp = pkg.scope.Lookup(sel)
   735  				if exp == nil {
   736  					if !pkg.fake && isValidName(sel) {
   737  						// Try to give a better error message when selector matches an object name ignoring case.
   738  						exps := pkg.scope.lookupIgnoringCase(sel, true)
   739  						if len(exps) >= 1 {
   740  							// report just the first one
   741  							check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s (but have %s)", ast.Expr(e), exps[0].Name())
   742  						} else {
   743  							check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s", ast.Expr(e))
   744  						}
   745  					}
   746  					goto Error
   747  				}
   748  				if !exp.Exported() {
   749  					check.errorf(e.Sel, UnexportedName, "name %s not exported by package %s", sel, pkg.name)
   750  					// ok to continue
   751  				}
   752  			}
   753  			check.recordUse(e.Sel, exp)
   754  
   755  			// Simplified version of the code for *ast.Idents:
   756  			// - imported objects are always fully initialized
   757  			switch exp := exp.(type) {
   758  			case *Const:
   759  				assert(exp.Val() != nil)
   760  				x.mode_ = constant_
   761  				x.typ_ = exp.typ
   762  				x.val = exp.val
   763  			case *TypeName:
   764  				x.mode_ = typexpr
   765  				x.typ_ = exp.typ
   766  			case *Var:
   767  				x.mode_ = variable
   768  				x.typ_ = exp.typ
   769  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
   770  					x.typ_ = x.typ().(*Pointer).base
   771  				}
   772  			case *Func:
   773  				x.mode_ = funcMode
   774  				x.typ_ = exp.typ
   775  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
   776  					x.mode_ = value
   777  					x.typ_ = x.typ().(*Signature).results.vars[0].typ
   778  				}
   779  			case *Builtin:
   780  				x.mode_ = builtin
   781  				x.typ_ = exp.typ
   782  				x.id = exp.id
   783  			default:
   784  				check.dump("%v: unexpected object %v", e.Sel.Pos(), exp)
   785  				panic("unreachable")
   786  			}
   787  			x.expr = e
   788  			return
   789  		}
   790  	}
   791  
   792  	check.exprOrType(x, e.X, false)
   793  	switch x.mode() {
   794  	case builtin:
   795  		// types2 uses the position of '.' for the error
   796  		check.errorf(e.Sel, 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", ast.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  
   882  		if x.mode() == typexpr {
   883  			// method expression
   884  			check.recordSelection(e, MethodExpr, x.typ(), obj, index, indirect)
   885  
   886  			sig := obj.typ.(*Signature)
   887  			if sig.recv == nil {
   888  				check.error(e, InvalidDeclCycle, "illegal cycle in method declaration")
   889  				goto Error
   890  			}
   891  
   892  			// The receiver type becomes the type of the first function
   893  			// argument of the method expression's function type.
   894  			var params []*Var
   895  			if sig.params != nil {
   896  				params = sig.params.vars
   897  			}
   898  			// Be consistent about named/unnamed parameters. This is not needed
   899  			// for type-checking, but the newly constructed signature may appear
   900  			// in an error message and then have mixed named/unnamed parameters.
   901  			// (An alternative would be to not print parameter names in errors,
   902  			// but it's useful to see them; this is cheap and method expressions
   903  			// are rare.)
   904  			name := ""
   905  			if len(params) > 0 && params[0].name != "" {
   906  				// name needed
   907  				name = sig.recv.name
   908  				if name == "" {
   909  					name = "_"
   910  				}
   911  			}
   912  			params = append([]*Var{NewParam(sig.recv.pos, sig.recv.pkg, name, x.typ())}, params...)
   913  			x.mode_ = value
   914  			x.typ_ = &Signature{
   915  				tparams:  sig.tparams,
   916  				params:   NewTuple(params...),
   917  				results:  sig.results,
   918  				variadic: sig.variadic,
   919  			}
   920  		} else {
   921  			// method value
   922  
   923  			// TODO(gri) If we needed to take into account the receiver's
   924  			// addressability, should we report the type &(x.typ) instead?
   925  			check.recordSelection(e, MethodVal, x.typ(), obj, index, indirect)
   926  
   927  			// TODO(gri) The verification pass below is disabled for now because
   928  			//           method sets don't match method lookup in some cases.
   929  			//           For instance, if we made a copy above when creating a
   930  			//           custom method for a parameterized received type, the
   931  			//           method set method doesn't match (no copy there). There
   932  			///          may be other situations.
   933  			disabled := true
   934  			if !disabled && debug {
   935  				// Verify that LookupFieldOrMethod and MethodSet.Lookup agree.
   936  				// TODO(gri) This only works because we call LookupFieldOrMethod
   937  				// _before_ calling NewMethodSet: LookupFieldOrMethod completes
   938  				// any incomplete interfaces so they are available to NewMethodSet
   939  				// (which assumes that interfaces have been completed already).
   940  				typ := x.typ_
   941  				if x.mode() == variable {
   942  					// If typ is not an (unnamed) pointer or an interface,
   943  					// use *typ instead, because the method set of *typ
   944  					// includes the methods of typ.
   945  					// Variables are addressable, so we can always take their
   946  					// address.
   947  					if _, ok := typ.(*Pointer); !ok && !IsInterface(typ) {
   948  						typ = &Pointer{base: typ}
   949  					}
   950  				}
   951  				// If we created a synthetic pointer type above, we will throw
   952  				// away the method set computed here after use.
   953  				// TODO(gri) Method set computation should probably always compute
   954  				// both, the value and the pointer receiver method set and represent
   955  				// them in a single structure.
   956  				// TODO(gri) Consider also using a method set cache for the lifetime
   957  				// of checker once we rely on MethodSet lookup instead of individual
   958  				// lookup.
   959  				mset := NewMethodSet(typ)
   960  				if m := mset.Lookup(check.pkg, sel); m == nil || m.obj != obj {
   961  					check.dump("%v: (%s).%v -> %s", e.Pos(), typ, obj.name, m)
   962  					check.dump("%s\n", mset)
   963  					// Caution: MethodSets are supposed to be used externally
   964  					// only (after all interface types were completed). It's
   965  					// now possible that we get here incorrectly. Not urgent
   966  					// to fix since we only run this code in debug mode.
   967  					// TODO(gri) fix this eventually.
   968  					panic("method sets and lookup don't agree")
   969  				}
   970  			}
   971  
   972  			x.mode_ = value
   973  
   974  			// remove receiver
   975  			sig := *obj.typ.(*Signature)
   976  			sig.recv = nil
   977  			x.typ_ = &sig
   978  		}
   979  
   980  	default:
   981  		panic("unreachable")
   982  	}
   983  
   984  	// everything went well
   985  	x.expr = e
   986  	return
   987  
   988  Error:
   989  	x.invalidate()
   990  	x.typ_ = Typ[Invalid]
   991  	x.expr = e
   992  }
   993  
   994  // use type-checks each argument.
   995  // Useful to make sure expressions are evaluated
   996  // (and variables are "used") in the presence of
   997  // other errors. Arguments may be nil.
   998  // Reports if all arguments evaluated without error.
   999  func (check *Checker) use(args ...ast.Expr) bool { return check.useN(args, false) }
  1000  
  1001  // useLHS is like use, but doesn't "use" top-level identifiers.
  1002  // It should be called instead of use if the arguments are
  1003  // expressions on the lhs of an assignment.
  1004  func (check *Checker) useLHS(args ...ast.Expr) bool { return check.useN(args, true) }
  1005  
  1006  func (check *Checker) useN(args []ast.Expr, lhs bool) bool {
  1007  	ok := true
  1008  	for _, e := range args {
  1009  		if !check.use1(e, lhs) {
  1010  			ok = false
  1011  		}
  1012  	}
  1013  	return ok
  1014  }
  1015  
  1016  func (check *Checker) use1(e ast.Expr, lhs bool) bool {
  1017  	var x operand
  1018  	x.mode_ = value // anything but invalid
  1019  	switch n := ast.Unparen(e).(type) {
  1020  	case nil:
  1021  		// nothing to do
  1022  	case *ast.Ident:
  1023  		// don't report an error evaluating blank
  1024  		if n.Name == "_" {
  1025  			break
  1026  		}
  1027  		// If the lhs is an identifier denoting a variable v, this assignment
  1028  		// is not a 'use' of v. Remember current value of v.used and restore
  1029  		// after evaluating the lhs via check.rawExpr.
  1030  		var v *Var
  1031  		var v_used bool
  1032  		if lhs {
  1033  			if obj := check.lookup(n.Name); obj != nil {
  1034  				// It's ok to mark non-local variables, but ignore variables
  1035  				// from other packages to avoid potential race conditions with
  1036  				// dot-imported variables.
  1037  				if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg {
  1038  					v = w
  1039  					v_used = check.usedVars[v]
  1040  				}
  1041  			}
  1042  		}
  1043  		check.exprOrType(&x, n, true)
  1044  		if v != nil {
  1045  			check.usedVars[v] = v_used // restore v.used
  1046  		}
  1047  	default:
  1048  		check.rawExpr(nil, &x, e, nil, true)
  1049  	}
  1050  	return x.isValid()
  1051  }
  1052  

View as plain text