...

Source file src/cmd/compile/internal/types2/call.go

Documentation: cmd/compile/internal/types2

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

View as plain text