...
Run Format

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/token"
    12  )
    13  
    14  func (check *Checker) call(x *operand, e *ast.CallExpr) exprKind {
    15  	check.exprOrType(x, e.Fun)
    16  
    17  	switch x.mode {
    18  	case invalid:
    19  		check.use(e.Args...)
    20  		x.mode = invalid
    21  		x.expr = e
    22  		return statement
    23  
    24  	case typexpr:
    25  		// conversion
    26  		T := x.typ
    27  		x.mode = invalid
    28  		switch n := len(e.Args); n {
    29  		case 0:
    30  			check.errorf(e.Rparen, "missing argument in conversion to %s", T)
    31  		case 1:
    32  			check.expr(x, e.Args[0])
    33  			if x.mode != invalid {
    34  				check.conversion(x, T)
    35  			}
    36  		default:
    37  			check.use(e.Args...)
    38  			check.errorf(e.Args[n-1].Pos(), "too many arguments in conversion to %s", T)
    39  		}
    40  		x.expr = e
    41  		return conversion
    42  
    43  	case builtin:
    44  		id := x.id
    45  		if !check.builtin(x, e, id) {
    46  			x.mode = invalid
    47  		}
    48  		x.expr = e
    49  		// a non-constant result implies a function call
    50  		if x.mode != invalid && x.mode != constant_ {
    51  			check.hasCallOrRecv = true
    52  		}
    53  		return predeclaredFuncs[id].kind
    54  
    55  	default:
    56  		// function/method call
    57  		sig, _ := x.typ.Underlying().(*Signature)
    58  		if sig == nil {
    59  			check.invalidOp(x.pos(), "cannot call non-function %s", x)
    60  			x.mode = invalid
    61  			x.expr = e
    62  			return statement
    63  		}
    64  
    65  		arg, n, _ := unpack(func(x *operand, i int) { check.multiExpr(x, e.Args[i]) }, len(e.Args), false)
    66  		if arg != nil {
    67  			check.arguments(x, e, sig, arg, n)
    68  		} else {
    69  			x.mode = invalid
    70  		}
    71  
    72  		// determine result
    73  		switch sig.results.Len() {
    74  		case 0:
    75  			x.mode = novalue
    76  		case 1:
    77  			x.mode = value
    78  			x.typ = sig.results.vars[0].typ // unpack tuple
    79  		default:
    80  			x.mode = value
    81  			x.typ = sig.results
    82  		}
    83  
    84  		x.expr = e
    85  		check.hasCallOrRecv = true
    86  
    87  		return statement
    88  	}
    89  }
    90  
    91  // use type-checks each argument.
    92  // Useful to make sure expressions are evaluated
    93  // (and variables are "used") in the presence of other errors.
    94  // The arguments may be nil.
    95  func (check *Checker) use(arg ...ast.Expr) {
    96  	var x operand
    97  	for _, e := range arg {
    98  		// The nil check below is necessary since certain AST fields
    99  		// may legally be nil (e.g., the ast.SliceExpr.High field).
   100  		if e != nil {
   101  			check.rawExpr(&x, e, nil)
   102  		}
   103  	}
   104  }
   105  
   106  // useLHS is like use, but doesn't "use" top-level identifiers.
   107  // It should be called instead of use if the arguments are
   108  // expressions on the lhs of an assignment.
   109  // The arguments must not be nil.
   110  func (check *Checker) useLHS(arg ...ast.Expr) {
   111  	var x operand
   112  	for _, e := range arg {
   113  		// If the lhs is an identifier denoting a variable v, this assignment
   114  		// is not a 'use' of v. Remember current value of v.used and restore
   115  		// after evaluating the lhs via check.rawExpr.
   116  		var v *Var
   117  		var v_used bool
   118  		if ident, _ := unparen(e).(*ast.Ident); ident != nil {
   119  			// never type-check the blank name on the lhs
   120  			if ident.Name == "_" {
   121  				continue
   122  			}
   123  			if _, obj := check.scope.LookupParent(ident.Name, token.NoPos); obj != nil {
   124  				// It's ok to mark non-local variables, but ignore variables
   125  				// from other packages to avoid potential race conditions with
   126  				// dot-imported variables.
   127  				if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg {
   128  					v = w
   129  					v_used = v.used
   130  				}
   131  			}
   132  		}
   133  		check.rawExpr(&x, e, nil)
   134  		if v != nil {
   135  			v.used = v_used // restore v.used
   136  		}
   137  	}
   138  }
   139  
   140  // useGetter is like use, but takes a getter instead of a list of expressions.
   141  // It should be called instead of use if a getter is present to avoid repeated
   142  // evaluation of the first argument (since the getter was likely obtained via
   143  // unpack, which may have evaluated the first argument already).
   144  func (check *Checker) useGetter(get getter, n int) {
   145  	var x operand
   146  	for i := 0; i < n; i++ {
   147  		get(&x, i)
   148  	}
   149  }
   150  
   151  // A getter sets x as the i'th operand, where 0 <= i < n and n is the total
   152  // number of operands (context-specific, and maintained elsewhere). A getter
   153  // type-checks the i'th operand; the details of the actual check are getter-
   154  // specific.
   155  type getter func(x *operand, i int)
   156  
   157  // unpack takes a getter get and a number of operands n. If n == 1, unpack
   158  // calls the incoming getter for the first operand. If that operand is
   159  // invalid, unpack returns (nil, 0, false). Otherwise, if that operand is a
   160  // function call, or a comma-ok expression and allowCommaOk is set, the result
   161  // is a new getter and operand count providing access to the function results,
   162  // or comma-ok values, respectively. The third result value reports if it
   163  // is indeed the comma-ok case. In all other cases, the incoming getter and
   164  // operand count are returned unchanged, and the third result value is false.
   165  //
   166  // In other words, if there's exactly one operand that - after type-checking
   167  // by calling get - stands for multiple operands, the resulting getter provides
   168  // access to those operands instead.
   169  //
   170  // If the returned getter is called at most once for a given operand index i
   171  // (including i == 0), that operand is guaranteed to cause only one call of
   172  // the incoming getter with that i.
   173  //
   174  func unpack(get getter, n int, allowCommaOk bool) (getter, int, bool) {
   175  	if n != 1 {
   176  		// zero or multiple values
   177  		return get, n, false
   178  	}
   179  	// possibly result of an n-valued function call or comma,ok value
   180  	var x0 operand
   181  	get(&x0, 0)
   182  	if x0.mode == invalid {
   183  		return nil, 0, false
   184  	}
   185  
   186  	if t, ok := x0.typ.(*Tuple); ok {
   187  		// result of an n-valued function call
   188  		return func(x *operand, i int) {
   189  			x.mode = value
   190  			x.expr = x0.expr
   191  			x.typ = t.At(i).typ
   192  		}, t.Len(), false
   193  	}
   194  
   195  	if x0.mode == mapindex || x0.mode == commaok {
   196  		// comma-ok value
   197  		if allowCommaOk {
   198  			a := [2]Type{x0.typ, Typ[UntypedBool]}
   199  			return func(x *operand, i int) {
   200  				x.mode = value
   201  				x.expr = x0.expr
   202  				x.typ = a[i]
   203  			}, 2, true
   204  		}
   205  		x0.mode = value
   206  	}
   207  
   208  	// single value
   209  	return func(x *operand, i int) {
   210  		if i != 0 {
   211  			unreachable()
   212  		}
   213  		*x = x0
   214  	}, 1, false
   215  }
   216  
   217  // arguments checks argument passing for the call with the given signature.
   218  // The arg function provides the operand for the i'th argument.
   219  func (check *Checker) arguments(x *operand, call *ast.CallExpr, sig *Signature, arg getter, n int) {
   220  	if call.Ellipsis.IsValid() {
   221  		// last argument is of the form x...
   222  		if !sig.variadic {
   223  			check.errorf(call.Ellipsis, "cannot use ... in call to non-variadic %s", call.Fun)
   224  			check.useGetter(arg, n)
   225  			return
   226  		}
   227  		if len(call.Args) == 1 && n > 1 {
   228  			// f()... is not permitted if f() is multi-valued
   229  			check.errorf(call.Ellipsis, "cannot use ... with %d-valued %s", n, call.Args[0])
   230  			check.useGetter(arg, n)
   231  			return
   232  		}
   233  	}
   234  
   235  	// evaluate arguments
   236  	for i := 0; i < n; i++ {
   237  		arg(x, i)
   238  		if x.mode != invalid {
   239  			var ellipsis token.Pos
   240  			if i == n-1 && call.Ellipsis.IsValid() {
   241  				ellipsis = call.Ellipsis
   242  			}
   243  			check.argument(call.Fun, sig, i, x, ellipsis)
   244  		}
   245  	}
   246  
   247  	// check argument count
   248  	if sig.variadic {
   249  		// a variadic function accepts an "empty"
   250  		// last argument: count one extra
   251  		n++
   252  	}
   253  	if n < sig.params.Len() {
   254  		check.errorf(call.Rparen, "too few arguments in call to %s", call.Fun)
   255  		// ok to continue
   256  	}
   257  }
   258  
   259  // argument checks passing of argument x to the i'th parameter of the given signature.
   260  // If ellipsis is valid, the argument is followed by ... at that position in the call.
   261  func (check *Checker) argument(fun ast.Expr, sig *Signature, i int, x *operand, ellipsis token.Pos) {
   262  	check.singleValue(x)
   263  	if x.mode == invalid {
   264  		return
   265  	}
   266  
   267  	n := sig.params.Len()
   268  
   269  	// determine parameter type
   270  	var typ Type
   271  	switch {
   272  	case i < n:
   273  		typ = sig.params.vars[i].typ
   274  	case sig.variadic:
   275  		typ = sig.params.vars[n-1].typ
   276  		if debug {
   277  			if _, ok := typ.(*Slice); !ok {
   278  				check.dump("%v: expected unnamed slice type, got %s", sig.params.vars[n-1].Pos(), typ)
   279  			}
   280  		}
   281  	default:
   282  		check.errorf(x.pos(), "too many arguments")
   283  		return
   284  	}
   285  
   286  	if ellipsis.IsValid() {
   287  		// argument is of the form x... and x is single-valued
   288  		if i != n-1 {
   289  			check.errorf(ellipsis, "can only use ... with matching parameter")
   290  			return
   291  		}
   292  		if _, ok := x.typ.Underlying().(*Slice); !ok && x.typ != Typ[UntypedNil] { // see issue #18268
   293  			check.errorf(x.pos(), "cannot use %s as parameter of type %s", x, typ)
   294  			return
   295  		}
   296  	} else if sig.variadic && i >= n-1 {
   297  		// use the variadic parameter slice's element type
   298  		typ = typ.(*Slice).elem
   299  	}
   300  
   301  	check.assignment(x, typ, check.sprintf("argument to %s", fun))
   302  }
   303  
   304  func (check *Checker) selector(x *operand, e *ast.SelectorExpr) {
   305  	// these must be declared before the "goto Error" statements
   306  	var (
   307  		obj      Object
   308  		index    []int
   309  		indirect bool
   310  	)
   311  
   312  	sel := e.Sel.Name
   313  	// If the identifier refers to a package, handle everything here
   314  	// so we don't need a "package" mode for operands: package names
   315  	// can only appear in qualified identifiers which are mapped to
   316  	// selector expressions.
   317  	if ident, ok := e.X.(*ast.Ident); ok {
   318  		obj := check.lookup(ident.Name)
   319  		if pname, _ := obj.(*PkgName); pname != nil {
   320  			assert(pname.pkg == check.pkg)
   321  			check.recordUse(ident, pname)
   322  			pname.used = true
   323  			pkg := pname.imported
   324  			exp := pkg.scope.Lookup(sel)
   325  			if exp == nil {
   326  				if !pkg.fake {
   327  					check.errorf(e.Sel.Pos(), "%s not declared by package %s", sel, pkg.name)
   328  				}
   329  				goto Error
   330  			}
   331  			if !exp.Exported() {
   332  				check.errorf(e.Sel.Pos(), "%s not exported by package %s", sel, pkg.name)
   333  				// ok to continue
   334  			}
   335  			check.recordUse(e.Sel, exp)
   336  
   337  			// Simplified version of the code for *ast.Idents:
   338  			// - imported objects are always fully initialized
   339  			switch exp := exp.(type) {
   340  			case *Const:
   341  				assert(exp.Val() != nil)
   342  				x.mode = constant_
   343  				x.typ = exp.typ
   344  				x.val = exp.val
   345  			case *TypeName:
   346  				x.mode = typexpr
   347  				x.typ = exp.typ
   348  			case *Var:
   349  				x.mode = variable
   350  				x.typ = exp.typ
   351  			case *Func:
   352  				x.mode = value
   353  				x.typ = exp.typ
   354  			case *Builtin:
   355  				x.mode = builtin
   356  				x.typ = exp.typ
   357  				x.id = exp.id
   358  			default:
   359  				check.dump("unexpected object %v", exp)
   360  				unreachable()
   361  			}
   362  			x.expr = e
   363  			return
   364  		}
   365  	}
   366  
   367  	check.exprOrType(x, e.X)
   368  	if x.mode == invalid {
   369  		goto Error
   370  	}
   371  
   372  	obj, index, indirect = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, sel)
   373  	if obj == nil {
   374  		switch {
   375  		case index != nil:
   376  			// TODO(gri) should provide actual type where the conflict happens
   377  			check.invalidOp(e.Sel.Pos(), "ambiguous selector %s", sel)
   378  		case indirect:
   379  			check.invalidOp(e.Sel.Pos(), "%s is not in method set of %s", sel, x.typ)
   380  		default:
   381  			check.invalidOp(e.Sel.Pos(), "%s has no field or method %s", x, sel)
   382  		}
   383  		goto Error
   384  	}
   385  
   386  	if x.mode == typexpr {
   387  		// method expression
   388  		m, _ := obj.(*Func)
   389  		if m == nil {
   390  			check.invalidOp(e.Sel.Pos(), "%s has no method %s", x, sel)
   391  			goto Error
   392  		}
   393  
   394  		check.recordSelection(e, MethodExpr, x.typ, m, index, indirect)
   395  
   396  		// the receiver type becomes the type of the first function
   397  		// argument of the method expression's function type
   398  		var params []*Var
   399  		sig := m.typ.(*Signature)
   400  		if sig.params != nil {
   401  			params = sig.params.vars
   402  		}
   403  		x.mode = value
   404  		x.typ = &Signature{
   405  			params:   NewTuple(append([]*Var{NewVar(token.NoPos, check.pkg, "", x.typ)}, params...)...),
   406  			results:  sig.results,
   407  			variadic: sig.variadic,
   408  		}
   409  
   410  		check.addDeclDep(m)
   411  
   412  	} else {
   413  		// regular selector
   414  		switch obj := obj.(type) {
   415  		case *Var:
   416  			check.recordSelection(e, FieldVal, x.typ, obj, index, indirect)
   417  			if x.mode == variable || indirect {
   418  				x.mode = variable
   419  			} else {
   420  				x.mode = value
   421  			}
   422  			x.typ = obj.typ
   423  
   424  		case *Func:
   425  			// TODO(gri) If we needed to take into account the receiver's
   426  			// addressability, should we report the type &(x.typ) instead?
   427  			check.recordSelection(e, MethodVal, x.typ, obj, index, indirect)
   428  
   429  			if debug {
   430  				// Verify that LookupFieldOrMethod and MethodSet.Lookup agree.
   431  				typ := x.typ
   432  				if x.mode == variable {
   433  					// If typ is not an (unnamed) pointer or an interface,
   434  					// use *typ instead, because the method set of *typ
   435  					// includes the methods of typ.
   436  					// Variables are addressable, so we can always take their
   437  					// address.
   438  					if _, ok := typ.(*Pointer); !ok && !IsInterface(typ) {
   439  						typ = &Pointer{base: typ}
   440  					}
   441  				}
   442  				// If we created a synthetic pointer type above, we will throw
   443  				// away the method set computed here after use.
   444  				// TODO(gri) Method set computation should probably always compute
   445  				// both, the value and the pointer receiver method set and represent
   446  				// them in a single structure.
   447  				// TODO(gri) Consider also using a method set cache for the lifetime
   448  				// of checker once we rely on MethodSet lookup instead of individual
   449  				// lookup.
   450  				mset := NewMethodSet(typ)
   451  				if m := mset.Lookup(check.pkg, sel); m == nil || m.obj != obj {
   452  					check.dump("%v: (%s).%v -> %s", e.Pos(), typ, obj.name, m)
   453  					check.dump("%s\n", mset)
   454  					panic("method sets and lookup don't agree")
   455  				}
   456  			}
   457  
   458  			x.mode = value
   459  
   460  			// remove receiver
   461  			sig := *obj.typ.(*Signature)
   462  			sig.recv = nil
   463  			x.typ = &sig
   464  
   465  			check.addDeclDep(obj)
   466  
   467  		default:
   468  			unreachable()
   469  		}
   470  	}
   471  
   472  	// everything went well
   473  	x.expr = e
   474  	return
   475  
   476  Error:
   477  	x.mode = invalid
   478  	x.expr = e
   479  }
   480  

View as plain text