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(newTarget(T, "conversion"), T, 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(sig.argType, 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, 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. Additionally, typeAt must return the
   371  // corresponding target type for each operand, or nil if none exists.
   372  // For each non-generic or uninstantiated generic operand, the corresponding targsList and
   373  // elements do not exist (targsList is nil) or the elements are nil.
   374  // For each partially instantiated generic function operand, the corresponding
   375  // targsList elements are the operand's partial type arguments.
   376  func (check *Checker) genericExprList(typeAt func(int) Type, elist []syntax.Expr) (resList []*operand, targsList [][]Type) {
   377  	if debug {
   378  		defer func() {
   379  			// type arguments must only exist for partially instantiated functions
   380  			for i, x := range resList {
   381  				if i < len(targsList) {
   382  					if n := len(targsList[i]); n > 0 {
   383  						// x must be a partially instantiated function
   384  						assert(n < x.typ().(*Signature).TypeParams().Len())
   385  					}
   386  				}
   387  			}
   388  		}()
   389  	}
   390  
   391  	// Before Go 1.21, uninstantiated or partially instantiated argument functions are
   392  	// not permitted. Checker.funcInst must infer missing type arguments in that case.
   393  	infer := true // for -lang < go1.21
   394  	n := len(elist)
   395  	if n > 0 && check.allowVersion(go1_21) {
   396  		infer = false
   397  	}
   398  
   399  	if n == 1 {
   400  		// single value (possibly a partially instantiated function), or a multi-valued expression
   401  		e := elist[0]
   402  		var x operand
   403  		if inst, _ := e.(*syntax.IndexExpr); inst != nil && check.indexExpr(&x, inst) {
   404  			// x is a generic function.
   405  			targs := check.funcInst(nil, x.Pos(), &x, inst, infer)
   406  			if targs != nil {
   407  				// x was not instantiated: collect the (partial) type arguments.
   408  				targsList = [][]Type{targs}
   409  				// Update x.expr so that we can record the partially instantiated function.
   410  				x.expr = inst
   411  			} else {
   412  				// x was instantiated: we must record it here because we didn't
   413  				// use the usual expression evaluators.
   414  				check.record(&x)
   415  			}
   416  			resList = []*operand{&x}
   417  		} else {
   418  			// x is not a function instantiation (it may still be a generic function).
   419  			check.rawExpr(nil, typeAt(0), &x, e, nil, true)
   420  			check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
   421  			if t, ok := x.typ().(*Tuple); ok && x.isValid() {
   422  				// x is a function call returning multiple values; it cannot be generic.
   423  				resList = make([]*operand, t.Len())
   424  				for i, v := range t.vars {
   425  					resList[i] = &operand{mode_: value, expr: e, typ_: v.typ}
   426  				}
   427  			} else {
   428  				// x is exactly one value (possibly invalid or uninstantiated generic function).
   429  				resList = []*operand{&x}
   430  			}
   431  		}
   432  	} else if n > 1 {
   433  		// multiple values
   434  		resList = make([]*operand, n)
   435  		targsList = make([][]Type, n)
   436  		for i, e := range elist {
   437  			var x operand
   438  			if inst, _ := e.(*syntax.IndexExpr); inst != nil && check.indexExpr(&x, inst) {
   439  				// x is a generic function.
   440  				targs := check.funcInst(nil, x.Pos(), &x, inst, infer)
   441  				if targs != nil {
   442  					// x was not instantiated: collect the (partial) type arguments.
   443  					targsList[i] = targs
   444  					// Update x.expr so that we can record the partially instantiated function.
   445  					x.expr = inst
   446  				} else {
   447  					// x was instantiated: we must record it here because we didn't
   448  					// use the usual expression evaluators.
   449  					check.record(&x)
   450  				}
   451  			} else {
   452  				// x is exactly one value (possibly invalid or uninstantiated generic function).
   453  				check.genericExpr(typeAt(i), &x, e, nil)
   454  			}
   455  			resList[i] = &x
   456  		}
   457  	}
   458  
   459  	return
   460  }
   461  
   462  // arguments type-checks arguments passed to a function call with the given signature.
   463  // The function and its arguments may be generic, and possibly partially instantiated.
   464  // targs and xlist are the function's type arguments (and corresponding expressions).
   465  // args are the function arguments. If an argument args[i] is a partially instantiated
   466  // generic function, atargs[i] are the corresponding type arguments.
   467  // If the callee is variadic, arguments adjusts its signature to match the provided
   468  // arguments. The type parameters and arguments of the callee and all its arguments
   469  // are used together to infer any missing type arguments, and the callee and argument
   470  // functions are instantiated as necessary.
   471  // The result signature is the (possibly adjusted and instantiated) function signature.
   472  // If an error occurred, the result signature is the incoming sig.
   473  func (check *Checker) arguments(call *syntax.CallExpr, sig *Signature, targs []Type, xlist []syntax.Expr, args []*operand, atargs [][]Type) (rsig *Signature) {
   474  	rsig = sig
   475  
   476  	// Function call argument/parameter count requirements
   477  	//
   478  	//               | standard call    | dotdotdot call |
   479  	// --------------+------------------+----------------+
   480  	// standard func | nargs == npars   | invalid        |
   481  	// --------------+------------------+----------------+
   482  	// variadic func | nargs >= npars-1 | nargs == npars |
   483  	// --------------+------------------+----------------+
   484  
   485  	nargs := len(args)
   486  	npars := sig.params.Len()
   487  	ddd := hasDots(call)
   488  
   489  	// set up parameters
   490  	sigParams := sig.params // adjusted for variadic functions (may be nil for empty parameter lists!)
   491  	adjusted := false       // indicates if sigParams is different from sig.params
   492  	if sig.variadic {
   493  		if ddd {
   494  			// variadic_func(a, b, c...)
   495  			if len(call.ArgList) == 1 && nargs > 1 {
   496  				// f()... is not permitted if f() is multi-valued
   497  				//check.errorf(call.Ellipsis, "cannot use ... with %d-valued %s", nargs, call.ArgList[0])
   498  				check.errorf(call, InvalidDotDotDot, "cannot use ... with %d-valued %s", nargs, call.ArgList[0])
   499  				return
   500  			}
   501  		} else {
   502  			// variadic_func(a, b, c)
   503  			if nargs >= npars-1 {
   504  				// Create custom parameters for arguments: keep
   505  				// the first npars-1 parameters and add one for
   506  				// each argument mapping to the ... parameter.
   507  				vars := make([]*Var, npars-1) // npars > 0 for variadic functions
   508  				copy(vars, sig.params.vars)
   509  				last := sig.params.vars[npars-1]
   510  				typ := last.typ.(*Slice).elem
   511  				for len(vars) < nargs {
   512  					vars = append(vars, NewParam(last.pos, last.pkg, last.name, typ))
   513  				}
   514  				sigParams = NewTuple(vars...) // possibly nil!
   515  				adjusted = true
   516  				npars = nargs
   517  			} else {
   518  				// nargs < npars-1
   519  				npars-- // for correct error message below
   520  			}
   521  		}
   522  	} else {
   523  		if ddd {
   524  			// standard_func(a, b, c...)
   525  			//check.errorf(call.Ellipsis, "cannot use ... in call to non-variadic %s", call.Fun)
   526  			check.errorf(call, NonVariadicDotDotDot, "cannot use ... in call to non-variadic %s", call.Fun)
   527  			return
   528  		}
   529  		// standard_func(a, b, c)
   530  	}
   531  
   532  	// check argument count
   533  	if nargs != npars {
   534  		var at poser = call
   535  		qualifier := "not enough"
   536  		if nargs > npars {
   537  			at = args[npars].expr // report at first extra argument
   538  			qualifier = "too many"
   539  		} else if nargs > 0 {
   540  			at = args[nargs-1].expr // report at last argument
   541  		}
   542  		// take care of empty parameter lists represented by nil tuples
   543  		var params []*Var
   544  		if sig.params != nil {
   545  			params = sig.params.vars
   546  		}
   547  		err := check.newError(WrongArgCount)
   548  		err.addf(at, "%s arguments in call to %s", qualifier, call.Fun)
   549  		err.addf(nopos, "have %s", check.typesSummary(operandTypes(args), false, ddd))
   550  		err.addf(nopos, "want %s", check.typesSummary(varTypes(params), sig.variadic, false))
   551  		err.report()
   552  		return
   553  	}
   554  
   555  	// collect type parameters of callee and generic function arguments
   556  	var tparams []*TypeParam
   557  
   558  	// collect type parameters of callee
   559  	n := sig.TypeParams().Len()
   560  	if n > 0 {
   561  		if !check.allowVersion(go1_18) {
   562  			if iexpr, _ := call.Fun.(*syntax.IndexExpr); iexpr != nil {
   563  				check.versionErrorf(iexpr, go1_18, "function instantiation")
   564  			} else {
   565  				check.versionErrorf(call, go1_18, "implicit function instantiation")
   566  			}
   567  		}
   568  		// rename type parameters to avoid problems with recursive calls
   569  		var tmp Type
   570  		tparams, tmp = check.renameTParams(call.Pos(), sig.TypeParams().list(), sigParams)
   571  		sigParams = tmp.(*Tuple)
   572  		// make sure targs and tparams have the same length
   573  		for len(targs) < len(tparams) {
   574  			targs = append(targs, nil)
   575  		}
   576  	}
   577  	assert(len(tparams) == len(targs))
   578  
   579  	// collect type parameters from generic function arguments
   580  	var genericArgs []int // indices of generic function arguments
   581  	if enableReverseTypeInference {
   582  		for i, arg := range args {
   583  			// generic arguments cannot have a defined (*Named) type - no need for underlying type below
   584  			if asig, _ := arg.typ().(*Signature); asig != nil && asig.TypeParams().Len() > 0 {
   585  				// The argument type is a generic function signature. This type is
   586  				// pointer-identical with (it's copied from) the type of the generic
   587  				// function argument and thus the function object.
   588  				// Before we change the type (type parameter renaming, below), make
   589  				// a clone of it as otherwise we implicitly modify the object's type
   590  				// (go.dev/issues/63260).
   591  				asig = clone(asig)
   592  				// Rename type parameters for cases like f(g, g); this gives each
   593  				// generic function argument a unique type identity (go.dev/issues/59956).
   594  				// TODO(gri) Consider only doing this if a function argument appears
   595  				//           multiple times, which is rare (possible optimization).
   596  				atparams, tmp := check.renameTParams(call.Pos(), asig.TypeParams().list(), asig)
   597  				asig = tmp.(*Signature)
   598  				asig.tparams = &TypeParamList{atparams} // renameTParams doesn't touch associated type parameters
   599  				arg.typ_ = asig                         // new type identity for the function argument
   600  				tparams = append(tparams, atparams...)
   601  				// add partial list of type arguments, if any
   602  				if i < len(atargs) {
   603  					targs = append(targs, atargs[i]...)
   604  				}
   605  				// make sure targs and tparams have the same length
   606  				for len(targs) < len(tparams) {
   607  					targs = append(targs, nil)
   608  				}
   609  				genericArgs = append(genericArgs, i)
   610  			}
   611  		}
   612  	}
   613  	assert(len(tparams) == len(targs))
   614  
   615  	// at the moment we only support implicit instantiations of argument functions
   616  	_ = len(genericArgs) > 0 && check.verifyVersionf(args[genericArgs[0]], go1_21, "implicitly instantiated function as argument")
   617  
   618  	// tparams holds the type parameters of the callee and generic function arguments, if any:
   619  	// the first n type parameters belong to the callee, followed by mi type parameters for each
   620  	// of the generic function arguments, where mi = args[i].typ.(*Signature).TypeParams().Len().
   621  
   622  	// infer missing type arguments of callee and function arguments
   623  	if len(tparams) > 0 {
   624  		err := check.newError(CannotInferTypeArgs)
   625  		targs = check.infer(call.Pos(), tparams, targs, sigParams, args, false, err)
   626  		if targs == nil {
   627  			// TODO(gri) If infer inferred the first targs[:n], consider instantiating
   628  			//           the call signature for better error messages/gopls behavior.
   629  			//           Perhaps instantiate as much as we can, also for arguments.
   630  			//           This will require changes to how infer returns its results.
   631  			if !err.empty() {
   632  				check.errorf(err.pos(), CannotInferTypeArgs, "in call to %s, %s", call.Fun, err.msg())
   633  			}
   634  			return
   635  		}
   636  
   637  		// update result signature: instantiate if needed
   638  		if n > 0 {
   639  			rsig = check.instantiateSignature(call.Pos(), call.Fun, sig, targs[:n], xlist)
   640  			// If the callee's parameter list was adjusted we need to update (instantiate)
   641  			// it separately. Otherwise we can simply use the result signature's parameter
   642  			// list.
   643  			if adjusted {
   644  				sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(tparams[:n], targs[:n]), nil, check.context()).(*Tuple)
   645  			} else {
   646  				sigParams = rsig.params
   647  			}
   648  		}
   649  
   650  		// compute argument signatures: instantiate if needed
   651  		j := n
   652  		for _, i := range genericArgs {
   653  			arg := args[i]
   654  			asig := arg.typ().(*Signature)
   655  			k := j + asig.TypeParams().Len()
   656  			// targs[j:k] are the inferred type arguments for asig
   657  			arg.typ_ = check.instantiateSignature(call.Pos(), arg.expr, asig, targs[j:k], nil) // TODO(gri) provide xlist if possible (partial instantiations)
   658  			check.record(arg)                                                                  // record here because we didn't use the usual expr evaluators
   659  			j = k
   660  		}
   661  	}
   662  
   663  	// check arguments
   664  	if len(args) > 0 {
   665  		context := check.sprintf("argument to %s", call.Fun)
   666  		for i, a := range args {
   667  			check.assignment(a, sigParams.vars[i].typ, context)
   668  		}
   669  	}
   670  
   671  	return
   672  }
   673  
   674  var cgoPrefixes = [...]string{
   675  	"_Ciconst_",
   676  	"_Cfconst_",
   677  	"_Csconst_",
   678  	"_Ctype_",
   679  	"_Cvar_", // actually a pointer to the var
   680  	"_Cfpvar_fp_",
   681  	"_Cfunc_",
   682  	"_Cmacro_", // function to evaluate the expanded expression
   683  }
   684  
   685  func (check *Checker) selector(x *operand, e *syntax.SelectorExpr, wantType bool) {
   686  	// these must be declared before the "goto Error" statements
   687  	var (
   688  		obj      Object
   689  		index    []int
   690  		indirect bool
   691  	)
   692  
   693  	sel := e.Sel.Value
   694  	// If the identifier refers to a package, handle everything here
   695  	// so we don't need a "package" mode for operands: package names
   696  	// can only appear in qualified identifiers which are mapped to
   697  	// selector expressions.
   698  	if ident, ok := e.X.(*syntax.Name); ok {
   699  		obj := check.lookup(ident.Value)
   700  		if pname, _ := obj.(*PkgName); pname != nil {
   701  			assert(pname.pkg == check.pkg)
   702  			check.recordUse(ident, pname)
   703  			check.usedPkgNames[pname] = true
   704  			pkg := pname.imported
   705  
   706  			var exp Object
   707  			funcMode := value
   708  			if pkg.cgo {
   709  				// cgo special cases C.malloc: it's
   710  				// rewritten to _CMalloc and does not
   711  				// support two-result calls.
   712  				if sel == "malloc" {
   713  					sel = "_CMalloc"
   714  				} else {
   715  					funcMode = cgofunc
   716  				}
   717  				for _, prefix := range cgoPrefixes {
   718  					// cgo objects are part of the current package (in file
   719  					// _cgo_gotypes.go). Use regular lookup.
   720  					exp = check.lookup(prefix + sel)
   721  					if exp != nil {
   722  						break
   723  					}
   724  				}
   725  				if exp == nil {
   726  					if isValidName(sel) {
   727  						check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s", syntax.Expr(e)) // cast to syntax.Expr to silence vet
   728  					}
   729  					goto Error
   730  				}
   731  				check.objDecl(exp)
   732  			} else {
   733  				exp = pkg.scope.Lookup(sel)
   734  				if exp == nil {
   735  					if !pkg.fake && isValidName(sel) {
   736  						// Try to give a better error message when selector matches an object name ignoring case.
   737  						exps := pkg.scope.lookupIgnoringCase(sel, true)
   738  						if len(exps) >= 1 {
   739  							// report just the first one
   740  							check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s (but have %s)", syntax.Expr(e), exps[0].Name())
   741  						} else {
   742  							check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s", syntax.Expr(e))
   743  						}
   744  					}
   745  					goto Error
   746  				}
   747  				if !exp.Exported() {
   748  					check.errorf(e.Sel, UnexportedName, "name %s not exported by package %s", sel, pkg.name)
   749  					// ok to continue
   750  				}
   751  			}
   752  			check.recordUse(e.Sel, exp)
   753  
   754  			// Simplified version of the code for *syntax.Names:
   755  			// - imported objects are always fully initialized
   756  			switch exp := exp.(type) {
   757  			case *Const:
   758  				assert(exp.Val() != nil)
   759  				x.mode_ = constant_
   760  				x.typ_ = exp.typ
   761  				x.val = exp.val
   762  			case *TypeName:
   763  				x.mode_ = typexpr
   764  				x.typ_ = exp.typ
   765  			case *Var:
   766  				x.mode_ = variable
   767  				x.typ_ = exp.typ
   768  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
   769  					x.typ_ = x.typ().(*Pointer).base
   770  				}
   771  			case *Func:
   772  				x.mode_ = funcMode
   773  				x.typ_ = exp.typ
   774  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
   775  					x.mode_ = value
   776  					x.typ_ = x.typ().(*Signature).results.vars[0].typ
   777  				}
   778  			case *Builtin:
   779  				x.mode_ = builtin
   780  				x.typ_ = exp.typ
   781  				x.id = exp.id
   782  			default:
   783  				check.dump("%v: unexpected object %v", atPos(e.Sel), exp)
   784  				panic("unreachable")
   785  			}
   786  			x.expr = e
   787  			return
   788  		}
   789  	}
   790  
   791  	check.exprOrType(x, e.X, false)
   792  	switch x.mode() {
   793  	case builtin:
   794  		check.errorf(e.Pos(), UncalledBuiltin, "invalid use of %s in selector expression", x)
   795  		goto Error
   796  	case invalid:
   797  		goto Error
   798  	}
   799  
   800  	// We cannot select on an incomplete type; make sure it's complete.
   801  	if !check.isComplete(x.typ()) {
   802  		goto Error
   803  	}
   804  
   805  	// Avoid crashing when checking an invalid selector in a method declaration.
   806  	//
   807  	//   type S[T any] struct{}
   808  	//   type V = S[any]
   809  	//   func (fs *S[T]) M(x V.M) {}
   810  	//
   811  	// All codepaths below return a non-type expression. If we get here while
   812  	// expecting a type expression, it is an error.
   813  	//
   814  	// See go.dev/issue/57522 for more details.
   815  	if wantType {
   816  		check.errorf(e.Sel, NotAType, "%s is not a type", syntax.Expr(e))
   817  		goto Error
   818  	}
   819  
   820  	// Additionally, if x.typ is a pointer type, selecting implicitly dereferences the value, meaning
   821  	// its base type must also be complete.
   822  	if p, ok := x.typ().Underlying().(*Pointer); ok && !check.isComplete(p.base) {
   823  		goto Error
   824  	}
   825  
   826  	obj, index, indirect = lookupFieldOrMethod(x.typ(), x.mode() == variable, check.pkg, sel, false)
   827  	if obj == nil {
   828  		// Don't report another error if the underlying type was invalid (go.dev/issue/49541).
   829  		if !isValid(x.typ().Underlying()) {
   830  			goto Error
   831  		}
   832  
   833  		if index != nil {
   834  			// TODO(gri) should provide actual type where the conflict happens
   835  			check.errorf(e.Sel, AmbiguousSelector, "ambiguous selector %s.%s", x.expr, sel)
   836  			goto Error
   837  		}
   838  
   839  		if indirect {
   840  			if x.mode() == typexpr {
   841  				check.errorf(e.Sel, InvalidMethodExpr, "invalid method expression %s.%s (needs pointer receiver (*%s).%s)", x.typ(), sel, x.typ(), sel)
   842  			} else {
   843  				check.errorf(e.Sel, InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ())
   844  			}
   845  			goto Error
   846  		}
   847  
   848  		var why string
   849  		if isInterfacePtr(x.typ()) {
   850  			why = check.interfacePtrError(x.typ())
   851  		} else {
   852  			alt, _, _ := lookupFieldOrMethod(x.typ(), x.mode() == variable, check.pkg, sel, true)
   853  			why = check.lookupError(x.typ(), sel, alt, false)
   854  		}
   855  		check.errorf(e.Sel, MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why)
   856  		goto Error
   857  	}
   858  	// obj != nil
   859  
   860  	switch obj := obj.(type) {
   861  	case *Var:
   862  		if x.mode() == typexpr {
   863  			check.errorf(e.X, MissingFieldOrMethod, "operand for field selector %s must be value of type %s", sel, x.typ())
   864  			goto Error
   865  		}
   866  
   867  		// field value
   868  		check.recordSelection(e, FieldVal, x.typ(), obj, index, indirect)
   869  		if x.mode() == variable || indirect {
   870  			x.mode_ = variable
   871  		} else {
   872  			x.mode_ = value
   873  		}
   874  		x.typ_ = obj.typ
   875  
   876  	case *Func:
   877  		check.objDecl(obj) // ensure fully set-up signature
   878  		check.addDeclDep(obj)
   879  		// TODO(mark): Assert that sig.rparams is nil here?
   880  
   881  		if x.mode() == typexpr {
   882  			// method expression
   883  			check.recordSelection(e, MethodExpr, x.typ(), obj, index, indirect)
   884  
   885  			sig := obj.typ.(*Signature)
   886  			if sig.recv == nil {
   887  				check.error(e, InvalidDeclCycle, "illegal cycle in method declaration")
   888  				goto Error
   889  			}
   890  
   891  			// The receiver type becomes the type of the first function
   892  			// argument of the method expression's function type.
   893  			var params []*Var
   894  			if sig.params != nil {
   895  				params = sig.params.vars
   896  			}
   897  			// Be consistent about named/unnamed parameters. This is not needed
   898  			// for type-checking, but the newly constructed signature may appear
   899  			// in an error message and then have mixed named/unnamed parameters.
   900  			// (An alternative would be to not print parameter names in errors,
   901  			// but it's useful to see them; this is cheap and method expressions
   902  			// are rare.)
   903  			name := ""
   904  			if len(params) > 0 && params[0].name != "" {
   905  				// name needed
   906  				name = sig.recv.name
   907  				if name == "" {
   908  					name = "_"
   909  				}
   910  			}
   911  			params = append([]*Var{NewParam(sig.recv.pos, sig.recv.pkg, name, x.typ())}, params...)
   912  			x.mode_ = value
   913  			x.typ_ = &Signature{
   914  				tparams:  sig.tparams,
   915  				recvold:  methodExprSentinel,
   916  				params:   NewTuple(params...),
   917  				results:  sig.results,
   918  				variadic: sig.variadic,
   919  			}
   920  		} else {
   921  			// method value
   922  
   923  			// TODO(gri) If we needed to take into account the receiver's
   924  			// addressability, should we report the type &(x.typ) instead?
   925  			check.recordSelection(e, MethodVal, x.typ(), obj, index, indirect)
   926  
   927  			x.mode_ = value
   928  
   929  			// remove/stash receiver
   930  			sig := *obj.typ.(*Signature)
   931  			sig.recvold = sig.recv
   932  			sig.recv = nil
   933  			x.typ_ = &sig
   934  		}
   935  
   936  	default:
   937  		panic("unreachable")
   938  	}
   939  
   940  	// everything went well
   941  	x.expr = e
   942  	return
   943  
   944  Error:
   945  	x.invalidate()
   946  	x.typ_ = Typ[Invalid]
   947  	x.expr = e
   948  }
   949  
   950  // use type-checks each argument.
   951  // Useful to make sure expressions are evaluated
   952  // (and variables are "used") in the presence of
   953  // other errors. Arguments may be nil.
   954  // Reports if all arguments evaluated without error.
   955  func (check *Checker) use(args ...syntax.Expr) bool { return check.useN(args, false) }
   956  
   957  // useLHS is like use, but doesn't "use" top-level identifiers.
   958  // It should be called instead of use if the arguments are
   959  // expressions on the lhs of an assignment.
   960  func (check *Checker) useLHS(args ...syntax.Expr) bool { return check.useN(args, true) }
   961  
   962  func (check *Checker) useN(args []syntax.Expr, lhs bool) bool {
   963  	ok := true
   964  	for _, e := range args {
   965  		if !check.use1(e, lhs) {
   966  			ok = false
   967  		}
   968  	}
   969  	return ok
   970  }
   971  
   972  func (check *Checker) use1(e syntax.Expr, lhs bool) bool {
   973  	var x operand
   974  	x.mode_ = value // anything but invalid
   975  	switch n := syntax.Unparen(e).(type) {
   976  	case nil:
   977  		// nothing to do
   978  	case *syntax.Name:
   979  		// don't report an error evaluating blank
   980  		if n.Value == "_" {
   981  			break
   982  		}
   983  		// If the lhs is an identifier denoting a variable v, this assignment
   984  		// is not a 'use' of v. Remember current value of v.used and restore
   985  		// after evaluating the lhs via check.rawExpr.
   986  		var v *Var
   987  		var v_used bool
   988  		if lhs {
   989  			if obj := check.lookup(n.Value); obj != nil {
   990  				// It's ok to mark non-local variables, but ignore variables
   991  				// from other packages to avoid potential race conditions with
   992  				// dot-imported variables.
   993  				if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg {
   994  					v = w
   995  					v_used = check.usedVars[v]
   996  				}
   997  			}
   998  		}
   999  		check.exprOrType(&x, n, true)
  1000  		if v != nil {
  1001  			check.usedVars[v] = v_used // restore v.used
  1002  		}
  1003  	case *syntax.ListExpr:
  1004  		return check.useN(n.ElemList, lhs)
  1005  	default:
  1006  		check.rawExpr(nil, nil, &x, e, nil, true)
  1007  	}
  1008  	return x.isValid()
  1009  }
  1010  

View as plain text