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

View as plain text