...

Source file src/go/types/call.go

Documentation: go/types

     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 signature %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, nil, check.context()).(*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, check.context()); 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  	}).describef(atPos(pos), "verify instantiation")
    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  		err := newErrorf(at, _WrongArgCount, "%s arguments in call to %s", qualifier, call.Fun)
   372  		err.errorf(token.NoPos, "have %s", check.typesSummary(operandTypes(args), false))
   373  		err.errorf(token.NoPos, "want %s", check.typesSummary(varTypes(params), sig.variadic))
   374  		check.report(err)
   375  		return
   376  	}
   377  
   378  	// infer type arguments and instantiate signature if necessary
   379  	if sig.TypeParams().Len() > 0 {
   380  		if !check.allowVersion(check.pkg, 1, 18) {
   381  			switch call.Fun.(type) {
   382  			case *ast.IndexExpr, *ast.IndexListExpr:
   383  				ix := typeparams.UnpackIndexExpr(call.Fun)
   384  				check.softErrorf(inNode(call.Fun, ix.Lbrack), _UnsupportedFeature, "function instantiation requires go1.18 or later")
   385  			default:
   386  				check.softErrorf(inNode(call, call.Lparen), _UnsupportedFeature, "implicit function instantiation requires go1.18 or later")
   387  			}
   388  		}
   389  		targs := check.infer(call, sig.TypeParams().list(), targs, sigParams, args)
   390  		if targs == nil {
   391  			return // error already reported
   392  		}
   393  
   394  		// compute result signature
   395  		rsig = check.instantiateSignature(call.Pos(), sig, targs, xlist)
   396  		assert(rsig.TypeParams().Len() == 0) // signature is not generic anymore
   397  		check.recordInstance(call.Fun, targs, rsig)
   398  
   399  		// Optimization: Only if the parameter list was adjusted do we
   400  		// need to compute it from the adjusted list; otherwise we can
   401  		// simply use the result signature's parameter list.
   402  		if adjusted {
   403  			sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(sig.TypeParams().list(), targs), nil, check.context()).(*Tuple)
   404  		} else {
   405  			sigParams = rsig.params
   406  		}
   407  	}
   408  
   409  	// check arguments
   410  	if len(args) > 0 {
   411  		context := check.sprintf("argument to %s", call.Fun)
   412  		for i, a := range args {
   413  			check.assignment(a, sigParams.vars[i].typ, context)
   414  		}
   415  	}
   416  
   417  	return
   418  }
   419  
   420  var cgoPrefixes = [...]string{
   421  	"_Ciconst_",
   422  	"_Cfconst_",
   423  	"_Csconst_",
   424  	"_Ctype_",
   425  	"_Cvar_", // actually a pointer to the var
   426  	"_Cfpvar_fp_",
   427  	"_Cfunc_",
   428  	"_Cmacro_", // function to evaluate the expanded expression
   429  }
   430  
   431  func (check *Checker) selector(x *operand, e *ast.SelectorExpr, def *Named) {
   432  	// these must be declared before the "goto Error" statements
   433  	var (
   434  		obj      Object
   435  		index    []int
   436  		indirect bool
   437  	)
   438  
   439  	sel := e.Sel.Name
   440  	// If the identifier refers to a package, handle everything here
   441  	// so we don't need a "package" mode for operands: package names
   442  	// can only appear in qualified identifiers which are mapped to
   443  	// selector expressions.
   444  	if ident, ok := e.X.(*ast.Ident); ok {
   445  		obj := check.lookup(ident.Name)
   446  		if pname, _ := obj.(*PkgName); pname != nil {
   447  			assert(pname.pkg == check.pkg)
   448  			check.recordUse(ident, pname)
   449  			pname.used = true
   450  			pkg := pname.imported
   451  
   452  			var exp Object
   453  			funcMode := value
   454  			if pkg.cgo {
   455  				// cgo special cases C.malloc: it's
   456  				// rewritten to _CMalloc and does not
   457  				// support two-result calls.
   458  				if sel == "malloc" {
   459  					sel = "_CMalloc"
   460  				} else {
   461  					funcMode = cgofunc
   462  				}
   463  				for _, prefix := range cgoPrefixes {
   464  					// cgo objects are part of the current package (in file
   465  					// _cgo_gotypes.go). Use regular lookup.
   466  					_, exp = check.scope.LookupParent(prefix+sel, check.pos)
   467  					if exp != nil {
   468  						break
   469  					}
   470  				}
   471  				if exp == nil {
   472  					check.errorf(e.Sel, _UndeclaredImportedName, "%s not declared by package C", sel)
   473  					goto Error
   474  				}
   475  				check.objDecl(exp, nil)
   476  			} else {
   477  				exp = pkg.scope.Lookup(sel)
   478  				if exp == nil {
   479  					if !pkg.fake {
   480  						check.errorf(e.Sel, _UndeclaredImportedName, "%s not declared by package %s", sel, pkg.name)
   481  					}
   482  					goto Error
   483  				}
   484  				if !exp.Exported() {
   485  					check.errorf(e.Sel, _UnexportedName, "%s not exported by package %s", sel, pkg.name)
   486  					// ok to continue
   487  				}
   488  			}
   489  			check.recordUse(e.Sel, exp)
   490  
   491  			// Simplified version of the code for *ast.Idents:
   492  			// - imported objects are always fully initialized
   493  			switch exp := exp.(type) {
   494  			case *Const:
   495  				assert(exp.Val() != nil)
   496  				x.mode = constant_
   497  				x.typ = exp.typ
   498  				x.val = exp.val
   499  			case *TypeName:
   500  				x.mode = typexpr
   501  				x.typ = exp.typ
   502  			case *Var:
   503  				x.mode = variable
   504  				x.typ = exp.typ
   505  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
   506  					x.typ = x.typ.(*Pointer).base
   507  				}
   508  			case *Func:
   509  				x.mode = funcMode
   510  				x.typ = exp.typ
   511  				if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
   512  					x.mode = value
   513  					x.typ = x.typ.(*Signature).results.vars[0].typ
   514  				}
   515  			case *Builtin:
   516  				x.mode = builtin
   517  				x.typ = exp.typ
   518  				x.id = exp.id
   519  			default:
   520  				check.dump("%v: unexpected object %v", e.Sel.Pos(), exp)
   521  				unreachable()
   522  			}
   523  			x.expr = e
   524  			return
   525  		}
   526  	}
   527  
   528  	check.exprOrType(x, e.X, false)
   529  	switch x.mode {
   530  	case typexpr:
   531  		// don't crash for "type T T.x" (was issue #51509)
   532  		if def != nil && x.typ == def {
   533  			check.cycleError([]Object{def.obj})
   534  			goto Error
   535  		}
   536  	case builtin:
   537  		// types2 uses the position of '.' for the error
   538  		check.errorf(e.Sel, _UncalledBuiltin, "cannot select on %s", x)
   539  		goto Error
   540  	case invalid:
   541  		goto Error
   542  	}
   543  
   544  	obj, index, indirect = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, sel)
   545  	if obj == nil {
   546  		// Don't report another error if the underlying type was invalid (issue #49541).
   547  		if under(x.typ) == Typ[Invalid] {
   548  			goto Error
   549  		}
   550  
   551  		if index != nil {
   552  			// TODO(gri) should provide actual type where the conflict happens
   553  			check.errorf(e.Sel, _AmbiguousSelector, "ambiguous selector %s.%s", x.expr, sel)
   554  			goto Error
   555  		}
   556  
   557  		if indirect {
   558  			check.errorf(e.Sel, _InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ)
   559  			goto Error
   560  		}
   561  
   562  		var why string
   563  		if isInterfacePtr(x.typ) {
   564  			why = check.interfacePtrError(x.typ)
   565  		} else {
   566  			why = check.sprintf("type %s has no field or method %s", x.typ, sel)
   567  			// Check if capitalization of sel matters and provide better error message in that case.
   568  			// TODO(gri) This code only looks at the first character but LookupFieldOrMethod should
   569  			//           have an (internal) mechanism for case-insensitive lookup that we should use
   570  			//           instead (see types2).
   571  			if len(sel) > 0 {
   572  				var changeCase string
   573  				if r := rune(sel[0]); unicode.IsUpper(r) {
   574  					changeCase = string(unicode.ToLower(r)) + sel[1:]
   575  				} else {
   576  					changeCase = string(unicode.ToUpper(r)) + sel[1:]
   577  				}
   578  				if obj, _, _ = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, changeCase); obj != nil {
   579  					why += ", but does have " + changeCase
   580  				}
   581  			}
   582  		}
   583  		check.errorf(e.Sel, _MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why)
   584  		goto Error
   585  	}
   586  
   587  	// methods may not have a fully set up signature yet
   588  	if m, _ := obj.(*Func); m != nil {
   589  		check.objDecl(m, nil)
   590  	}
   591  
   592  	if x.mode == typexpr {
   593  		// method expression
   594  		m, _ := obj.(*Func)
   595  		if m == nil {
   596  			// TODO(gri) should check if capitalization of sel matters and provide better error message in that case
   597  			check.errorf(e.Sel, _MissingFieldOrMethod, "%s.%s undefined (type %s has no method %s)", x.expr, sel, x.typ, sel)
   598  			goto Error
   599  		}
   600  
   601  		check.recordSelection(e, MethodExpr, x.typ, m, index, indirect)
   602  
   603  		sig := m.typ.(*Signature)
   604  		if sig.recv == nil {
   605  			check.error(e, _InvalidDeclCycle, "illegal cycle in method declaration")
   606  			goto Error
   607  		}
   608  
   609  		// the receiver type becomes the type of the first function
   610  		// argument of the method expression's function type
   611  		var params []*Var
   612  		if sig.params != nil {
   613  			params = sig.params.vars
   614  		}
   615  		// Be consistent about named/unnamed parameters. This is not needed
   616  		// for type-checking, but the newly constructed signature may appear
   617  		// in an error message and then have mixed named/unnamed parameters.
   618  		// (An alternative would be to not print parameter names in errors,
   619  		// but it's useful to see them; this is cheap and method expressions
   620  		// are rare.)
   621  		name := ""
   622  		if len(params) > 0 && params[0].name != "" {
   623  			// name needed
   624  			name = sig.recv.name
   625  			if name == "" {
   626  				name = "_"
   627  			}
   628  		}
   629  		params = append([]*Var{NewVar(sig.recv.pos, sig.recv.pkg, name, x.typ)}, params...)
   630  		x.mode = value
   631  		x.typ = &Signature{
   632  			tparams:  sig.tparams,
   633  			params:   NewTuple(params...),
   634  			results:  sig.results,
   635  			variadic: sig.variadic,
   636  		}
   637  
   638  		check.addDeclDep(m)
   639  
   640  	} else {
   641  		// regular selector
   642  		switch obj := obj.(type) {
   643  		case *Var:
   644  			check.recordSelection(e, FieldVal, x.typ, obj, index, indirect)
   645  			if x.mode == variable || indirect {
   646  				x.mode = variable
   647  			} else {
   648  				x.mode = value
   649  			}
   650  			x.typ = obj.typ
   651  
   652  		case *Func:
   653  			// TODO(gri) If we needed to take into account the receiver's
   654  			// addressability, should we report the type &(x.typ) instead?
   655  			check.recordSelection(e, MethodVal, x.typ, obj, index, indirect)
   656  
   657  			// TODO(gri) The verification pass below is disabled for now because
   658  			//           method sets don't match method lookup in some cases.
   659  			//           For instance, if we made a copy above when creating a
   660  			//           custom method for a parameterized received type, the
   661  			//           method set method doesn't match (no copy there). There
   662  			///          may be other situations.
   663  			disabled := true
   664  			if !disabled && debug {
   665  				// Verify that LookupFieldOrMethod and MethodSet.Lookup agree.
   666  				// TODO(gri) This only works because we call LookupFieldOrMethod
   667  				// _before_ calling NewMethodSet: LookupFieldOrMethod completes
   668  				// any incomplete interfaces so they are available to NewMethodSet
   669  				// (which assumes that interfaces have been completed already).
   670  				typ := x.typ
   671  				if x.mode == variable {
   672  					// If typ is not an (unnamed) pointer or an interface,
   673  					// use *typ instead, because the method set of *typ
   674  					// includes the methods of typ.
   675  					// Variables are addressable, so we can always take their
   676  					// address.
   677  					if _, ok := typ.(*Pointer); !ok && !IsInterface(typ) {
   678  						typ = &Pointer{base: typ}
   679  					}
   680  				}
   681  				// If we created a synthetic pointer type above, we will throw
   682  				// away the method set computed here after use.
   683  				// TODO(gri) Method set computation should probably always compute
   684  				// both, the value and the pointer receiver method set and represent
   685  				// them in a single structure.
   686  				// TODO(gri) Consider also using a method set cache for the lifetime
   687  				// of checker once we rely on MethodSet lookup instead of individual
   688  				// lookup.
   689  				mset := NewMethodSet(typ)
   690  				if m := mset.Lookup(check.pkg, sel); m == nil || m.obj != obj {
   691  					check.dump("%v: (%s).%v -> %s", e.Pos(), typ, obj.name, m)
   692  					check.dump("%s\n", mset)
   693  					// Caution: MethodSets are supposed to be used externally
   694  					// only (after all interface types were completed). It's
   695  					// now possible that we get here incorrectly. Not urgent
   696  					// to fix since we only run this code in debug mode.
   697  					// TODO(gri) fix this eventually.
   698  					panic("method sets and lookup don't agree")
   699  				}
   700  			}
   701  
   702  			x.mode = value
   703  
   704  			// remove receiver
   705  			sig := *obj.typ.(*Signature)
   706  			sig.recv = nil
   707  			x.typ = &sig
   708  
   709  			check.addDeclDep(obj)
   710  
   711  		default:
   712  			unreachable()
   713  		}
   714  	}
   715  
   716  	// everything went well
   717  	x.expr = e
   718  	return
   719  
   720  Error:
   721  	x.mode = invalid
   722  	x.expr = e
   723  }
   724  
   725  // use type-checks each argument.
   726  // Useful to make sure expressions are evaluated
   727  // (and variables are "used") in the presence of other errors.
   728  // The arguments may be nil.
   729  func (check *Checker) use(arg ...ast.Expr) {
   730  	var x operand
   731  	for _, e := range arg {
   732  		// The nil check below is necessary since certain AST fields
   733  		// may legally be nil (e.g., the ast.SliceExpr.High field).
   734  		if e != nil {
   735  			check.rawExpr(&x, e, nil, false)
   736  		}
   737  	}
   738  }
   739  
   740  // useLHS is like use, but doesn't "use" top-level identifiers.
   741  // It should be called instead of use if the arguments are
   742  // expressions on the lhs of an assignment.
   743  // The arguments must not be nil.
   744  func (check *Checker) useLHS(arg ...ast.Expr) {
   745  	var x operand
   746  	for _, e := range arg {
   747  		// If the lhs is an identifier denoting a variable v, this assignment
   748  		// is not a 'use' of v. Remember current value of v.used and restore
   749  		// after evaluating the lhs via check.rawExpr.
   750  		var v *Var
   751  		var v_used bool
   752  		if ident, _ := unparen(e).(*ast.Ident); ident != nil {
   753  			// never type-check the blank name on the lhs
   754  			if ident.Name == "_" {
   755  				continue
   756  			}
   757  			if _, obj := check.scope.LookupParent(ident.Name, token.NoPos); obj != nil {
   758  				// It's ok to mark non-local variables, but ignore variables
   759  				// from other packages to avoid potential race conditions with
   760  				// dot-imported variables.
   761  				if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg {
   762  					v = w
   763  					v_used = v.used
   764  				}
   765  			}
   766  		}
   767  		check.rawExpr(&x, e, nil, false)
   768  		if v != nil {
   769  			v.used = v_used // restore v.used
   770  		}
   771  	}
   772  }
   773  

View as plain text