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

View as plain text