Source file src/go/types/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 types
     8  
     9  import (
    10  	"go/ast"
    11  	"go/internal/typeparams"
    12  	"go/token"
    13  	"strings"
    14  	"unicode"
    15  )
    16  
    17  // funcInst type-checks a function instantiation inst and returns the result in x.
    18  // The operand x must be the evaluation of inst.X and its type must be a signature.
    19  func (check *Checker) funcInst(x *operand, ix *typeparams.IndexExpr) {
    20  	if !check.allowVersion(check.pkg, 1, 18) {
    21  		check.softErrorf(inNode(ix.Orig, ix.Lbrack), _UnsupportedFeature, "function instantiation requires go1.18 or later")
    22  	}
    23  
    24  	targs := check.typeList(ix.Indices)
    25  	if targs == nil {
    26  		x.mode = invalid
    27  		x.expr = ix.Orig
    28  		return
    29  	}
    30  	assert(len(targs) == len(ix.Indices))
    31  
    32  	// check number of type arguments (got) vs number of type parameters (want)
    33  	sig := x.typ.(*Signature)
    34  	got, want := len(targs), sig.TypeParams().Len()
    35  	if got > want {
    36  		check.errorf(ix.Indices[got-1], _WrongTypeArgCount, "got %d type arguments but want %d", got, want)
    37  		x.mode = invalid
    38  		x.expr = ix.Orig
    39  		return
    40  	}
    41  
    42  	if got < want {
    43  		targs = check.infer(ix.Orig, sig.TypeParams().list(), targs, nil, nil)
    44  		if targs == nil {
    45  			// error was already reported
    46  			x.mode = invalid
    47  			x.expr = ix.Orig
    48  			return
    49  		}
    50  		got = len(targs)
    51  	}
    52  	assert(got == want)
    53  
    54  	// instantiate function signature
    55  	res := check.instantiateSignature(x.Pos(), sig, targs, ix.Indices)
    56  	assert(res.TypeParams().Len() == 0) // signature is not generic anymore
    57  	check.recordInstance(ix.Orig, targs, res)
    58  	x.typ = res
    59  	x.mode = value
    60  	x.expr = ix.Orig
    61  }
    62  
    63  func (check *Checker) instantiateSignature(pos token.Pos, typ *Signature, targs []Type, xlist []ast.Expr) (res *Signature) {
    64  	assert(check != nil)
    65  	assert(len(targs) == typ.TypeParams().Len())
    66  
    67  	if trace {
    68  		check.trace(pos, "-- instantiating %s with %s", typ, targs)
    69  		check.indent++
    70  		defer func() {
    71  			check.indent--
    72  			check.trace(pos, "=> %s (under = %s)", res, res.Underlying())
    73  		}()
    74  	}
    75  
    76  	inst := check.instance(pos, typ, targs, check.bestContext(nil)).(*Signature)
    77  	assert(len(xlist) <= len(targs))
    78  
    79  	// verify instantiation lazily (was issue #50450)
    80  	check.later(func() {
    81  		tparams := typ.TypeParams().list()
    82  		if i, err := check.verify(pos, tparams, targs); err != nil {
    83  			// best position for error reporting
    84  			pos := pos
    85  			if i < len(xlist) {
    86  				pos = xlist[i].Pos()
    87  			}
    88  			check.softErrorf(atPos(pos), _InvalidTypeArg, "%s", err)
    89  		} else {
    90  			check.mono.recordInstance(check.pkg, pos, tparams, targs, xlist)
    91  		}
    92  	})
    93  
    94  	return inst
    95  }
    96  
    97  func (check *Checker) callExpr(x *operand, call *ast.CallExpr) exprKind {
    98  	ix := typeparams.UnpackIndexExpr(call.Fun)
    99  	if ix != nil {
   100  		if check.indexExpr(x, ix) {
   101  			// Delay function instantiation to argument checking,
   102  			// where we combine type and value arguments for type
   103  			// inference.
   104  			assert(x.mode == value)
   105  		} else {
   106  			ix = nil
   107  		}
   108  		x.expr = call.Fun
   109  		check.record(x)
   110  
   111  	} else {
   112  		check.exprOrType(x, call.Fun, true)
   113  	}
   114  	// x.typ may be generic
   115  
   116  	switch x.mode {
   117  	case invalid:
   118  		check.use(call.Args...)
   119  		x.expr = call
   120  		return statement
   121  
   122  	case typexpr:
   123  		// conversion
   124  		check.nonGeneric(x)
   125  		if x.mode == invalid {
   126  			return conversion
   127  		}
   128  		T := x.typ
   129  		x.mode = invalid
   130  		switch n := len(call.Args); n {
   131  		case 0:
   132  			check.errorf(inNode(call, call.Rparen), _WrongArgCount, "missing argument in conversion to %s", T)
   133  		case 1:
   134  			check.expr(x, call.Args[0])
   135  			if x.mode != invalid {
   136  				if call.Ellipsis.IsValid() {
   137  					check.errorf(call.Args[0], _BadDotDotDotSyntax, "invalid use of ... in conversion to %s", T)
   138  					break
   139  				}
   140  				if t, _ := under(T).(*Interface); t != nil && !isTypeParam(T) {
   141  					if !t.IsMethodSet() {
   142  						check.errorf(call, _MisplacedConstraintIface, "cannot use interface %s in conversion (contains specific type constraints or is comparable)", T)
   143  						break
   144  					}
   145  				}
   146  				check.conversion(x, T)
   147  			}
   148  		default:
   149  			check.use(call.Args...)
   150  			check.errorf(call.Args[n-1], _WrongArgCount, "too many arguments in conversion to %s", T)
   151  		}
   152  		x.expr = call
   153  		return conversion
   154  
   155  	case builtin:
   156  		// no need to check for non-genericity here
   157  		id := x.id
   158  		if !check.builtin(x, call, id) {
   159  			x.mode = invalid
   160  		}
   161  		x.expr = call
   162  		// a non-constant result implies a function call
   163  		if x.mode != invalid && x.mode != constant_ {
   164  			check.hasCallOrRecv = true
   165  		}
   166  		return predeclaredFuncs[id].kind
   167  	}
   168  
   169  	// ordinary function/method call
   170  	// signature may be generic
   171  	cgocall := x.mode == cgofunc
   172  
   173  	// a type parameter may be "called" if all types have the same signature
   174  	sig, _ := coreType(x.typ).(*Signature)
   175  	if sig == nil {
   176  		check.invalidOp(x, _InvalidCall, "cannot call non-function %s", x)
   177  		x.mode = invalid
   178  		x.expr = call
   179  		return statement
   180  	}
   181  
   182  	// evaluate type arguments, if any
   183  	var xlist []ast.Expr
   184  	var targs []Type
   185  	if ix != nil {
   186  		xlist = ix.Indices
   187  		targs = check.typeList(xlist)
   188  		if targs == nil {
   189  			check.use(call.Args...)
   190  			x.mode = invalid
   191  			x.expr = call
   192  			return statement
   193  		}
   194  		assert(len(targs) == len(xlist))
   195  
   196  		// check number of type arguments (got) vs number of type parameters (want)
   197  		got, want := len(targs), sig.TypeParams().Len()
   198  		if got > want {
   199  			check.errorf(xlist[want], _WrongTypeArgCount, "got %d type arguments but want %d", got, want)
   200  			check.use(call.Args...)
   201  			x.mode = invalid
   202  			x.expr = call
   203  			return statement
   204  		}
   205  	}
   206  
   207  	// evaluate arguments
   208  	args, _ := check.exprList(call.Args, false)
   209  	isGeneric := sig.TypeParams().Len() > 0
   210  	sig = check.arguments(call, sig, targs, args, xlist)
   211  
   212  	if isGeneric && sig.TypeParams().Len() == 0 {
   213  		// Update the recorded type of call.Fun to its instantiated type.
   214  		check.recordTypeAndValue(call.Fun, value, sig, nil)
   215  	}
   216  
   217  	// determine result
   218  	switch sig.results.Len() {
   219  	case 0:
   220  		x.mode = novalue
   221  	case 1:
   222  		if cgocall {
   223  			x.mode = commaerr
   224  		} else {
   225  			x.mode = value
   226  		}
   227  		x.typ = sig.results.vars[0].typ // unpack tuple
   228  	default:
   229  		x.mode = value
   230  		x.typ = sig.results
   231  	}
   232  	x.expr = call
   233  	check.hasCallOrRecv = true
   234  
   235  	// if type inference failed, a parametrized result must be invalidated
   236  	// (operands cannot have a parametrized type)
   237  	if x.mode == value && sig.TypeParams().Len() > 0 && isParameterized(sig.TypeParams().list(), x.typ) {
   238  		x.mode = invalid
   239  	}
   240  
   241  	return statement
   242  }
   243  
   244  func (check *Checker) exprList(elist []ast.Expr, allowCommaOk bool) (xlist []*operand, commaOk bool) {
   245  	switch len(elist) {
   246  	case 0:
   247  		// nothing to do
   248  
   249  	case 1:
   250  		// single (possibly comma-ok) value, or function returning multiple values
   251  		e := elist[0]
   252  		var x operand
   253  		check.multiExpr(&x, e)
   254  		if t, ok := x.typ.(*Tuple); ok && x.mode != invalid {
   255  			// multiple values
   256  			xlist = make([]*operand, t.Len())
   257  			for i, v := range t.vars {
   258  				xlist[i] = &operand{mode: value, expr: e, typ: v.typ}
   259  			}
   260  			break
   261  		}
   262  
   263  		// exactly one (possibly invalid or comma-ok) value
   264  		xlist = []*operand{&x}
   265  		if allowCommaOk && (x.mode == mapindex || x.mode == commaok || x.mode == commaerr) {
   266  			x2 := &operand{mode: value, expr: e, typ: Typ[UntypedBool]}
   267  			if x.mode == commaerr {
   268  				x2.typ = universeError
   269  			}
   270  			xlist = append(xlist, x2)
   271  			commaOk = true
   272  		}
   273  
   274  	default:
   275  		// multiple (possibly invalid) values
   276  		xlist = make([]*operand, len(elist))
   277  		for i, e := range elist {
   278  			var x operand
   279  			check.expr(&x, e)
   280  			xlist[i] = &x
   281  		}
   282  	}
   283  
   284  	return
   285  }
   286  
   287  // xlist is the list of type argument expressions supplied in the source code.
   288  func (check *Checker) arguments(call *ast.CallExpr, sig *Signature, targs []Type, args []*operand, xlist []ast.Expr) (rsig *Signature) {
   289  	rsig = sig
   290  
   291  	// TODO(gri) try to eliminate this extra verification loop
   292  	for _, a := range args {
   293  		switch a.mode {
   294  		case typexpr:
   295  			check.errorf(a, 0, "%s used as value", a)
   296  			return
   297  		case invalid:
   298  			return
   299  		}
   300  	}
   301  
   302  	// Function call argument/parameter count requirements
   303  	//
   304  	//               | standard call    | dotdotdot call |
   305  	// --------------+------------------+----------------+
   306  	// standard func | nargs == npars   | invalid        |
   307  	// --------------+------------------+----------------+
   308  	// variadic func | nargs >= npars-1 | nargs == npars |
   309  	// --------------+------------------+----------------+
   310  
   311  	nargs := len(args)
   312  	npars := sig.params.Len()
   313  	ddd := call.Ellipsis.IsValid()
   314  
   315  	// set up parameters
   316  	sigParams := sig.params // adjusted for variadic functions (may be nil for empty parameter lists!)
   317  	adjusted := false       // indicates if sigParams is different from t.params
   318  	if sig.variadic {
   319  		if ddd {
   320  			// variadic_func(a, b, c...)
   321  			if len(call.Args) == 1 && nargs > 1 {
   322  				// f()... is not permitted if f() is multi-valued
   323  				check.errorf(inNode(call, call.Ellipsis), _InvalidDotDotDot, "cannot use ... with %d-valued %s", nargs, call.Args[0])
   324  				return
   325  			}
   326  		} else {
   327  			// variadic_func(a, b, c)
   328  			if nargs >= npars-1 {
   329  				// Create custom parameters for arguments: keep
   330  				// the first npars-1 parameters and add one for
   331  				// each argument mapping to the ... parameter.
   332  				vars := make([]*Var, npars-1) // npars > 0 for variadic functions
   333  				copy(vars, sig.params.vars)
   334  				last := sig.params.vars[npars-1]
   335  				typ := last.typ.(*Slice).elem
   336  				for len(vars) < nargs {
   337  					vars = append(vars, NewParam(last.pos, last.pkg, last.name, typ))
   338  				}
   339  				sigParams = NewTuple(vars...) // possibly nil!
   340  				adjusted = true
   341  				npars = nargs
   342  			} else {
   343  				// nargs < npars-1
   344  				npars-- // for correct error message below
   345  			}
   346  		}
   347  	} else {
   348  		if ddd {
   349  			// standard_func(a, b, c...)
   350  			check.errorf(inNode(call, call.Ellipsis), _NonVariadicDotDotDot, "cannot use ... in call to non-variadic %s", call.Fun)
   351  			return
   352  		}
   353  		// standard_func(a, b, c)
   354  	}
   355  
   356  	// check argument count
   357  	if nargs != npars {
   358  		var at positioner = call
   359  		qualifier := "not enough"
   360  		if nargs > npars {
   361  			at = args[npars].expr // report at first extra argument
   362  			qualifier = "too many"
   363  		} else {
   364  			at = atPos(call.Rparen) // report at closing )
   365  		}
   366  		// take care of empty parameter lists represented by nil tuples
   367  		var params []*Var
   368  		if sig.params != nil {
   369  			params = sig.params.vars
   370  		}
   371  		check.errorf(at, _WrongArgCount, "%s arguments in call to %s\n\thave %s\n\twant %s",
   372  			qualifier, call.Fun,
   373  			check.typesSummary(operandTypes(args), false),
   374  			check.typesSummary(varTypes(params), sig.variadic),
   375  		)
   376  		return
   377  	}
   378  
   379  	// infer type arguments and instantiate signature if necessary
   380  	if sig.TypeParams().Len() > 0 {
   381  		if !check.allowVersion(check.pkg, 1, 18) {
   382  			switch call.Fun.(type) {
   383  			case *ast.IndexExpr, *ast.IndexListExpr:
   384  				ix := typeparams.UnpackIndexExpr(call.Fun)
   385  				check.softErrorf(inNode(call.Fun, ix.Lbrack), _UnsupportedFeature, "function instantiation requires go1.18 or later")
   386  			default:
   387  				check.softErrorf(inNode(call, call.Lparen), _UnsupportedFeature, "implicit function instantiation requires go1.18 or later")
   388  			}
   389  		}
   390  		targs := check.infer(call, sig.TypeParams().list(), targs, sigParams, args)
   391  		if targs == nil {
   392  			return // error already reported
   393  		}
   394  
   395  		// compute result signature
   396  		rsig = check.instantiateSignature(call.Pos(), sig, targs, xlist)
   397  		assert(rsig.TypeParams().Len() == 0) // signature is not generic anymore
   398  		check.recordInstance(call.Fun, targs, rsig)
   399  
   400  		// Optimization: Only if the parameter list was adjusted do we
   401  		// need to compute it from the adjusted list; otherwise we can
   402  		// simply use the result signature's parameter list.
   403  		if adjusted {
   404  			sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(sig.TypeParams().list(), targs), nil).(*Tuple)
   405  		} else {
   406  			sigParams = rsig.params
   407  		}
   408  	}
   409  
   410  	// check arguments
   411  	if len(args) > 0 {
   412  		context := check.sprintf("argument to %s", call.Fun)
   413  		for i, a := range args {
   414  			check.assignment(a, sigParams.vars[i].typ, context)
   415  		}
   416  	}
   417  
   418  	return
   419  }
   420  
   421  var cgoPrefixes = [...]string{
   422  	"_Ciconst_",
   423  	"_Cfconst_",
   424  	"_Csconst_",
   425  	"_Ctype_",
   426  	"_Cvar_", // actually a pointer to the var
   427  	"_Cfpvar_fp_",
   428  	"_Cfunc_",
   429  	"_Cmacro_", // function to evaluate the expanded expression
   430  }
   431  
   432  func (check *Checker) selector(x *operand, e *ast.SelectorExpr, def *Named) {
   433  	// these must be declared before the "goto Error" statements
   434  	var (
   435  		obj      Object
   436  		index    []int
   437  		indirect bool
   438  	)
   439  
   440  	sel := e.Sel.Name
   441  	// If the identifier refers to a package, handle everything here
   442  	// so we don't need a "package" mode for operands: package names
   443  	// can only appear in qualified identifiers which are mapped to
   444  	// selector expressions.
   445  	if ident, ok := e.X.(*ast.Ident); ok {
   446  		obj := check.lookup(ident.Name)
   447  		if pname, _ := obj.(*PkgName); pname != nil {
   448  			assert(pname.pkg == check.pkg)
   449  			check.recordUse(ident, pname)
   450  			pname.used = true
   451  			pkg := pname.imported
   452  
   453  			var exp Object
   454  			funcMode := value
   455  			if pkg.cgo {
   456  				// cgo special cases C.malloc: it's
   457  				// rewritten to _CMalloc and does not
   458  				// support two-result calls.
   459  				if sel == "malloc" {
   460  					sel = "_CMalloc"
   461  				} else {
   462  					funcMode = cgofunc
   463  				}
   464  				for _, prefix := range cgoPrefixes {
   465  					// cgo objects are part of the current package (in file
   466  					// _cgo_gotypes.go). Use regular lookup.
   467  					_, exp = check.scope.LookupParent(prefix+sel, check.pos)
   468  					if exp != nil {
   469  						break
   470  					}
   471  				}
   472  				if exp == nil {
   473  					check.errorf(e.Sel, _UndeclaredImportedName, "%s not declared by package C", sel)
   474  					goto Error
   475  				}
   476  				check.objDecl(exp, nil)
   477  			} else {
   478  				exp = pkg.scope.Lookup(sel)
   479  				if exp == nil {
   480  					if !pkg.fake {
   481  						check.errorf(e.Sel, _UndeclaredImportedName, "%s not declared by package %s", sel, pkg.name)
   482  					}
   483  					goto Error
   484  				}
   485  				if !exp.Exported() {
   486  					check.errorf(e.Sel, _UnexportedName, "%s not exported by package %s", sel, pkg.name)
   487  					// ok to continue
   488  				}
   489  			}
   490  			check.recordUse(e.Sel, exp)
   491  
   492  			// Simplified version of the code for *ast.Idents:
   493  			// - imported objects are always fully initialized
   494  			switch exp := exp.(type) {
   495  			case *Const:
   496  				assert(exp.Val() != nil)
   497  				x.mode = constant_
   498  				x.typ = exp.typ
   499  				x.val = exp.val
   500  			case *TypeName:
   501  				x.mode = typexpr
   502  				x.typ = exp.typ
   503  			case *Var:
   504  				x.mode = variable
   505  				x.typ = exp.typ
   506  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
   507  					x.typ = x.typ.(*Pointer).base
   508  				}
   509  			case *Func:
   510  				x.mode = funcMode
   511  				x.typ = exp.typ
   512  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
   513  					x.mode = value
   514  					x.typ = x.typ.(*Signature).results.vars[0].typ
   515  				}
   516  			case *Builtin:
   517  				x.mode = builtin
   518  				x.typ = exp.typ
   519  				x.id = exp.id
   520  			default:
   521  				check.dump("%v: unexpected object %v", e.Sel.Pos(), exp)
   522  				unreachable()
   523  			}
   524  			x.expr = e
   525  			return
   526  		}
   527  	}
   528  
   529  	check.exprOrType(x, e.X, false)
   530  	switch x.mode {
   531  	case typexpr:
   532  		// don't crash for "type T T.x" (was issue #51509)
   533  		if def != nil && x.typ == def {
   534  			check.cycleError([]Object{def.obj})
   535  			goto Error
   536  		}
   537  	case builtin:
   538  		// types2 uses the position of '.' for the error
   539  		check.errorf(e.Sel, _UncalledBuiltin, "cannot select on %s", x)
   540  		goto Error
   541  	case invalid:
   542  		goto Error
   543  	}
   544  
   545  	obj, index, indirect = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, sel)
   546  	if obj == nil {
   547  		// Don't report another error if the underlying type was invalid (issue #49541).
   548  		if under(x.typ) == Typ[Invalid] {
   549  			goto Error
   550  		}
   551  
   552  		if index != nil {
   553  			// TODO(gri) should provide actual type where the conflict happens
   554  			check.errorf(e.Sel, _AmbiguousSelector, "ambiguous selector %s.%s", x.expr, sel)
   555  			goto Error
   556  		}
   557  
   558  		if indirect {
   559  			check.errorf(e.Sel, _InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ)
   560  			goto Error
   561  		}
   562  
   563  		var why string
   564  		if isInterfacePtr(x.typ) {
   565  			why = check.interfacePtrError(x.typ)
   566  		} else {
   567  			why = check.sprintf("type %s has no field or method %s", x.typ, sel)
   568  			// Check if capitalization of sel matters and provide better error message in that case.
   569  			// TODO(gri) This code only looks at the first character but LookupFieldOrMethod should
   570  			//           have an (internal) mechanism for case-insensitive lookup that we should use
   571  			//           instead (see types2).
   572  			if len(sel) > 0 {
   573  				var changeCase string
   574  				if r := rune(sel[0]); unicode.IsUpper(r) {
   575  					changeCase = string(unicode.ToLower(r)) + sel[1:]
   576  				} else {
   577  					changeCase = string(unicode.ToUpper(r)) + sel[1:]
   578  				}
   579  				if obj, _, _ = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, changeCase); obj != nil {
   580  					why += ", but does have " + changeCase
   581  				}
   582  			}
   583  		}
   584  		check.errorf(e.Sel, _MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why)
   585  		goto Error
   586  	}
   587  
   588  	// methods may not have a fully set up signature yet
   589  	if m, _ := obj.(*Func); m != nil {
   590  		check.objDecl(m, nil)
   591  	}
   592  
   593  	if x.mode == typexpr {
   594  		// method expression
   595  		m, _ := obj.(*Func)
   596  		if m == nil {
   597  			// TODO(gri) should check if capitalization of sel matters and provide better error message in that case
   598  			check.errorf(e.Sel, _MissingFieldOrMethod, "%s.%s undefined (type %s has no method %s)", x.expr, sel, x.typ, sel)
   599  			goto Error
   600  		}
   601  
   602  		check.recordSelection(e, MethodExpr, x.typ, m, index, indirect)
   603  
   604  		sig := m.typ.(*Signature)
   605  		if sig.recv == nil {
   606  			check.error(e, _InvalidDeclCycle, "illegal cycle in method declaration")
   607  			goto Error
   608  		}
   609  
   610  		// the receiver type becomes the type of the first function
   611  		// argument of the method expression's function type
   612  		var params []*Var
   613  		if sig.params != nil {
   614  			params = sig.params.vars
   615  		}
   616  		// Be consistent about named/unnamed parameters. This is not needed
   617  		// for type-checking, but the newly constructed signature may appear
   618  		// in an error message and then have mixed named/unnamed parameters.
   619  		// (An alternative would be to not print parameter names in errors,
   620  		// but it's useful to see them; this is cheap and method expressions
   621  		// are rare.)
   622  		name := ""
   623  		if len(params) > 0 && params[0].name != "" {
   624  			// name needed
   625  			name = sig.recv.name
   626  			if name == "" {
   627  				name = "_"
   628  			}
   629  		}
   630  		params = append([]*Var{NewVar(sig.recv.pos, sig.recv.pkg, name, x.typ)}, params...)
   631  		x.mode = value
   632  		x.typ = &Signature{
   633  			tparams:  sig.tparams,
   634  			params:   NewTuple(params...),
   635  			results:  sig.results,
   636  			variadic: sig.variadic,
   637  		}
   638  
   639  		check.addDeclDep(m)
   640  
   641  	} else {
   642  		// regular selector
   643  		switch obj := obj.(type) {
   644  		case *Var:
   645  			check.recordSelection(e, FieldVal, x.typ, obj, index, indirect)
   646  			if x.mode == variable || indirect {
   647  				x.mode = variable
   648  			} else {
   649  				x.mode = value
   650  			}
   651  			x.typ = obj.typ
   652  
   653  		case *Func:
   654  			// TODO(gri) If we needed to take into account the receiver's
   655  			// addressability, should we report the type &(x.typ) instead?
   656  			check.recordSelection(e, MethodVal, x.typ, obj, index, indirect)
   657  
   658  			// TODO(gri) The verification pass below is disabled for now because
   659  			//           method sets don't match method lookup in some cases.
   660  			//           For instance, if we made a copy above when creating a
   661  			//           custom method for a parameterized received type, the
   662  			//           method set method doesn't match (no copy there). There
   663  			///          may be other situations.
   664  			disabled := true
   665  			if !disabled && debug {
   666  				// Verify that LookupFieldOrMethod and MethodSet.Lookup agree.
   667  				// TODO(gri) This only works because we call LookupFieldOrMethod
   668  				// _before_ calling NewMethodSet: LookupFieldOrMethod completes
   669  				// any incomplete interfaces so they are available to NewMethodSet
   670  				// (which assumes that interfaces have been completed already).
   671  				typ := x.typ
   672  				if x.mode == variable {
   673  					// If typ is not an (unnamed) pointer or an interface,
   674  					// use *typ instead, because the method set of *typ
   675  					// includes the methods of typ.
   676  					// Variables are addressable, so we can always take their
   677  					// address.
   678  					if _, ok := typ.(*Pointer); !ok && !IsInterface(typ) {
   679  						typ = &Pointer{base: typ}
   680  					}
   681  				}
   682  				// If we created a synthetic pointer type above, we will throw
   683  				// away the method set computed here after use.
   684  				// TODO(gri) Method set computation should probably always compute
   685  				// both, the value and the pointer receiver method set and represent
   686  				// them in a single structure.
   687  				// TODO(gri) Consider also using a method set cache for the lifetime
   688  				// of checker once we rely on MethodSet lookup instead of individual
   689  				// lookup.
   690  				mset := NewMethodSet(typ)
   691  				if m := mset.Lookup(check.pkg, sel); m == nil || m.obj != obj {
   692  					check.dump("%v: (%s).%v -> %s", e.Pos(), typ, obj.name, m)
   693  					check.dump("%s\n", mset)
   694  					// Caution: MethodSets are supposed to be used externally
   695  					// only (after all interface types were completed). It's
   696  					// now possible that we get here incorrectly. Not urgent
   697  					// to fix since we only run this code in debug mode.
   698  					// TODO(gri) fix this eventually.
   699  					panic("method sets and lookup don't agree")
   700  				}
   701  			}
   702  
   703  			x.mode = value
   704  
   705  			// remove receiver
   706  			sig := *obj.typ.(*Signature)
   707  			sig.recv = nil
   708  			x.typ = &sig
   709  
   710  			check.addDeclDep(obj)
   711  
   712  		default:
   713  			unreachable()
   714  		}
   715  	}
   716  
   717  	// everything went well
   718  	x.expr = e
   719  	return
   720  
   721  Error:
   722  	x.mode = invalid
   723  	x.expr = e
   724  }
   725  
   726  // use type-checks each argument.
   727  // Useful to make sure expressions are evaluated
   728  // (and variables are "used") in the presence of other errors.
   729  // The arguments may be nil.
   730  func (check *Checker) use(arg ...ast.Expr) {
   731  	var x operand
   732  	for _, e := range arg {
   733  		// The nil check below is necessary since certain AST fields
   734  		// may legally be nil (e.g., the ast.SliceExpr.High field).
   735  		if e != nil {
   736  			check.rawExpr(&x, e, nil, false)
   737  		}
   738  	}
   739  }
   740  
   741  // useLHS is like use, but doesn't "use" top-level identifiers.
   742  // It should be called instead of use if the arguments are
   743  // expressions on the lhs of an assignment.
   744  // The arguments must not be nil.
   745  func (check *Checker) useLHS(arg ...ast.Expr) {
   746  	var x operand
   747  	for _, e := range arg {
   748  		// If the lhs is an identifier denoting a variable v, this assignment
   749  		// is not a 'use' of v. Remember current value of v.used and restore
   750  		// after evaluating the lhs via check.rawExpr.
   751  		var v *Var
   752  		var v_used bool
   753  		if ident, _ := unparen(e).(*ast.Ident); ident != nil {
   754  			// never type-check the blank name on the lhs
   755  			if ident.Name == "_" {
   756  				continue
   757  			}
   758  			if _, obj := check.scope.LookupParent(ident.Name, token.NoPos); obj != nil {
   759  				// It's ok to mark non-local variables, but ignore variables
   760  				// from other packages to avoid potential race conditions with
   761  				// dot-imported variables.
   762  				if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg {
   763  					v = w
   764  					v_used = v.used
   765  				}
   766  			}
   767  		}
   768  		check.rawExpr(&x, e, nil, false)
   769  		if v != nil {
   770  			v.used = v_used // restore v.used
   771  		}
   772  	}
   773  }
   774  

View as plain text