PageRenderTime 56ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/rlib/test/test_rarithmetic.py

https://bitbucket.org/pypy/pypy/
Python | 604 lines | 537 code | 52 blank | 15 comment | 58 complexity | 6e57e3ace81b3fae36024cdf5e1a9fab MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from rpython.rtyper.test.tool import BaseRtypingTest
  2. from rpython.rtyper.test.test_llinterp import interpret
  3. from rpython.rlib.rarithmetic import *
  4. from rpython.rlib.rstring import ParseStringError, ParseStringOverflowError
  5. from hypothesis import given, strategies
  6. import sys
  7. import py
  8. maxint_mask = (sys.maxint*2 + 1)
  9. machbits = 0
  10. i = 1
  11. l = 1L
  12. while i == l and type(i) is int:
  13. i *= 2
  14. l *= 2
  15. machbits += 1
  16. #print machbits
  17. class Test_r_int:
  18. def test__add__(self):
  19. self.binary_test(lambda x, y: x + y, includes_floats=True)
  20. def test__sub__(self):
  21. self.binary_test(lambda x, y: x - y, includes_floats=True)
  22. def test__mul__(self):
  23. self.binary_test(lambda x, y: x * y, includes_floats=True)
  24. x = 3; y = [2]
  25. assert x*y == r_int(x)*y
  26. assert y*x == y*r_int(x)
  27. def test__div__(self):
  28. self.binary_test(lambda x, y: x // y)
  29. def test__mod__(self):
  30. self.binary_test(lambda x, y: x % y)
  31. def test__divmod__(self):
  32. self.binary_test(divmod)
  33. def test__lshift__(self):
  34. self.binary_test(lambda x, y: x << y, (1, 2, 3))
  35. def test__rshift__(self):
  36. self.binary_test(lambda x, y: x >> y, (1, 2, 3))
  37. def test__or__(self):
  38. self.binary_test(lambda x, y: x | y)
  39. def test__and__(self):
  40. self.binary_test(lambda x, y: x & y)
  41. def test__xor__(self):
  42. self.binary_test(lambda x, y: x ^ y)
  43. def test__neg__(self):
  44. self.unary_test(lambda x: -x)
  45. def test__pos__(self):
  46. self.unary_test(lambda x: +x)
  47. def test__invert__(self):
  48. self.unary_test(lambda x: ~x)
  49. def test__pow__(self):
  50. self.binary_test(lambda x, y: x**y, (2, 3))
  51. self.binary_test(lambda x, y: pow(x, y, 42L), (2, 3, 5, 1000))
  52. def unary_test(self, f):
  53. for arg in (-10, -1, 0, 3, 12345):
  54. res = f(arg)
  55. cmp = f(r_int(arg))
  56. assert res == cmp
  57. def binary_test(self, f, rargs=None, includes_floats=False):
  58. if not rargs:
  59. rargs = (-10, -1, 3, 55)
  60. types_list = [(int, r_int), (r_int, int), (r_int, r_int)]
  61. if includes_floats:
  62. types_list += [(float, r_int), (r_int, float)]
  63. for larg in (-10, -1, 0, 3, 1234):
  64. for rarg in rargs:
  65. for types in types_list:
  66. res = f(larg, rarg)
  67. left, right = types
  68. cmp = f(left(larg), right(rarg))
  69. assert res == cmp
  70. class Test_r_uint:
  71. def test__add__(self):
  72. self.binary_test(lambda x, y: x + y)
  73. def test__sub__(self):
  74. self.binary_test(lambda x, y: x - y)
  75. def test__mul__(self):
  76. self.binary_test(lambda x, y: x * y)
  77. x = 3; y = [2]
  78. assert x*y == r_uint(x)*y
  79. assert y*x == y*r_uint(x)
  80. def test__div__(self):
  81. self.binary_test(lambda x, y: x // y)
  82. def test__mod__(self):
  83. self.binary_test(lambda x, y: x % y)
  84. def test__divmod__(self):
  85. self.binary_test(divmod)
  86. def test__lshift__(self):
  87. self.binary_test(lambda x, y: x << y, (1, 2, 3))
  88. def test__rshift__(self):
  89. self.binary_test(lambda x, y: x >> y, (1, 2, 3))
  90. def test__or__(self):
  91. self.binary_test(lambda x, y: x | y)
  92. def test__and__(self):
  93. self.binary_test(lambda x, y: x & y)
  94. def test__xor__(self):
  95. self.binary_test(lambda x, y: x ^ y)
  96. def test__neg__(self):
  97. self.unary_test(lambda x: -x)
  98. def test__pos__(self):
  99. self.unary_test(lambda x: +x)
  100. def test__invert__(self):
  101. self.unary_test(lambda x: ~x)
  102. def test__pow__(self):
  103. self.binary_test(lambda x, y: x**y, (2, 3))
  104. # pow is buggy, dowsn't allow our type
  105. #self.binary_test(lambda x, y: pow(x, y, 42), (2, 3, 5, 1000))
  106. def test_back_to_int(self):
  107. #assert int(r_uint(-1)) == -1
  108. # ^^^ that looks wrong IMHO: int(x) should not by itself return
  109. # an integer that has a different value than x, especially
  110. # if x is a subclass of long.
  111. assert int(r_uint(1)) == 1
  112. def unary_test(self, f):
  113. for arg in (0, 3, 12345):
  114. res = f(arg) & maxint_mask
  115. cmp = f(r_uint(arg))
  116. assert res == cmp
  117. def binary_test(self, f, rargs = None, translated=False):
  118. mask = maxint_mask
  119. if not rargs:
  120. rargs = (1, 3, 55)
  121. # when translated merging different int types is not allowed
  122. if translated:
  123. alltypes = [(r_uint, r_uint)]
  124. else:
  125. alltypes = [(int, r_uint), (r_uint, int), (r_uint, r_uint)]
  126. for larg in (0, 1, 2, 3, 1234):
  127. for rarg in rargs:
  128. for types in alltypes:
  129. res = f(larg, rarg)
  130. left, right = types
  131. cmp = f(left(larg), right(rarg))
  132. if type(res) is tuple:
  133. res = res[0] & mask, res[1] & mask
  134. else:
  135. res = res & mask
  136. assert res == cmp
  137. def test_from_float(self):
  138. assert r_uint(2.3) == 2
  139. assert r_uint(sys.maxint * 1.234) == long(sys.maxint * 1.234)
  140. def test_to_float(self):
  141. assert float(r_uint(2)) == 2.0
  142. val = long(sys.maxint * 1.234)
  143. assert float(r_uint(val)) == float(val)
  144. def test_mixed_types():
  145. types = [r_uint, r_ulonglong]
  146. for left in types:
  147. for right in types:
  148. x = left(3) + right(5)
  149. expected = max(types.index(left), types.index(right))
  150. assert types.index(type(x)) == expected
  151. def test_limits():
  152. for cls in r_uint, r_ulonglong:
  153. mask = cls.MASK
  154. assert cls(mask) == mask
  155. assert cls(mask+1) == 0
  156. for cls in r_int, r_longlong:
  157. mask = cls.MASK>>1
  158. assert cls(mask) == mask
  159. assert cls(-mask-1) == -mask-1
  160. py.test.raises(OverflowError, "cls(mask) + 1")
  161. py.test.raises(OverflowError, "cls(-mask-1) - 1")
  162. def test_intmask():
  163. assert intmask(1) == 1
  164. assert intmask(sys.maxint) == sys.maxint
  165. minint = -sys.maxint-1
  166. assert intmask(minint) == minint
  167. assert intmask(2*sys.maxint+1) == -1
  168. assert intmask(sys.maxint*2) == -2
  169. assert intmask(sys.maxint*2+2) == 0
  170. assert intmask(2*(sys.maxint*1+1)) == 0
  171. assert intmask(1 << (machbits-1)) == 1 << (machbits-1)
  172. assert intmask(sys.maxint+1) == minint
  173. assert intmask(minint-1) == sys.maxint
  174. assert intmask(r_uint(-1)) == -1
  175. assert intmask(r_ulonglong(-1)) == -1
  176. def test_intmask_small():
  177. from rpython.rtyper.lltypesystem import rffi
  178. for tp in [rffi.r_signedchar, rffi.r_short, rffi.r_int,
  179. rffi.r_long, rffi.r_longlong]:
  180. x = intmask(tp(5))
  181. assert (type(x), x) == (int, 5)
  182. x = intmask(tp(-5))
  183. assert (type(x), x) == (int, -5)
  184. for tp in [rffi.r_uchar, rffi.r_ushort, rffi.r_uint,
  185. rffi.r_ulong, rffi.r_ulonglong]:
  186. x = intmask(tp(5))
  187. assert (type(x), x) == (int, 5)
  188. def test_bug_creating_r_int():
  189. minint = -sys.maxint-1
  190. assert r_int(r_int(minint)) == minint
  191. def test_ovfcheck():
  192. one = 1
  193. x = sys.maxint
  194. minusx = -sys.maxint
  195. n = -sys.maxint-1
  196. y = sys.maxint-1
  197. # sanity
  198. py.test.raises(AssertionError, ovfcheck, r_uint(0))
  199. # not overflowing
  200. try:
  201. ovfcheck(y+one)
  202. except OverflowError:
  203. assert False
  204. else:
  205. pass
  206. try:
  207. ovfcheck(minusx-one)
  208. except OverflowError:
  209. assert False
  210. else:
  211. pass
  212. try:
  213. ovfcheck(x-x)
  214. except OverflowError:
  215. assert False
  216. else:
  217. pass
  218. try:
  219. ovfcheck(n-n)
  220. except OverflowError:
  221. assert False
  222. else:
  223. pass
  224. # overflowing
  225. try:
  226. ovfcheck(x+one)
  227. except OverflowError:
  228. pass
  229. else:
  230. assert False
  231. try:
  232. ovfcheck(x+x)
  233. except OverflowError:
  234. pass
  235. else:
  236. assert False
  237. try:
  238. ovfcheck(n-one)
  239. except OverflowError:
  240. pass
  241. else:
  242. assert False
  243. try:
  244. ovfcheck(n-y)
  245. except OverflowError:
  246. pass
  247. else:
  248. assert False
  249. def test_ovfcheck_float_to_int():
  250. assert ovfcheck_float_to_int(1.0) == 1
  251. assert ovfcheck_float_to_int(0.0) == 0
  252. assert ovfcheck_float_to_int(13.0) == 13
  253. assert ovfcheck_float_to_int(-1.0) == -1
  254. assert ovfcheck_float_to_int(-13.0) == -13
  255. # strange things happening for float to int on 64 bit:
  256. # int(float(i)) != i because of rounding issues
  257. x = sys.maxint
  258. while int(float(x)) > sys.maxint:
  259. x -= 1
  260. assert ovfcheck_float_to_int(float(x)) == int(float(x))
  261. x = sys.maxint + 1
  262. while int(float(x)) <= sys.maxint:
  263. x += 1
  264. py.test.raises(OverflowError, ovfcheck_float_to_int, x)
  265. x = -sys.maxint-1
  266. while int(float(x)) < -sys.maxint-1:
  267. x += 1
  268. assert ovfcheck_float_to_int(float(x)) == int(float(x))
  269. x = -sys.maxint-1
  270. while int(float(x)) >= -sys.maxint-1:
  271. x -= 1
  272. py.test.raises(OverflowError, ovfcheck_float_to_int, x)
  273. def test_abs():
  274. assert type(abs(r_longlong(1))) is r_longlong
  275. def test_r_singlefloat():
  276. x = r_singlefloat(2.5) # exact number
  277. assert float(x) == 2.5
  278. x = r_singlefloat(2.1) # approximate number, bits are lost
  279. assert float(x) != 2.1
  280. assert abs(float(x) - 2.1) < 1E-6
  281. def test_r_singlefloat_eq():
  282. x = r_singlefloat(2.5) # exact number
  283. y = r_singlefloat(2.5)
  284. assert x == y
  285. assert not x != y
  286. assert not x == 2.5
  287. assert x != 2.5
  288. py.test.raises(TypeError, "x>y")
  289. class TestRarithmetic(BaseRtypingTest):
  290. def test_compare_singlefloat_crashes(self):
  291. from rpython.rlib.rarithmetic import r_singlefloat
  292. from rpython.rtyper.error import MissingRTypeOperation
  293. def f(x):
  294. a = r_singlefloat(x)
  295. b = r_singlefloat(x+1)
  296. return a == b
  297. py.test.raises(MissingRTypeOperation, "self.interpret(f, [42.0])")
  298. def test_is_valid_int(self):
  299. def f(x):
  300. return (is_valid_int(x) * 4 +
  301. is_valid_int(x > 0) * 2 +
  302. is_valid_int(x + 0.5))
  303. assert f(123) == 4 + 2
  304. res = self.interpret(f, [123])
  305. assert res == 4 + 2
  306. def test_int_real_union():
  307. from rpython.rtyper.lltypesystem.rffi import r_int_real
  308. assert compute_restype(r_int_real, r_int_real) is r_int_real
  309. def test_compute_restype_incompatible():
  310. from rpython.rtyper.lltypesystem.rffi import r_int_real, r_short, r_ushort
  311. testcases = [(r_uint, r_longlong), (r_int_real, r_uint),
  312. (r_short, r_ushort)]
  313. for t1, t2 in testcases:
  314. py.test.raises(AssertionError, compute_restype, t1, t2)
  315. py.test.raises(AssertionError, compute_restype, t2, t1)
  316. def test_most_neg_value_of():
  317. assert most_neg_value_of_same_type(123) == -sys.maxint-1
  318. assert most_neg_value_of_same_type(r_uint(123)) == 0
  319. llmin = -(2**(r_longlong.BITS-1))
  320. assert most_neg_value_of_same_type(r_longlong(123)) == llmin
  321. assert most_neg_value_of_same_type(r_ulonglong(123)) == 0
  322. def test_most_pos_value_of():
  323. assert most_pos_value_of_same_type(123) == sys.maxint
  324. assert most_pos_value_of_same_type(r_uint(123)) == 2 * sys.maxint + 1
  325. llmax_sign = (2**(r_longlong.BITS-1))-1
  326. llmax_unsign = (2**r_longlong.BITS)-1
  327. assert most_pos_value_of_same_type(r_longlong(123)) == llmax_sign
  328. assert most_pos_value_of_same_type(r_ulonglong(123)) == llmax_unsign
  329. def test_is_signed_integer_type():
  330. from rpython.rtyper.lltypesystem import lltype, rffi
  331. assert is_signed_integer_type(lltype.Signed)
  332. assert is_signed_integer_type(rffi.SIGNEDCHAR)
  333. assert is_signed_integer_type(lltype.SignedLongLong)
  334. assert not is_signed_integer_type(lltype.Unsigned)
  335. assert not is_signed_integer_type(lltype.UnsignedLongLong)
  336. assert not is_signed_integer_type(lltype.Char)
  337. assert not is_signed_integer_type(lltype.UniChar)
  338. assert not is_signed_integer_type(lltype.Bool)
  339. def test_r_ulonglong():
  340. x = r_longlong(-1)
  341. y = r_ulonglong(x)
  342. assert long(y) == 2**r_ulonglong.BITS - 1
  343. def test_highest_bit():
  344. py.test.raises(AssertionError, highest_bit, 0)
  345. py.test.raises(AssertionError, highest_bit, 14)
  346. for i in xrange(31):
  347. assert highest_bit(2**i) == i
  348. def test_int_between():
  349. assert int_between(1, 1, 3)
  350. assert int_between(1, 2, 3)
  351. assert not int_between(1, 0, 2)
  352. assert not int_between(1, 5, 2)
  353. assert not int_between(1, 2, 2)
  354. assert not int_between(1, 1, 1)
  355. def test_int_force_ge_zero():
  356. assert int_force_ge_zero(42) == 42
  357. assert int_force_ge_zero(0) == 0
  358. assert int_force_ge_zero(-42) == 0
  359. @given(strategies.integers(min_value=0, max_value=sys.maxint),
  360. strategies.integers(min_value=1, max_value=sys.maxint))
  361. def test_int_c_div_mod(x, y):
  362. assert int_c_div(~x, y) == -(abs(~x) // y)
  363. assert int_c_div( x,-y) == -(x // y)
  364. if (x, y) == (sys.maxint, 1):
  365. py.test.skip("would overflow")
  366. assert int_c_div(~x,-y) == +(abs(~x) // y)
  367. for x1 in [x, ~x]:
  368. for y1 in [y, -y]:
  369. assert int_c_div(x1, y1) * y1 + int_c_mod(x1, y1) == x1
  370. # these can't be prebuilt on 32bit
  371. U1 = r_ulonglong(0x0102030405060708L)
  372. U2 = r_ulonglong(0x0807060504030201L)
  373. S1 = r_longlong(0x0102030405060708L)
  374. S2 = r_longlong(0x0807060504030201L)
  375. def test_byteswap():
  376. from rpython.rtyper.lltypesystem import rffi, lltype
  377. assert rffi.cast(lltype.Signed, byteswap(rffi.cast(rffi.USHORT, 0x0102))) == 0x0201
  378. assert rffi.cast(lltype.Signed, byteswap(rffi.cast(rffi.INT, 0x01020304))) == 0x04030201
  379. assert byteswap(U1) == U2
  380. assert byteswap(S1) == S2
  381. assert ((byteswap(2.3) - 1.903598566252326e+185) / 1e185) < 0.000001
  382. assert (rffi.cast(lltype.Float, byteswap(rffi.cast(lltype.SingleFloat, 2.3))) - 4.173496037651603e-08) < 1e-16
  383. def test_byteswap_interpret():
  384. interpret(test_byteswap, [])
  385. class TestStringToInt:
  386. def test_string_to_int(self):
  387. cases = [('0', 0),
  388. ('1', 1),
  389. ('9', 9),
  390. ('10', 10),
  391. ('09', 9),
  392. ('0000101', 101), # not octal unless base 0 or 8
  393. ('5123', 5123),
  394. (' 0', 0),
  395. ('0 ', 0),
  396. (' \t \n 32313 \f \v \r \n\r ', 32313),
  397. ('+12', 12),
  398. ('-5', -5),
  399. ('- 5', -5),
  400. ('+ 5', 5),
  401. (' -123456789 ', -123456789),
  402. ]
  403. for s, expected in cases:
  404. assert string_to_int(s) == expected
  405. #assert string_to_bigint(s).tolong() == expected
  406. def test_string_to_int_base(self):
  407. cases = [('111', 2, 7),
  408. ('010', 2, 2),
  409. ('102', 3, 11),
  410. ('103', 4, 19),
  411. ('107', 8, 71),
  412. ('109', 10, 109),
  413. ('10A', 11, 131),
  414. ('10a', 11, 131),
  415. ('10f', 16, 271),
  416. ('10F', 16, 271),
  417. ('0x10f', 16, 271),
  418. ('0x10F', 16, 271),
  419. ('10z', 36, 1331),
  420. ('10Z', 36, 1331),
  421. ('12', 0, 12),
  422. ('015', 0, 13),
  423. ('0x10', 0, 16),
  424. ('0XE', 0, 14),
  425. ('0', 0, 0),
  426. ('0b11', 2, 3),
  427. ('0B10', 2, 2),
  428. ('0o77', 8, 63),
  429. ]
  430. for s, base, expected in cases:
  431. assert string_to_int(s, base) == expected
  432. assert string_to_int('+'+s, base) == expected
  433. assert string_to_int('-'+s, base) == -expected
  434. assert string_to_int(s+'\n', base) == expected
  435. assert string_to_int(' +'+s, base) == expected
  436. assert string_to_int('-'+s+' ', base) == -expected
  437. def test_string_to_int_error(self):
  438. cases = ['0x123', # must use base 0 or 16
  439. ' 0X12 ',
  440. '0b01',
  441. '0o01',
  442. '',
  443. '++12',
  444. '+-12',
  445. '-+12',
  446. '--12',
  447. '12a6',
  448. '12A6',
  449. 'f',
  450. 'Z',
  451. '.',
  452. '@',
  453. ]
  454. for s in cases:
  455. py.test.raises(ParseStringError, string_to_int, s)
  456. py.test.raises(ParseStringError, string_to_int, ' '+s)
  457. py.test.raises(ParseStringError, string_to_int, s+' ')
  458. py.test.raises(ParseStringError, string_to_int, '+'+s)
  459. py.test.raises(ParseStringError, string_to_int, '-'+s)
  460. py.test.raises(ParseStringError, string_to_int, '0x', 16)
  461. py.test.raises(ParseStringError, string_to_int, '-0x', 16)
  462. exc = py.test.raises(ParseStringError, string_to_int, '')
  463. assert exc.value.msg == "invalid literal for int() with base 10"
  464. exc = py.test.raises(ParseStringError, string_to_int, '', 0)
  465. assert exc.value.msg == "invalid literal for int() with base 0"
  466. def test_string_to_int_overflow(self):
  467. import sys
  468. py.test.raises(ParseStringOverflowError, string_to_int,
  469. str(sys.maxint*17))
  470. def test_string_to_int_not_overflow(self):
  471. import sys
  472. for x in [-sys.maxint-1, sys.maxint]:
  473. y = string_to_int(str(x))
  474. assert y == x
  475. def test_string_to_int_base_error(self):
  476. cases = [('1', 1),
  477. ('1', 37),
  478. ('a', 0),
  479. ('9', 9),
  480. ('0x123', 7),
  481. ('145cdf', 15),
  482. ('12', 37),
  483. ('12', 98172),
  484. ('12', -1),
  485. ('12', -908),
  486. ('12.3', 10),
  487. ('12.3', 13),
  488. ('12.3', 16),
  489. ]
  490. for s, base in cases:
  491. py.test.raises(ParseStringError, string_to_int, s, base)
  492. py.test.raises(ParseStringError, string_to_int, ' '+s, base)
  493. py.test.raises(ParseStringError, string_to_int, s+' ', base)
  494. py.test.raises(ParseStringError, string_to_int, '+'+s, base)
  495. py.test.raises(ParseStringError, string_to_int, '-'+s, base)
  496. class TestExplicitIntsizes:
  497. _32_max = 2147483647
  498. _32_min = -2147483648
  499. _32_umax = 4294967295
  500. _64_max = 9223372036854775807
  501. _64_min = -9223372036854775808
  502. _64_umax = 18446744073709551615
  503. def test_explicit_32(self):
  504. assert type(r_int32(0)) == r_int32
  505. assert type(r_int32(self._32_max)) == r_int32
  506. assert type(r_int32(self._32_min)) == r_int32
  507. assert type(r_uint32(0)) == r_uint32
  508. assert type(r_uint32(self._32_umax)) == r_uint32
  509. with py.test.raises(OverflowError):
  510. ovfcheck(r_int32(self._32_max) + r_int32(1))
  511. ovfcheck(r_int32(self._32_min) - r_int32(1))
  512. assert most_pos_value_of_same_type(r_int32(1)) == self._32_max
  513. assert most_neg_value_of_same_type(r_int32(1)) == self._32_min
  514. assert most_pos_value_of_same_type(r_uint32(1)) == self._32_umax
  515. assert most_neg_value_of_same_type(r_uint32(1)) == 0
  516. assert r_uint32(self._32_umax) + r_uint32(1) == r_uint32(0)
  517. assert r_uint32(0) - r_uint32(1) == r_uint32(self._32_umax)
  518. def test_explicit_64(self):
  519. assert type(r_int64(0)) == r_int64
  520. assert type(r_int64(self._64_max)) == r_int64
  521. assert type(r_int64(self._64_min)) == r_int64
  522. assert type(r_uint64(0)) == r_uint64
  523. assert type(r_uint64(self._64_umax)) == r_uint64
  524. with py.test.raises(OverflowError):
  525. ovfcheck(r_int64(self._64_max) + r_int64(1))
  526. ovfcheck(r_int64(self._64_min) - r_int64(1))
  527. assert most_pos_value_of_same_type(r_int64(1)) == self._64_max
  528. assert most_neg_value_of_same_type(r_int64(1)) == self._64_min
  529. assert most_pos_value_of_same_type(r_uint64(1)) == self._64_umax
  530. assert most_neg_value_of_same_type(r_uint64(1)) == 0
  531. assert r_uint64(self._64_umax) + r_uint64(1) == r_uint64(0)
  532. assert r_uint64(0) - r_uint64(1) == r_uint64(self._64_umax)