PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/third_party/gofrontend/libgo/go/go/types/builtins.go

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