PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/translator/c/test/test_typed.py

https://bitbucket.org/pypy/pypy/
Python | 898 lines | 840 code | 50 blank | 8 comment | 39 complexity | 361cbb62f1af9d89606093f28eae3e80 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from __future__ import with_statement
  2. import math
  3. import sys
  4. import py
  5. from rpython.rlib.rstackovf import StackOverflow
  6. from rpython.rlib.objectmodel import compute_hash, current_object_addr_as_int
  7. from rpython.rlib.rarithmetic import r_uint, r_ulonglong, r_longlong, intmask, longlongmask
  8. from rpython.rtyper.lltypesystem import rffi, lltype
  9. from rpython.translator.test import snippet
  10. from rpython.translator.c.test.test_genc import compile
  11. class TestTypedTestCase(object):
  12. def getcompiled(self, func, argtypes):
  13. return compile(func, argtypes, backendopt=False)
  14. def test_set_attr(self):
  15. set_attr = self.getcompiled(snippet.set_attr, [])
  16. assert set_attr() == 2
  17. def test_inheritance2(self):
  18. def wrap():
  19. res = snippet.inheritance2()
  20. return res == ((-12, -12.0), (3, 12.3))
  21. fn = self.getcompiled(wrap, [])
  22. assert fn()
  23. def test_factorial2(self):
  24. factorial2 = self.getcompiled(snippet.factorial2, [int])
  25. assert factorial2(5) == 120
  26. def test_factorial(self):
  27. factorial = self.getcompiled(snippet.factorial, [int])
  28. assert factorial(5) == 120
  29. def test_simple_method(self):
  30. simple_method = self.getcompiled(snippet.simple_method, [int])
  31. assert simple_method(55) == 55
  32. def test_sieve_of_eratosthenes(self):
  33. sieve_of_eratosthenes = self.getcompiled(snippet.sieve_of_eratosthenes,
  34. [])
  35. assert sieve_of_eratosthenes() == 1028
  36. def test_nested_whiles(self):
  37. nested_whiles = self.getcompiled(snippet.nested_whiles, [int, int])
  38. assert nested_whiles(5, 3) == '!!!!!'
  39. def test_call_unpack_56(self):
  40. def wrap():
  41. res = snippet.call_unpack_56()
  42. return res == (2, 5, 6)
  43. fn = self.getcompiled(wrap, [])
  44. assert fn()
  45. def test_class_defaultattr(self):
  46. class K:
  47. n = "hello"
  48. def class_defaultattr():
  49. k = K()
  50. k.n += " world"
  51. return k.n
  52. fn = self.getcompiled(class_defaultattr, [])
  53. assert fn() == "hello world"
  54. def test_tuple_repr(self):
  55. def tuple_repr(x, y):
  56. z = x, y
  57. while x:
  58. x = x - 1
  59. return z == (6, 'a')
  60. fn = self.getcompiled(tuple_repr, [int, str])
  61. assert fn(6, "a")
  62. assert not fn(6, "xyz")
  63. def test_classattribute(self):
  64. fn = self.getcompiled(snippet.classattribute, [int])
  65. assert fn(1) == 123
  66. assert fn(2) == 456
  67. assert fn(3) == 789
  68. assert fn(4) == 789
  69. assert fn(5) == 101112
  70. def test_type_conversion(self):
  71. # obfuscated test case specially for typer.insert_link_conversions()
  72. def type_conversion(n):
  73. if n > 3:
  74. while n > 0:
  75. n = n - 1
  76. if n == 5:
  77. n += 3.1416
  78. return n
  79. fn = self.getcompiled(type_conversion, [int])
  80. assert fn(3) == 3
  81. assert fn(5) == 0
  82. assert abs(fn(7) + 0.8584) < 1E-5
  83. def test_do_try_raise_choose(self):
  84. fn = self.getcompiled(snippet.try_raise_choose, [int])
  85. result = []
  86. for n in [-1, 0, 1, 2]:
  87. result.append(fn(n))
  88. assert result == [-1, 0, 1, 2]
  89. def test_is_perfect_number(self):
  90. fn = self.getcompiled(snippet.is_perfect_number, [int])
  91. for i in range(1, 33):
  92. perfect = fn(i)
  93. assert perfect is (i in (6, 28))
  94. def test_prime(self):
  95. fn = self.getcompiled(snippet.prime, [int])
  96. result = [fn(i) for i in range(1, 21)]
  97. assert result == [False, True, True, False, True, False, True, False,
  98. False, False, True, False, True, False, False, False,
  99. True, False, True, False]
  100. def test_mutate_global(self):
  101. class Stuff:
  102. pass
  103. g1 = Stuff(); g1.value = 1
  104. g2 = Stuff(); g2.value = 2
  105. g3 = Stuff(); g3.value = 3
  106. g1.next = g3
  107. g2.next = g3
  108. g3.next = g3
  109. def do_things():
  110. g1.next = g1
  111. g2.next = g1
  112. g3.next = g2
  113. return g3.next.next.value
  114. fn = self.getcompiled(do_things, [])
  115. assert fn() == 1
  116. def test_float_ops(self):
  117. def f(x):
  118. return abs(math.pow(-x, 3) + 1)
  119. fn = self.getcompiled(f, [float])
  120. assert fn(-4.5) == 92.125
  121. assert fn(4.5) == 90.125
  122. def test_memoryerror(self):
  123. def g(i):
  124. return [0] * i
  125. def f(i):
  126. try:
  127. lst = g(i)
  128. lst[-1] = 5
  129. return lst[0]
  130. except MemoryError:
  131. return -1
  132. fn = self.getcompiled(f, [int])
  133. assert fn(1) == 5
  134. assert fn(2) == 0
  135. assert fn(sys.maxint // 2 + 1) == -1
  136. assert fn(sys.maxint) == -1
  137. def test_chr(self):
  138. def f(x):
  139. try:
  140. return 'Yes ' + chr(x)
  141. except ValueError:
  142. return 'No'
  143. fn = self.getcompiled(f, [int])
  144. assert fn(65) == 'Yes A'
  145. assert fn(256) == 'No'
  146. assert fn(-1) == 'No'
  147. def test_unichr(self):
  148. def f(x):
  149. try:
  150. return ord(unichr(x))
  151. except ValueError:
  152. return -42
  153. fn = self.getcompiled(f, [int])
  154. assert fn(65) == 65
  155. assert fn(-12) == -42
  156. assert fn(sys.maxint) == -42
  157. def test_UNICHR(self):
  158. from rpython.rlib.runicode import UNICHR
  159. def f(x):
  160. try:
  161. return ord(UNICHR(x))
  162. except ValueError:
  163. return -42
  164. fn = self.getcompiled(f, [int])
  165. assert fn(65) == 65
  166. assert fn(-12) == -42
  167. assert fn(sys.maxint) == -42
  168. def test_list_indexerror(self):
  169. def f(i):
  170. lst = [123, 456]
  171. try:
  172. lst[i] = 789
  173. except IndexError:
  174. return 42
  175. return lst[0]
  176. fn = self.getcompiled(f, [int])
  177. assert fn(1) == 123
  178. assert fn(2) == 42
  179. assert fn(-2) == 789
  180. assert fn(-3) == 42
  181. def test_long_long(self):
  182. def f(i):
  183. return 4 * i
  184. fn = self.getcompiled(f, [r_ulonglong])
  185. assert fn(r_ulonglong(2147483647)) == 4 * 2147483647
  186. def g(i):
  187. return 4 * i
  188. gn = self.getcompiled(g, [r_longlong])
  189. assert gn(r_longlong(2147483647)) == 4 * 2147483647
  190. def g(i):
  191. return i << 12
  192. gn = self.getcompiled(g, [r_longlong])
  193. assert gn(r_longlong(2147483647)) == 2147483647 << 12
  194. def g(i):
  195. return i >> 12
  196. gn = self.getcompiled(g, [r_longlong])
  197. assert gn(r_longlong(-2147483647)) == (-2147483647) >> 12
  198. def g(i):
  199. return i >> 12
  200. gn = self.getcompiled(g, [r_ulonglong])
  201. assert gn(r_ulonglong(2 ** 64 - 12345678)) == (2 ** 64 - 12345678) >> 12
  202. def test_specializing_int_functions(self):
  203. def f(i):
  204. return i + 1
  205. f._annspecialcase_ = "specialize:argtype(0)"
  206. def g(n):
  207. if n > 0:
  208. return intmask(f(r_longlong(0)))
  209. else:
  210. return f(0)
  211. fn = self.getcompiled(g, [int])
  212. assert fn(0) == 1
  213. assert fn(1) == 1
  214. def test_downcast_int(self):
  215. def f(i):
  216. return int(i)
  217. fn = self.getcompiled(f, [r_longlong])
  218. assert fn(r_longlong(0)) == 0
  219. def test_upcast_int(self):
  220. def f(v):
  221. v = rffi.cast(rffi.USHORT, v)
  222. return intmask(v)
  223. fn = self.getcompiled(f, [int])
  224. assert fn(0x1234CDEF) == 0xCDEF
  225. def test_function_ptr(self):
  226. def f1():
  227. return 1
  228. def f2():
  229. return 2
  230. def g(i):
  231. if i:
  232. f = f1
  233. else:
  234. f = f2
  235. return f()
  236. fn = self.getcompiled(g, [int])
  237. assert fn(0) == 2
  238. assert fn(1) == 1
  239. def test_call_five(self):
  240. # -- the result of call_five() isn't a real list, but an rlist
  241. # that can't be converted to a PyListObject
  242. def wrapper():
  243. lst = snippet.call_five()
  244. return (len(lst), lst[0]) == (1, 5)
  245. call_five = self.getcompiled(wrapper, [])
  246. result = call_five()
  247. assert result
  248. def test_get_set_del_slice(self):
  249. def get_set_del_nonneg_slice(): # no neg slices for now!
  250. l = [ord('a'), ord('b'), ord('c'), ord('d'), ord('e'), ord('f'), ord('g'), ord('h'), ord('i'), ord('j')]
  251. del l[:1]
  252. bound = len(l) - 1
  253. if bound >= 0:
  254. del l[bound:]
  255. del l[2:4]
  256. #l[:1] = [3]
  257. #bound = len(l)-1
  258. #assert bound >= 0
  259. #l[bound:] = [9] no setting slice into lists for now
  260. #l[2:4] = [8,11]
  261. l[0], l[-1], l[2], l[3] = 3, 9, 8, 11
  262. list_3_c = l[:2]
  263. list_9 = l[5:]
  264. list_11_h = l[3:5]
  265. return str((len(l), l[0], l[1], l[2], l[3], l[4], l[5],
  266. len(list_3_c), list_3_c[0], list_3_c[1],
  267. len(list_9), list_9[0],
  268. len(list_11_h), list_11_h[0], list_11_h[1]))
  269. fn = self.getcompiled(get_set_del_nonneg_slice, [])
  270. result = fn()
  271. assert result == str((6, 3, ord('c'), 8, 11, ord('h'), 9,
  272. 2, 3, ord('c'),
  273. 1, 9,
  274. 2, 11, ord('h')))
  275. def test_is(self):
  276. def testfn():
  277. l1 = []
  278. return l1 is l1
  279. fn = self.getcompiled(testfn, [])
  280. result = fn()
  281. assert result is True
  282. def testfn():
  283. l1 = []
  284. return l1 is None
  285. fn = self.getcompiled(testfn, [])
  286. result = fn()
  287. assert result is False
  288. def test_str_compare(self):
  289. def testfn(i, j):
  290. s1 = ['one', 'two']
  291. s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
  292. return s1[i] == s2[j]
  293. fn = self.getcompiled(testfn, [int, int])
  294. for i in range(2):
  295. for j in range(6):
  296. res = fn(i, j)
  297. assert res is testfn(i, j)
  298. def testfn(i, j):
  299. s1 = ['one', 'two']
  300. s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
  301. return s1[i] != s2[j]
  302. fn = self.getcompiled(testfn, [int, int])
  303. for i in range(2):
  304. for j in range(6):
  305. res = fn(i, j)
  306. assert res is testfn(i, j)
  307. def testfn(i, j):
  308. s1 = ['one', 'two']
  309. s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
  310. return s1[i] < s2[j]
  311. fn = self.getcompiled(testfn, [int, int])
  312. for i in range(2):
  313. for j in range(6):
  314. res = fn(i, j)
  315. assert res is testfn(i, j)
  316. def testfn(i, j):
  317. s1 = ['one', 'two']
  318. s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
  319. return s1[i] <= s2[j]
  320. fn = self.getcompiled(testfn, [int, int])
  321. for i in range(2):
  322. for j in range(6):
  323. res = fn(i, j)
  324. assert res is testfn(i, j)
  325. def testfn(i, j):
  326. s1 = ['one', 'two']
  327. s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
  328. return s1[i] > s2[j]
  329. fn = self.getcompiled(testfn, [int, int])
  330. for i in range(2):
  331. for j in range(6):
  332. res = fn(i, j)
  333. assert res is testfn(i, j)
  334. def testfn(i, j):
  335. s1 = ['one', 'two']
  336. s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
  337. return s1[i] >= s2[j]
  338. fn = self.getcompiled(testfn, [int, int])
  339. for i in range(2):
  340. for j in range(6):
  341. res = fn(i, j)
  342. assert res is testfn(i, j)
  343. def test_str_methods(self):
  344. def testfn(i, j):
  345. s1 = ['one', 'two']
  346. s2 = ['one', 'two', 'o', 'on', 'ne', 'e', 'twos', 'foobar', 'fortytwo']
  347. return s1[i].startswith(s2[j])
  348. fn = self.getcompiled(testfn, [int, int])
  349. for i in range(2):
  350. for j in range(9):
  351. res = fn(i, j)
  352. assert res is testfn(i, j)
  353. def testfn(i, j):
  354. s1 = ['one', 'two']
  355. s2 = ['one', 'two', 'o', 'on', 'ne', 'e', 'twos', 'foobar', 'fortytwo']
  356. return s1[i].endswith(s2[j])
  357. fn = self.getcompiled(testfn, [int, int])
  358. for i in range(2):
  359. for j in range(9):
  360. res = fn(i, j)
  361. assert res is testfn(i, j)
  362. def test_str_join(self):
  363. def testfn(i, j):
  364. s1 = ['', ',', ' and ']
  365. s2 = [[], ['foo'], ['bar', 'baz', 'bazz']]
  366. return s1[i].join(s2[j])
  367. fn = self.getcompiled(testfn, [int, int])
  368. for i in range(3):
  369. for j in range(3):
  370. res = fn(i, j)
  371. assert res == fn(i, j)
  372. def test_unichr_eq(self):
  373. l = list(u'Hello world')
  374. def f(i, j):
  375. return l[i] == l[j]
  376. fn = self.getcompiled(f, [int, int])
  377. for i in range(len(l)):
  378. for j in range(len(l)):
  379. res = fn(i, j)
  380. assert res == f(i, j)
  381. def test_unichr_ne(self):
  382. l = list(u'Hello world')
  383. def f(i, j):
  384. return l[i] != l[j]
  385. fn = self.getcompiled(f, [int, int])
  386. for i in range(len(l)):
  387. for j in range(len(l)):
  388. res = fn(i, j)
  389. assert res == f(i, j)
  390. def test_unichr_ord(self):
  391. l = list(u'Hello world')
  392. def f(i):
  393. return ord(l[i])
  394. fn = self.getcompiled(f, [int])
  395. for i in range(len(l)):
  396. res = fn(i)
  397. assert res == f(i)
  398. def test_unichr_unichr(self):
  399. l = list(u'Hello world')
  400. def f(i, j):
  401. return l[i] == unichr(j)
  402. fn = self.getcompiled(f, [int, int])
  403. for i in range(len(l)):
  404. for j in range(len(l)):
  405. res = fn(i, ord(l[j]))
  406. assert res == f(i, ord(l[j]))
  407. def test_int_overflow(self):
  408. fn = self.getcompiled(snippet.add_func, [int])
  409. fn(sys.maxint, expected_exception_name='OverflowError')
  410. def test_int_floordiv_ovf_zer(self):
  411. fn = self.getcompiled(snippet.div_func, [int])
  412. fn(-1, expected_exception_name='OverflowError')
  413. fn(0, expected_exception_name='ZeroDivisionError')
  414. def test_int_mul_ovf(self):
  415. fn = self.getcompiled(snippet.mul_func, [int, int])
  416. for y in range(-5, 5):
  417. for x in range(-5, 5):
  418. assert fn(x, y) == snippet.mul_func(x, y)
  419. n = sys.maxint / 4
  420. assert fn(n, 3) == snippet.mul_func(n, 3)
  421. assert fn(n, 4) == snippet.mul_func(n, 4)
  422. fn(n, 5, expected_exception_name='OverflowError')
  423. def test_int_mod_ovf_zer(self):
  424. fn = self.getcompiled(snippet.mod_func, [int])
  425. fn(-1, expected_exception_name='OverflowError')
  426. fn(0, expected_exception_name='ZeroDivisionError')
  427. def test_int_lshift_ovf(self):
  428. fn = self.getcompiled(snippet.lshift_func, [int])
  429. fn(1, expected_exception_name='OverflowError')
  430. def test_int_unary_ovf(self):
  431. def w(a, b):
  432. if not b:
  433. return snippet.unary_func(a)[0]
  434. else:
  435. return snippet.unary_func(a)[1]
  436. fn = self.getcompiled(w, [int, int])
  437. for i in range(-3, 3):
  438. assert fn(i, 0) == -(i)
  439. assert fn(i, 1) == abs(i - 1)
  440. fn(-sys.maxint - 1, 0, expected_exception_name='OverflowError')
  441. fn(-sys.maxint, 0, expected_exception_name='OverflowError')
  442. # floats
  443. def test_float_operations(self):
  444. def func(x, y):
  445. z = x + y / 2.1 * x
  446. z = math.fmod(z, 60.0)
  447. z = math.pow(z, 2)
  448. z = -z
  449. return int(z)
  450. fn = self.getcompiled(func, [float, float])
  451. assert fn(5.0, 6.0) == func(5.0, 6.0)
  452. def test_rpbc_bound_method_static_call(self):
  453. class R:
  454. def meth(self):
  455. return 0
  456. r = R()
  457. m = r.meth
  458. def fn():
  459. return m()
  460. res = self.getcompiled(fn, [])()
  461. assert res == 0
  462. def test_constant_return_disagreement(self):
  463. class R:
  464. def meth(self):
  465. return 0
  466. r = R()
  467. def fn():
  468. return r.meth()
  469. res = self.getcompiled(fn, [])()
  470. assert res == 0
  471. def test_stringformatting(self):
  472. def fn(i):
  473. return "you said %d, you did" % i
  474. f = self.getcompiled(fn, [int])
  475. assert f(1) == fn(1)
  476. def test_int2str(self):
  477. def fn(i):
  478. return str(i)
  479. f = self.getcompiled(fn, [int])
  480. assert f(1) == fn(1)
  481. def test_float2str(self):
  482. def fn(i):
  483. return str(i)
  484. f = self.getcompiled(fn, [float])
  485. res = f(1.0)
  486. assert type(res) is str and float(res) == 1.0
  487. def test_uint_arith(self):
  488. def fn(i):
  489. try:
  490. return ~(i * (i + 1)) / (i - 1)
  491. except ZeroDivisionError:
  492. return r_uint(91872331)
  493. f = self.getcompiled(fn, [r_uint])
  494. for value in range(15):
  495. i = r_uint(value)
  496. assert f(i) == fn(i)
  497. def test_ord_returns_a_positive(self):
  498. def fn(i):
  499. return ord(chr(i))
  500. f = self.getcompiled(fn, [int])
  501. assert f(255) == 255
  502. def test_hash_preservation(self):
  503. class C:
  504. pass
  505. class D(C):
  506. pass
  507. c = C()
  508. d = D()
  509. compute_hash(d) # force to be cached on 'd', but not on 'c'
  510. #
  511. def fn():
  512. d2 = D()
  513. return str((compute_hash(d2),
  514. current_object_addr_as_int(d2),
  515. compute_hash(c),
  516. compute_hash(d),
  517. compute_hash(("Hi", None, (7.5, 2, d)))))
  518. f = self.getcompiled(fn, [])
  519. res = f()
  520. # xxx the next line is too precise, checking the exact implementation
  521. res = [int(a) for a in res[1:-1].split(",")]
  522. if res[0] != res[1]:
  523. assert res[0] == -res[1] - 1
  524. assert res[2] != compute_hash(c) # likely
  525. assert res[3] == compute_hash(d)
  526. assert res[4] == compute_hash(("Hi", None, (7.5, 2, d)))
  527. def test_list_basic_ops(self):
  528. def list_basic_ops(i, j):
  529. l = [1, 2, 3]
  530. l.insert(0, 42)
  531. del l[1]
  532. l.append(i)
  533. listlen = len(l)
  534. l.extend(l)
  535. del l[listlen:]
  536. l += [5, 6]
  537. l[1] = i
  538. return l[j]
  539. f = self.getcompiled(list_basic_ops, [int, int])
  540. for i in range(6):
  541. for j in range(6):
  542. assert f(i, j) == list_basic_ops(i, j)
  543. def test_range2list(self):
  544. def fn():
  545. r = range(10, 37, 4)
  546. r.reverse()
  547. return r[0]
  548. f = self.getcompiled(fn, [])
  549. assert f() == fn()
  550. def test_range_idx(self):
  551. def fn(idx):
  552. r = range(10, 37, 4)
  553. try:
  554. return r[idx]
  555. except IndexError:
  556. return -1
  557. f = self.getcompiled(fn, [int])
  558. assert f(0) == fn(0)
  559. assert f(-1) == fn(-1)
  560. assert f(42) == -1
  561. def test_range_step(self):
  562. def fn(step):
  563. r = range(10, 37, step)
  564. return r[-2]
  565. f = self.getcompiled(fn, [int])
  566. assert f(1) == fn(1)
  567. assert f(3) == fn(3)
  568. def test_range_iter(self):
  569. def fn(start, stop, step):
  570. res = 0
  571. if step == 0:
  572. if stop >= start:
  573. r = range(start, stop, 1)
  574. else:
  575. r = range(start, stop, -1)
  576. else:
  577. r = range(start, stop, step)
  578. for i in r:
  579. res = res * 51 + i
  580. return res
  581. f = self.getcompiled(fn, [int, int, int])
  582. for args in [2, 7, 0], [7, 2, 0], [10, 50, 7], [50, -10, -3]:
  583. assert f(*args) == intmask(fn(*args))
  584. def test_list_len_is_true(self):
  585. class X(object):
  586. pass
  587. class A(object):
  588. def __init__(self):
  589. self.l = []
  590. def append_to_list(self, e):
  591. self.l.append(e)
  592. def check_list_is_true(self):
  593. did_loop = 0
  594. while self.l:
  595. did_loop = 1
  596. if len(self.l):
  597. break
  598. return did_loop
  599. a1 = A()
  600. def f():
  601. for ii in range(1):
  602. a1.append_to_list(X())
  603. return a1.check_list_is_true()
  604. fn = self.getcompiled(f, [])
  605. assert fn() == 1
  606. def test_recursion_detection(self):
  607. def g(n):
  608. try:
  609. return f(n)
  610. except StackOverflow:
  611. return -42
  612. def f(n):
  613. if n == 0:
  614. return 1
  615. else:
  616. return n * f(n - 1)
  617. fn = self.getcompiled(g, [int])
  618. assert fn(7) == 5040
  619. assert fn(7) == 5040 # detection must work several times, too
  620. assert fn(7) == 5040
  621. assert fn(-1) == -42
  622. def test_infinite_recursion(self):
  623. def f(x):
  624. if x:
  625. return 1 + f(x)
  626. return 1
  627. def g(x):
  628. try:
  629. f(x)
  630. except RuntimeError:
  631. return 42
  632. return 1
  633. fn = self.getcompiled(g, [int])
  634. assert fn(0) == 1
  635. assert fn(1) == 42
  636. def test_r_dict_exceptions(self):
  637. from rpython.rlib.objectmodel import r_dict
  638. def raising_hash(obj):
  639. if obj.startswith("bla"):
  640. raise TypeError
  641. return 1
  642. def eq(obj1, obj2):
  643. return obj1 is obj2
  644. def f():
  645. d1 = r_dict(eq, raising_hash)
  646. d1['xxx'] = 1
  647. try:
  648. x = d1["blabla"]
  649. except Exception:
  650. return 42
  651. return x
  652. fn = self.getcompiled(f, [])
  653. res = fn()
  654. assert res == 42
  655. def f():
  656. d1 = r_dict(eq, raising_hash)
  657. d1['xxx'] = 1
  658. try:
  659. x = d1["blabla"]
  660. except TypeError:
  661. return 42
  662. return x
  663. fn = self.getcompiled(f, [])
  664. res = fn()
  665. assert res == 42
  666. def f():
  667. d1 = r_dict(eq, raising_hash)
  668. d1['xxx'] = 1
  669. try:
  670. d1["blabla"] = 2
  671. except TypeError:
  672. return 42
  673. return 0
  674. fn = self.getcompiled(f, [])
  675. res = fn()
  676. assert res == 42
  677. def test_float(self):
  678. ex = ['', ' ', '0', '1', '-1.5', '1.5E2', '2.5e-1', ' 0 ', '?']
  679. def f(i):
  680. s = ex[i]
  681. try:
  682. return float(s)
  683. except ValueError:
  684. return -999.0
  685. fn = self.getcompiled(f, [int])
  686. for i in range(len(ex)):
  687. expected = f(i)
  688. res = fn(i)
  689. assert res == expected
  690. def test_swap(self):
  691. def func_swap():
  692. a = []
  693. b = range(10)
  694. while b:
  695. b.pop()
  696. a.extend(b)
  697. tmp = a
  698. a = b
  699. b = tmp
  700. del a[:]
  701. self.getcompiled(func_swap, [])
  702. def test_ovfcheck_float_to_int(self):
  703. from rpython.rlib.rarithmetic import ovfcheck_float_to_int
  704. def func(fl):
  705. try:
  706. return ovfcheck_float_to_int(fl)
  707. except OverflowError:
  708. return -666
  709. f = self.getcompiled(func, [float])
  710. assert f(-123.0) == -123
  711. for frac in [0.0, 0.01, 0.99]:
  712. # strange things happening for float to int on 64 bit:
  713. # int(float(i)) != i because of rounding issues
  714. x = sys.maxint
  715. while int(x + frac) > sys.maxint:
  716. x -= 1
  717. assert f(x + frac) == int(x + frac)
  718. x = sys.maxint
  719. while int(x - frac) <= sys.maxint:
  720. x += 1
  721. assert f(x - frac) == -666
  722. x = -sys.maxint - 1
  723. while int(x - frac) < -sys.maxint - 1:
  724. x += 1
  725. assert f(x - frac) == int(x - frac)
  726. x = -sys.maxint - 1
  727. while int(x + frac) >= -sys.maxint- 1:
  728. x -= 1
  729. assert f(x + frac) == -666
  730. def test_context_manager(self):
  731. state = []
  732. class C:
  733. def __init__(self, name):
  734. self.name = name
  735. def __enter__(self):
  736. state.append('acquire')
  737. return self
  738. def __exit__(self, typ, value, tb):
  739. if typ is not None:
  740. if value is None:
  741. raise RuntimeError('test failed')
  742. state.append('raised')
  743. else:
  744. if value is not None:
  745. raise RuntimeError('test failed')
  746. state.append('release')
  747. def func(n):
  748. del state[:]
  749. try:
  750. with C('hello') as c:
  751. state.append(c.name)
  752. if n == 1:
  753. raise ValueError
  754. elif n == 2:
  755. raise TypeError
  756. except (ValueError, TypeError):
  757. pass
  758. return ', '.join(state)
  759. f = self.getcompiled(func, [int])
  760. res = f(0)
  761. assert res == 'acquire, hello, release'
  762. res = f(1)
  763. assert res == 'acquire, hello, raised, release'
  764. res = f(2)
  765. assert res == 'acquire, hello, raised, release'
  766. def test_longlongmask(self):
  767. def func(n):
  768. m = r_ulonglong(n)
  769. m *= 100000
  770. return longlongmask(m)
  771. f = self.getcompiled(func, [int])
  772. res = f(-2000000000)
  773. assert res == -200000000000000
  774. def test_int128(self):
  775. if not hasattr(rffi, '__INT128_T'):
  776. py.test.skip("no '__int128_t'")
  777. def func(n):
  778. x = rffi.cast(getattr(rffi, '__INT128_T'), n)
  779. x *= x
  780. x *= x
  781. x *= x
  782. x *= x
  783. return intmask(x >> 96)
  784. f = self.getcompiled(func, [int])
  785. res = f(217)
  786. assert res == 305123851
  787. def test_bool_2(self):
  788. def func(n):
  789. x = rffi.cast(lltype.Bool, n)
  790. return int(x)
  791. f = self.getcompiled(func, [int])
  792. res = f(2)
  793. assert res == 1 # and not 2