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

View as plain text