github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/go/types/builtins.go (about)

     1  // Copyright 2012 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 builtin function calls.
     6  
     7  package types
     8  
     9  import (
    10  	"go/ast"
    11  	"go/exact"
    12  	"go/token"
    13  )
    14  
    15  // builtin type-checks a call to the built-in specified by id and
    16  // returns true if the call is valid, with *x holding the result;
    17  // but x.expr is not set. If the call is invalid, the result is
    18  // false, and *x is undefined.
    19  //
    20  func (check *Checker) builtin(x *operand, call *ast.CallExpr, id builtinId) (_ bool) {
    21  	// append is the only built-in that permits the use of ... for the last argument
    22  	bin := predeclaredFuncs[id]
    23  	if call.Ellipsis.IsValid() && id != _Append {
    24  		check.invalidOp(call.Ellipsis, "invalid use of ... with built-in %s", bin.name)
    25  		check.use(call.Args...)
    26  		return
    27  	}
    28  
    29  	// For len(x) and cap(x) we need to know if x contains any function calls or
    30  	// receive operations. Save/restore current setting and set hasCallOrRecv to
    31  	// false for the evaluation of x so that we can check it afterwards.
    32  	// Note: We must do this _before_ calling unpack because unpack evaluates the
    33  	//       first argument before we even call arg(x, 0)!
    34  	if id == _Len || id == _Cap {
    35  		defer func(b bool) {
    36  			check.hasCallOrRecv = b
    37  		}(check.hasCallOrRecv)
    38  		check.hasCallOrRecv = false
    39  	}
    40  
    41  	// determine actual arguments
    42  	var arg getter
    43  	nargs := len(call.Args)
    44  	switch id {
    45  	default:
    46  		// make argument getter
    47  		arg, nargs, _ = unpack(func(x *operand, i int) { check.expr(x, call.Args[i]) }, nargs, false)
    48  		if arg == nil {
    49  			return
    50  		}
    51  		// evaluate first argument, if present
    52  		if nargs > 0 {
    53  			arg(x, 0)
    54  			if x.mode == invalid {
    55  				return
    56  			}
    57  		}
    58  	case _Make, _New, _Offsetof, _Trace:
    59  		// arguments require special handling
    60  	}
    61  
    62  	// check argument count
    63  	{
    64  		msg := ""
    65  		if nargs < bin.nargs {
    66  			msg = "not enough"
    67  		} else if !bin.variadic && nargs > bin.nargs {
    68  			msg = "too many"
    69  		}
    70  		if msg != "" {
    71  			check.invalidOp(call.Rparen, "%s arguments for %s (expected %d, found %d)", msg, call, bin.nargs, nargs)
    72  			return
    73  		}
    74  	}
    75  
    76  	switch id {
    77  	case _Append:
    78  		// append(s S, x ...T) S, where T is the element type of S
    79  		// spec: "The variadic function append appends zero or more values x to s of type
    80  		// S, which must be a slice type, and returns the resulting slice, also of type S.
    81  		// The values x are passed to a parameter of type ...T where T is the element type
    82  		// of S and the respective parameter passing rules apply."
    83  		S := x.typ
    84  		var T Type
    85  		if s, _ := S.Underlying().(*Slice); s != nil {
    86  			T = s.elem
    87  		} else {
    88  			check.invalidArg(x.pos(), "%s is not a slice", x)
    89  			return
    90  		}
    91  
    92  		// remember arguments that have been evaluated already
    93  		alist := []operand{*x}
    94  
    95  		// spec: "As a special case, append also accepts a first argument assignable
    96  		// to type []byte with a second argument of string type followed by ... .
    97  		// This form appends the bytes of the string.
    98  		if nargs == 2 && call.Ellipsis.IsValid() && x.assignableTo(check.conf, NewSlice(UniverseByte)) {
    99  			arg(x, 1)
   100  			if x.mode == invalid {
   101  				return
   102  			}
   103  			if isString(x.typ) {
   104  				if check.Types != nil {
   105  					sig := makeSig(S, S, x.typ)
   106  					sig.variadic = true
   107  					check.recordBuiltinType(call.Fun, sig)
   108  				}
   109  				x.mode = value
   110  				x.typ = S
   111  				break
   112  			}
   113  			alist = append(alist, *x)
   114  			// fallthrough
   115  		}
   116  
   117  		// check general case by creating custom signature
   118  		sig := makeSig(S, S, NewSlice(T)) // []T required for variadic signature
   119  		sig.variadic = true
   120  		check.arguments(x, call, sig, func(x *operand, i int) {
   121  			// only evaluate arguments that have not been evaluated before
   122  			if i < len(alist) {
   123  				*x = alist[i]
   124  				return
   125  			}
   126  			arg(x, i)
   127  		}, nargs)
   128  		// ok to continue even if check.arguments reported errors
   129  
   130  		x.mode = value
   131  		x.typ = S
   132  		if check.Types != nil {
   133  			check.recordBuiltinType(call.Fun, sig)
   134  		}
   135  
   136  	case _Cap, _Len:
   137  		// cap(x)
   138  		// len(x)
   139  		mode := invalid
   140  		var typ Type
   141  		var val exact.Value
   142  		switch typ = implicitArrayDeref(x.typ.Underlying()); t := typ.(type) {
   143  		case *Basic:
   144  			if isString(t) && id == _Len {
   145  				if x.mode == constant {
   146  					mode = constant
   147  					val = exact.MakeInt64(int64(len(exact.StringVal(x.val))))
   148  				} else {
   149  					mode = value
   150  				}
   151  			}
   152  
   153  		case *Array:
   154  			mode = value
   155  			// spec: "The expressions len(s) and cap(s) are constants
   156  			// if the type of s is an array or pointer to an array and
   157  			// the expression s does not contain channel receives or
   158  			// function calls; in this case s is not evaluated."
   159  			if !check.hasCallOrRecv {
   160  				mode = constant
   161  				val = exact.MakeInt64(t.len)
   162  			}
   163  
   164  		case *Slice, *Chan:
   165  			mode = value
   166  
   167  		case *Map:
   168  			if id == _Len {
   169  				mode = value
   170  			}
   171  		}
   172  
   173  		if mode == invalid {
   174  			check.invalidArg(x.pos(), "%s for %s", x, bin.name)
   175  			return
   176  		}
   177  
   178  		x.mode = mode
   179  		x.typ = Typ[Int]
   180  		x.val = val
   181  		if check.Types != nil && mode != constant {
   182  			check.recordBuiltinType(call.Fun, makeSig(x.typ, typ))
   183  		}
   184  
   185  	case _Close:
   186  		// close(c)
   187  		c, _ := x.typ.Underlying().(*Chan)
   188  		if c == nil {
   189  			check.invalidArg(x.pos(), "%s is not a channel", x)
   190  			return
   191  		}
   192  		if c.dir == RecvOnly {
   193  			check.invalidArg(x.pos(), "%s must not be a receive-only channel", x)
   194  			return
   195  		}
   196  
   197  		x.mode = novalue
   198  		if check.Types != nil {
   199  			check.recordBuiltinType(call.Fun, makeSig(nil, c))
   200  		}
   201  
   202  	case _Complex:
   203  		// complex(x, y realT) complexT
   204  		if !check.complexArg(x) {
   205  			return
   206  		}
   207  
   208  		var y operand
   209  		arg(&y, 1)
   210  		if y.mode == invalid {
   211  			return
   212  		}
   213  		if !check.complexArg(&y) {
   214  			return
   215  		}
   216  
   217  		check.convertUntyped(x, y.typ)
   218  		if x.mode == invalid {
   219  			return
   220  		}
   221  		check.convertUntyped(&y, x.typ)
   222  		if y.mode == invalid {
   223  			return
   224  		}
   225  
   226  		if !Identical(x.typ, y.typ) {
   227  			check.invalidArg(x.pos(), "mismatched types %s and %s", x.typ, y.typ)
   228  			return
   229  		}
   230  
   231  		if x.mode == constant && y.mode == constant {
   232  			x.val = exact.BinaryOp(x.val, token.ADD, exact.MakeImag(y.val))
   233  		} else {
   234  			x.mode = value
   235  		}
   236  
   237  		realT := x.typ
   238  		complexT := Typ[Invalid]
   239  		switch realT.Underlying().(*Basic).kind {
   240  		case Float32:
   241  			complexT = Typ[Complex64]
   242  		case Float64:
   243  			complexT = Typ[Complex128]
   244  		case UntypedInt, UntypedRune, UntypedFloat:
   245  			if x.mode == constant {
   246  				realT = defaultType(realT).(*Basic)
   247  				complexT = Typ[UntypedComplex]
   248  			} else {
   249  				// untyped but not constant; probably because one
   250  				// operand is a non-constant shift of untyped lhs
   251  				realT = Typ[Float64]
   252  				complexT = Typ[Complex128]
   253  			}
   254  		default:
   255  			check.invalidArg(x.pos(), "float32 or float64 arguments expected")
   256  			return
   257  		}
   258  
   259  		x.typ = complexT
   260  		if check.Types != nil && x.mode != constant {
   261  			check.recordBuiltinType(call.Fun, makeSig(complexT, realT, realT))
   262  		}
   263  
   264  		if x.mode != constant {
   265  			// The arguments have now their final types, which at run-
   266  			// time will be materialized. Update the expression trees.
   267  			// If the current types are untyped, the materialized type
   268  			// is the respective default type.
   269  			// (If the result is constant, the arguments are never
   270  			// materialized and there is nothing to do.)
   271  			check.updateExprType(x.expr, realT, true)
   272  			check.updateExprType(y.expr, realT, true)
   273  		}
   274  
   275  	case _Copy:
   276  		// copy(x, y []T) int
   277  		var dst Type
   278  		if t, _ := x.typ.Underlying().(*Slice); t != nil {
   279  			dst = t.elem
   280  		}
   281  
   282  		var y operand
   283  		arg(&y, 1)
   284  		if y.mode == invalid {
   285  			return
   286  		}
   287  		var src Type
   288  		switch t := y.typ.Underlying().(type) {
   289  		case *Basic:
   290  			if isString(y.typ) {
   291  				src = UniverseByte
   292  			}
   293  		case *Slice:
   294  			src = t.elem
   295  		}
   296  
   297  		if dst == nil || src == nil {
   298  			check.invalidArg(x.pos(), "copy expects slice arguments; found %s and %s", x, &y)
   299  			return
   300  		}
   301  
   302  		if !Identical(dst, src) {
   303  			check.invalidArg(x.pos(), "arguments to copy %s and %s have different element types %s and %s", x, &y, dst, src)
   304  			return
   305  		}
   306  
   307  		if check.Types != nil {
   308  			check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ, y.typ))
   309  		}
   310  		x.mode = value
   311  		x.typ = Typ[Int]
   312  
   313  	case _Delete:
   314  		// delete(m, k)
   315  		m, _ := x.typ.Underlying().(*Map)
   316  		if m == nil {
   317  			check.invalidArg(x.pos(), "%s is not a map", x)
   318  			return
   319  		}
   320  		arg(x, 1) // k
   321  		if x.mode == invalid {
   322  			return
   323  		}
   324  
   325  		if !x.assignableTo(check.conf, m.key) {
   326  			check.invalidArg(x.pos(), "%s is not assignable to %s", x, m.key)
   327  			return
   328  		}
   329  
   330  		x.mode = novalue
   331  		if check.Types != nil {
   332  			check.recordBuiltinType(call.Fun, makeSig(nil, m, m.key))
   333  		}
   334  
   335  	case _Imag, _Real:
   336  		// imag(complexT) realT
   337  		// real(complexT) realT
   338  		if !isComplex(x.typ) {
   339  			check.invalidArg(x.pos(), "%s must be a complex number", x)
   340  			return
   341  		}
   342  		if x.mode == constant {
   343  			if id == _Real {
   344  				x.val = exact.Real(x.val)
   345  			} else {
   346  				x.val = exact.Imag(x.val)
   347  			}
   348  		} else {
   349  			x.mode = value
   350  		}
   351  		var k BasicKind
   352  		switch x.typ.Underlying().(*Basic).kind {
   353  		case Complex64:
   354  			k = Float32
   355  		case Complex128:
   356  			k = Float64
   357  		case UntypedComplex:
   358  			k = UntypedFloat
   359  		default:
   360  			unreachable()
   361  		}
   362  
   363  		if check.Types != nil && x.mode != constant {
   364  			check.recordBuiltinType(call.Fun, makeSig(Typ[k], x.typ))
   365  		}
   366  		x.typ = Typ[k]
   367  
   368  	case _Make:
   369  		// make(T, n)
   370  		// make(T, n, m)
   371  		// (no argument evaluated yet)
   372  		arg0 := call.Args[0]
   373  		T := check.typ(arg0)
   374  		if T == Typ[Invalid] {
   375  			return
   376  		}
   377  
   378  		var min int // minimum number of arguments
   379  		switch T.Underlying().(type) {
   380  		case *Slice:
   381  			min = 2
   382  		case *Map, *Chan:
   383  			min = 1
   384  		default:
   385  			check.invalidArg(arg0.Pos(), "cannot make %s; type must be slice, map, or channel", arg0)
   386  			return
   387  		}
   388  		if nargs < min || min+1 < nargs {
   389  			check.errorf(call.Pos(), "%s expects %d or %d arguments; found %d", call, min, min+1, nargs)
   390  			return
   391  		}
   392  		var sizes []int64 // constant integer arguments, if any
   393  		for _, arg := range call.Args[1:] {
   394  			if s, ok := check.index(arg, -1); ok && s >= 0 {
   395  				sizes = append(sizes, s)
   396  			}
   397  		}
   398  		if len(sizes) == 2 && sizes[0] > sizes[1] {
   399  			check.invalidArg(call.Args[1].Pos(), "length and capacity swapped")
   400  			// safe to continue
   401  		}
   402  		x.mode = value
   403  		x.typ = T
   404  		if check.Types != nil {
   405  			params := [...]Type{T, Typ[Int], Typ[Int]}
   406  			check.recordBuiltinType(call.Fun, makeSig(x.typ, params[:1+len(sizes)]...))
   407  		}
   408  
   409  	case _New:
   410  		// new(T)
   411  		// (no argument evaluated yet)
   412  		T := check.typ(call.Args[0])
   413  		if T == Typ[Invalid] {
   414  			return
   415  		}
   416  
   417  		x.mode = value
   418  		x.typ = &Pointer{base: T}
   419  		if check.Types != nil {
   420  			check.recordBuiltinType(call.Fun, makeSig(x.typ, T))
   421  		}
   422  
   423  	case _Panic:
   424  		// panic(x)
   425  		T := new(Interface)
   426  		if !check.assignment(x, T) {
   427  			assert(x.mode == invalid)
   428  			return
   429  		}
   430  
   431  		x.mode = novalue
   432  		if check.Types != nil {
   433  			check.recordBuiltinType(call.Fun, makeSig(nil, T))
   434  		}
   435  
   436  	case _Print, _Println:
   437  		// print(x, y, ...)
   438  		// println(x, y, ...)
   439  		var params []Type
   440  		if nargs > 0 {
   441  			params = make([]Type, nargs)
   442  			for i := 0; i < nargs; i++ {
   443  				if i > 0 {
   444  					arg(x, i) // first argument already evaluated
   445  				}
   446  				if !check.assignment(x, nil) {
   447  					assert(x.mode == invalid)
   448  					return
   449  				}
   450  				params[i] = x.typ
   451  			}
   452  		}
   453  
   454  		x.mode = novalue
   455  		if check.Types != nil {
   456  			check.recordBuiltinType(call.Fun, makeSig(nil, params...))
   457  		}
   458  
   459  	case _Recover:
   460  		// recover() interface{}
   461  		x.mode = value
   462  		x.typ = new(Interface)
   463  		if check.Types != nil {
   464  			check.recordBuiltinType(call.Fun, makeSig(x.typ))
   465  		}
   466  
   467  	case _Alignof:
   468  		// unsafe.Alignof(x T) uintptr
   469  		if !check.assignment(x, nil) {
   470  			assert(x.mode == invalid)
   471  			return
   472  		}
   473  
   474  		x.mode = constant
   475  		x.val = exact.MakeInt64(check.conf.alignof(x.typ))
   476  		x.typ = Typ[Uintptr]
   477  		// result is constant - no need to record signature
   478  
   479  	case _Offsetof:
   480  		// unsafe.Offsetof(x T) uintptr, where x must be a selector
   481  		// (no argument evaluated yet)
   482  		arg0 := call.Args[0]
   483  		selx, _ := unparen(arg0).(*ast.SelectorExpr)
   484  		if selx == nil {
   485  			check.invalidArg(arg0.Pos(), "%s is not a selector expression", arg0)
   486  			check.use(arg0)
   487  			return
   488  		}
   489  
   490  		check.expr(x, selx.X)
   491  		if x.mode == invalid {
   492  			return
   493  		}
   494  
   495  		base := derefStructPtr(x.typ)
   496  		sel := selx.Sel.Name
   497  		obj, index, indirect := LookupFieldOrMethod(base, false, check.pkg, sel)
   498  		switch obj.(type) {
   499  		case nil:
   500  			check.invalidArg(x.pos(), "%s has no single field %s", base, sel)
   501  			return
   502  		case *Func:
   503  			// TODO(gri) Using derefStructPtr may result in methods being found
   504  			// that don't actually exist. An error either way, but the error
   505  			// message is confusing. See: http://play.golang.org/p/al75v23kUy ,
   506  			// but go/types reports: "invalid argument: x.m is a method value".
   507  			check.invalidArg(arg0.Pos(), "%s is a method value", arg0)
   508  			return
   509  		}
   510  		if indirect {
   511  			check.invalidArg(x.pos(), "field %s is embedded via a pointer in %s", sel, base)
   512  			return
   513  		}
   514  
   515  		// TODO(gri) Should we pass x.typ instead of base (and indirect report if derefStructPtr indirected)?
   516  		check.recordSelection(selx, FieldVal, base, obj, index, false)
   517  
   518  		offs := check.conf.offsetof(base, index)
   519  		x.mode = constant
   520  		x.val = exact.MakeInt64(offs)
   521  		x.typ = Typ[Uintptr]
   522  		// result is constant - no need to record signature
   523  
   524  	case _Sizeof:
   525  		// unsafe.Sizeof(x T) uintptr
   526  		if !check.assignment(x, nil) {
   527  			assert(x.mode == invalid)
   528  			return
   529  		}
   530  
   531  		x.mode = constant
   532  		x.val = exact.MakeInt64(check.conf.sizeof(x.typ))
   533  		x.typ = Typ[Uintptr]
   534  		// result is constant - no need to record signature
   535  
   536  	case _Assert:
   537  		// assert(pred) causes a typechecker error if pred is false.
   538  		// The result of assert is the value of pred if there is no error.
   539  		// Note: assert is only available in self-test mode.
   540  		if x.mode != constant || !isBoolean(x.typ) {
   541  			check.invalidArg(x.pos(), "%s is not a boolean constant", x)
   542  			return
   543  		}
   544  		if x.val.Kind() != exact.Bool {
   545  			check.errorf(x.pos(), "internal error: value of %s should be a boolean constant", x)
   546  			return
   547  		}
   548  		if !exact.BoolVal(x.val) {
   549  			check.errorf(call.Pos(), "%s failed", call)
   550  			// compile-time assertion failure - safe to continue
   551  		}
   552  		// result is constant - no need to record signature
   553  
   554  	case _Trace:
   555  		// trace(x, y, z, ...) dumps the positions, expressions, and
   556  		// values of its arguments. The result of trace is the value
   557  		// of the first argument.
   558  		// Note: trace is only available in self-test mode.
   559  		// (no argument evaluated yet)
   560  		if nargs == 0 {
   561  			check.dump("%s: trace() without arguments", call.Pos())
   562  			x.mode = novalue
   563  			break
   564  		}
   565  		var t operand
   566  		x1 := x
   567  		for _, arg := range call.Args {
   568  			check.rawExpr(x1, arg, nil) // permit trace for types, e.g.: new(trace(T))
   569  			check.dump("%s: %s", x1.pos(), x1)
   570  			x1 = &t // use incoming x only for first argument
   571  		}
   572  		// trace is only available in test mode - no need to record signature
   573  
   574  	default:
   575  		unreachable()
   576  	}
   577  
   578  	return true
   579  }
   580  
   581  // makeSig makes a signature for the given argument and result types.
   582  // Default types are used for untyped arguments, and res may be nil.
   583  func makeSig(res Type, args ...Type) *Signature {
   584  	list := make([]*Var, len(args))
   585  	for i, param := range args {
   586  		list[i] = NewVar(token.NoPos, nil, "", defaultType(param))
   587  	}
   588  	params := NewTuple(list...)
   589  	var result *Tuple
   590  	if res != nil {
   591  		assert(!isUntyped(res))
   592  		result = NewTuple(NewVar(token.NoPos, nil, "", res))
   593  	}
   594  	return &Signature{params: params, results: result}
   595  }
   596  
   597  // implicitArrayDeref returns A if typ is of the form *A and A is an array;
   598  // otherwise it returns typ.
   599  //
   600  func implicitArrayDeref(typ Type) Type {
   601  	if p, ok := typ.(*Pointer); ok {
   602  		if a, ok := p.base.Underlying().(*Array); ok {
   603  			return a
   604  		}
   605  	}
   606  	return typ
   607  }
   608  
   609  // unparen returns e with any enclosing parentheses stripped.
   610  func unparen(e ast.Expr) ast.Expr {
   611  	for {
   612  		p, ok := e.(*ast.ParenExpr)
   613  		if !ok {
   614  			return e
   615  		}
   616  		e = p.X
   617  	}
   618  }
   619  
   620  func (check *Checker) complexArg(x *operand) bool {
   621  	t, _ := x.typ.Underlying().(*Basic)
   622  	if t != nil && (t.info&IsFloat != 0 || t.kind == UntypedInt || t.kind == UntypedRune) {
   623  		return true
   624  	}
   625  	check.invalidArg(x.pos(), "%s must be a float32, float64, or an untyped non-complex numeric constant", x)
   626  	return false
   627  }