/Lib/test/test_llvm.py

http://unladen-swallow.googlecode.com/ · Python · 4509 lines · 3623 code · 416 blank · 470 comment · 95 complexity · c6186551698179e045ff3bb4d270ec9f MD5 · raw file

Large files are truncated click here to view the full file

  1. # Tests for our minimal LLVM wrappers
  2. import __future__
  3. from test import test_dynamic
  4. from test import test_support
  5. try:
  6. import _llvm
  7. except ImportError:
  8. raise test_support.TestSkipped("not built against LLVM")
  9. import __builtin__
  10. import contextlib
  11. import functools
  12. import gc
  13. import sys
  14. import types
  15. import unittest
  16. import weakref
  17. # Calculate default LLVM optimization level.
  18. def _foo():
  19. pass
  20. DEFAULT_OPT_LEVEL = _foo.__code__.co_optimization
  21. del _foo
  22. # Various constants that feed into the hotness model.
  23. HOTNESS_CALL = 10 # Points for a function entry.
  24. HOTNESS_LOOP = 1 # Points for a taken loop backedge.
  25. JIT_SPIN_COUNT = _llvm.get_hotness_threshold() / HOTNESS_CALL + 1000
  26. JIT_OPT_LEVEL = sys.flags.optimize if sys.flags.optimize > 2 else 2
  27. @contextlib.contextmanager
  28. def set_jit_control(new_level):
  29. orig_level = _llvm.get_jit_control()
  30. _llvm.set_jit_control(new_level)
  31. try:
  32. yield
  33. finally:
  34. _llvm.set_jit_control(orig_level)
  35. def at_each_optimization_level(func):
  36. """Decorator for test functions, to run them at each optimization level."""
  37. levels = [None, -1, 0, 1, 2]
  38. if DEFAULT_OPT_LEVEL != -1:
  39. levels = [level for level in levels if level >= DEFAULT_OPT_LEVEL]
  40. @functools.wraps(func)
  41. def result(self):
  42. for level in levels:
  43. func(self, level)
  44. return result
  45. def compile_for_llvm(function_name, def_string, optimization_level=-1,
  46. globals_dict=None):
  47. """Compiles function_name, defined in def_string to be run through LLVM.
  48. Compiles and runs def_string in a temporary namespace, pulls the
  49. function named 'function_name' out of that namespace, optimizes it
  50. at level 'optimization_level', -1 for the default optimization,
  51. and marks it to be JITted and run through LLVM.
  52. """
  53. namespace = {}
  54. if globals_dict is None:
  55. globals_dict = globals()
  56. exec def_string in globals_dict, namespace
  57. func = namespace[function_name]
  58. if optimization_level is not None:
  59. if optimization_level >= DEFAULT_OPT_LEVEL:
  60. func.__code__.co_optimization = optimization_level
  61. func.__code__.co_use_jit = True
  62. return func
  63. def spin_until_hot(func, *training_args):
  64. """Compile a function by calling it until it is hot.
  65. Calls a function JIT_SPIN_COUNT times with each of training_args as
  66. arguments and returns a list containing the return values from each
  67. iteration. When testing feedback directed optimizations, this function is
  68. used to gather feedback in the code object before performaing JIT
  69. compilation.
  70. To inject different training arguments into the function while it is being
  71. spun up, you can pass multiple tuples of arguments to this function, like
  72. so:
  73. spin_until_hot(mul, [1, 3], [1.0, 3.0])
  74. This will cause the function to be trained on both integer and floating
  75. point inputs.
  76. """
  77. if not training_args: # An empty training_args isn't what you meant.
  78. training_args = [[]]
  79. results = []
  80. with set_jit_control("whenhot"):
  81. for _ in xrange(JIT_SPIN_COUNT):
  82. for args in training_args:
  83. results.append(func(*args))
  84. return results
  85. class ExtraAssertsTestCase(unittest.TestCase):
  86. def assertRaisesWithArgs(self, expected_exception_type,
  87. expected_args, f, *args, **kwargs):
  88. try:
  89. f(*args, **kwargs)
  90. except expected_exception_type, real_exception:
  91. pass
  92. else:
  93. self.fail("%r not raised" % expected_exception_type)
  94. self.assertEquals(real_exception.args, expected_args)
  95. def assertContains(self, obj, container):
  96. if obj not in container:
  97. self.fail("%r not found in %r" % (obj, container))
  98. def assertNotContains(self, obj, container):
  99. if obj in container:
  100. self.fail("%r found in %r" % (obj, container))
  101. class LlvmTestCase(unittest.TestCase):
  102. """Common base class for LLVM-focused tests.
  103. Features provided:
  104. - Assert that the code doesn't bail to the interpreter.
  105. """
  106. def setUp(self):
  107. sys.setbailerror(True)
  108. self._old_jit_control = _llvm.get_jit_control()
  109. _llvm.set_jit_control("whenhot")
  110. def tearDown(self):
  111. sys.setbailerror(False)
  112. _llvm.set_jit_control(self._old_jit_control)
  113. class GeneralCompilationTests(ExtraAssertsTestCase, LlvmTestCase):
  114. def test_uncreatable(self):
  115. # Functions can only be created by their static factories.
  116. self.assertRaises(TypeError, _llvm._function)
  117. def test_use_llvm(self):
  118. # Regression test: setting co_use_jit without setting an optimization
  119. # level used to segfault when the function was called.
  120. def foo():
  121. return 5
  122. foo.__code__.co_use_jit = True
  123. foo()
  124. @at_each_optimization_level
  125. def test_llvm_compile(self, level):
  126. # Makes no sense at level None
  127. if level is None:
  128. return
  129. def f(x):
  130. pass
  131. f = _llvm.compile(f.func_code, level)
  132. self.assertTrue(isinstance(f, _llvm._function))
  133. self.assertRaises(TypeError, _llvm.compile, f, level)
  134. def test_co_llvm(self):
  135. def f():
  136. return 1 + 2
  137. spin_until_hot(f, [])
  138. str_co_llvm = str(f.__code__.co_llvm)
  139. # After code objects are compiled to machine code, the IR form
  140. # is mostly cleared out. However, we want to be able to print
  141. # the IR generated for any particular function, so this tests
  142. # that it gets regenerated when we ask for its string
  143. # representation. The cleared-out form is around 5 lines
  144. # long, while all full functions are much longer.
  145. self.assertTrue(10 < len(str_co_llvm.split('\n')), msg=str_co_llvm)
  146. @at_each_optimization_level
  147. def test_run_simple_function(self, level):
  148. foo = compile_for_llvm("foo", """
  149. def foo():
  150. pass
  151. """, level)
  152. self.assertEquals(None, foo())
  153. @at_each_optimization_level
  154. def test_constants(self, level):
  155. foo = compile_for_llvm("foo", """
  156. def foo(x):
  157. if x: x[...]
  158. return [1, 2L, 3.2, 7j, (), "Hello", u"Hello", None]
  159. """, level)
  160. self.assertEquals([1, 2L, 3.2, 7j, (), "Hello", u"Hello", None],
  161. foo(False))
  162. def test_same_named_functions_coexist(self):
  163. foo1 = compile_for_llvm("foo", """
  164. def foo(a):
  165. return a
  166. """)
  167. foo2 = compile_for_llvm("foo", """
  168. def foo():
  169. return 7
  170. """)
  171. self.assertEquals("Hello", foo1("Hello"))
  172. self.assertEquals(7, foo2())
  173. def test_stack_pointer_optimized_to_register(self):
  174. def test_func():
  175. # We may have to add opcode uses to here as we find things
  176. # that break the stack pointer optimization.
  177. return sum(range(*[1, 10, 3]))
  178. # Run mem2reg.
  179. test_func.__code__.co_optimization = 2
  180. self.assertFalse("%stack_pointer_addr = alloca"
  181. in str(test_func.__code__.co_llvm))
  182. # -Xjit=always will cause this test to always fail.
  183. if _llvm.get_jit_control() != "always":
  184. def test_fetch_unset_co_llvm(self):
  185. def test_func():
  186. pass
  187. test_func.__code__.co_use_jit = True
  188. # Just setting co_use_jit doesn't force code generation.
  189. self.assertEqual(str(test_func.__code__.co_llvm), "None")
  190. @at_each_optimization_level
  191. def test_return_arg(self, level):
  192. foo = compile_for_llvm("foo", """
  193. def foo(a):
  194. return a
  195. """, level)
  196. self.assertEquals(3, foo(3))
  197. self.assertEquals("Hello", foo("Hello"))
  198. @at_each_optimization_level
  199. def test_unbound_local(self, level):
  200. foo = compile_for_llvm("foo", """
  201. def foo():
  202. a = a
  203. """, level)
  204. try:
  205. foo()
  206. except UnboundLocalError as e:
  207. self.assertEquals(
  208. str(e), "local variable 'a' referenced before assignment")
  209. else:
  210. self.fail("Expected UnboundLocalError")
  211. @at_each_optimization_level
  212. def test_assign(self, level):
  213. foo = compile_for_llvm("foo", """
  214. def foo(a):
  215. b = a
  216. return b
  217. """, level)
  218. self.assertEquals(3, foo(3))
  219. self.assertEquals("Hello", foo("Hello"))
  220. @at_each_optimization_level
  221. def test_raising_getiter(self, level):
  222. class RaisingIter(object):
  223. def __iter__(self):
  224. raise RuntimeError
  225. loop = compile_for_llvm("loop", """
  226. def loop(range):
  227. for i in range:
  228. pass
  229. """, level)
  230. self.assertRaises(RuntimeError, loop, RaisingIter())
  231. @at_each_optimization_level
  232. def test_raising_next(self, level):
  233. class RaisingNext(object):
  234. def __iter__(self):
  235. return self
  236. def next(self):
  237. raise RuntimeError
  238. loop = compile_for_llvm("loop", """
  239. def loop(range):
  240. for i in range:
  241. pass
  242. """, level)
  243. self.assertRaises(RuntimeError, loop, RaisingNext())
  244. @at_each_optimization_level
  245. def test_import_name(self, level):
  246. importer = compile_for_llvm("importer", """
  247. def importer():
  248. import os
  249. return os
  250. """, level)
  251. import os
  252. self.assertEqual(importer(), os)
  253. @at_each_optimization_level
  254. def test_loop(self, level):
  255. loop = compile_for_llvm("loop", """
  256. def loop(range):
  257. for i in range:
  258. pass
  259. """, level)
  260. r = iter(range(12))
  261. self.assertEquals(None, loop(r))
  262. self.assertRaises(StopIteration, next, r)
  263. @at_each_optimization_level
  264. def test_return_from_loop(self, level):
  265. loop = compile_for_llvm("loop", """
  266. def loop(range):
  267. for i in range:
  268. return i
  269. """, level)
  270. self.assertEquals(1, loop([1,2,3]))
  271. @at_each_optimization_level
  272. def test_finally(self, level):
  273. cleanup = compile_for_llvm("cleanup", """
  274. def cleanup(obj):
  275. try:
  276. return 3
  277. finally:
  278. obj['x'] = 2
  279. """, level)
  280. obj = {}
  281. self.assertEquals(3, cleanup(obj))
  282. self.assertEquals({'x': 2}, obj)
  283. @at_each_optimization_level
  284. def test_nested_finally(self, level):
  285. cleanup = compile_for_llvm("cleanup", """
  286. def cleanup(obj):
  287. try:
  288. try:
  289. return 3
  290. finally:
  291. obj['x'] = 2
  292. finally:
  293. obj['y'] = 3
  294. """, level)
  295. obj = {}
  296. self.assertEquals(3, cleanup(obj))
  297. self.assertEquals({'x': 2, 'y': 3}, obj)
  298. @at_each_optimization_level
  299. def test_finally_fallthrough(self, level):
  300. cleanup = compile_for_llvm("cleanup", """
  301. def cleanup(obj):
  302. try:
  303. obj['y'] = 3
  304. finally:
  305. obj['x'] = 2
  306. return 3
  307. """, level)
  308. obj = {}
  309. self.assertEquals(3, cleanup(obj))
  310. self.assertEquals({'x': 2, 'y': 3}, obj)
  311. @at_each_optimization_level
  312. def test_exception_out_of_finally(self, level):
  313. cleanup = compile_for_llvm("cleanup", """
  314. def cleanup(obj):
  315. try:
  316. obj['x'] = 2
  317. finally:
  318. a = a
  319. obj['y'] = 3
  320. return 3
  321. """, level)
  322. obj = {}
  323. self.assertRaises(UnboundLocalError, cleanup, obj)
  324. self.assertEquals({'x': 2}, obj)
  325. @at_each_optimization_level
  326. def test_exception_through_finally(self, level):
  327. cleanup = compile_for_llvm("cleanup", """
  328. def cleanup(obj):
  329. try:
  330. a = a
  331. finally:
  332. obj['x'] = 2
  333. """, level)
  334. obj = {}
  335. self.assertRaises(UnboundLocalError, cleanup, obj)
  336. self.assertEquals({'x': 2}, obj)
  337. @at_each_optimization_level
  338. def test_return_in_finally_overrides(self, level):
  339. cleanup = compile_for_llvm("cleanup", """
  340. def cleanup():
  341. try:
  342. return 3
  343. finally:
  344. return 2
  345. """, level)
  346. self.assertEquals(2, cleanup())
  347. @at_each_optimization_level
  348. def test_except(self, level):
  349. catch = compile_for_llvm("catch", """
  350. def catch(obj):
  351. try:
  352. raise ZeroDivisionError
  353. except:
  354. obj["x"] = 2
  355. """, level)
  356. obj = {}
  357. self.assertEquals(None, catch(obj))
  358. self.assertEquals({"x": 2}, obj)
  359. @at_each_optimization_level
  360. def test_filtered_except(self, level):
  361. catch = compile_for_llvm("catch", """
  362. def catch(exc_type, obj):
  363. try:
  364. 1 / 0
  365. except exc_type:
  366. obj["x"] = 2
  367. """, level)
  368. obj = {}
  369. self.assertEquals(None, catch(ZeroDivisionError, obj))
  370. self.assertEquals({"x": 2}, obj)
  371. obj = {}
  372. self.assertRaises(ZeroDivisionError, catch, UnboundLocalError, obj)
  373. self.assertEquals({}, obj)
  374. @at_each_optimization_level
  375. def test_filtered_except_var(self, level):
  376. catch = compile_for_llvm("catch", """
  377. def catch():
  378. try:
  379. 1 / 0
  380. except ZeroDivisionError, exc:
  381. return exc
  382. """, level)
  383. exc = catch()
  384. self.assertEquals(ZeroDivisionError, type(exc))
  385. self.assertEquals(('integer division or modulo by zero',), exc.args)
  386. @at_each_optimization_level
  387. def test_except_skipped_on_fallthrough(self, level):
  388. catch = compile_for_llvm("catch", """
  389. def catch(obj):
  390. try:
  391. obj["x"] = 2
  392. except:
  393. obj["y"] = 3
  394. return 7
  395. """, level)
  396. obj = {}
  397. self.assertEquals(7, catch(obj))
  398. self.assertEquals({"x": 2}, obj)
  399. @at_each_optimization_level
  400. def test_else_hit_on_fallthrough(self, level):
  401. catch = compile_for_llvm("catch", """
  402. def catch(obj):
  403. try:
  404. obj["x"] = 2
  405. except:
  406. obj["y"] = 3
  407. else:
  408. obj["z"] = 4
  409. return 7
  410. """, level)
  411. obj = {}
  412. self.assertEquals(7, catch(obj))
  413. self.assertEquals({"x": 2, "z": 4}, obj)
  414. @at_each_optimization_level
  415. def test_else_skipped_on_catch(self, level):
  416. catch = compile_for_llvm("catch", """
  417. def catch(obj):
  418. try:
  419. a = a
  420. except:
  421. obj["y"] = 3
  422. else:
  423. obj["z"] = 4
  424. return 7
  425. """, level)
  426. obj = {}
  427. self.assertEquals(7, catch(obj))
  428. self.assertEquals({"y": 3}, obj)
  429. @at_each_optimization_level
  430. def test_raise_from_except(self, level):
  431. catch = compile_for_llvm("catch", """
  432. def catch(obj):
  433. try:
  434. raise ZeroDivisionError
  435. except:
  436. a = a
  437. obj["x"] = 2
  438. """, level)
  439. obj = {}
  440. self.assertRaises(UnboundLocalError, catch, obj)
  441. self.assertEquals({}, obj)
  442. @at_each_optimization_level
  443. def test_nested_except(self, level):
  444. catch = compile_for_llvm("catch", """
  445. def catch(obj):
  446. try:
  447. try:
  448. 1 / 0
  449. except:
  450. obj["x"] = 2
  451. a = a
  452. except:
  453. obj["y"] = 3
  454. """, level)
  455. obj = {}
  456. self.assertEquals(None, catch(obj))
  457. self.assertEquals({"x": 2, "y": 3}, obj)
  458. @at_each_optimization_level
  459. def test_nested_except_skipped_on_fallthrough(self, level):
  460. catch = compile_for_llvm("catch", """
  461. def catch(obj):
  462. try:
  463. try:
  464. raise ZeroDivisionError
  465. except:
  466. obj["x"] = 2
  467. except:
  468. obj["y"] = 3
  469. """, level)
  470. obj = {}
  471. self.assertEquals(None, catch(obj))
  472. self.assertEquals({"x": 2}, obj)
  473. @at_each_optimization_level
  474. def test_nested_finally_doesnt_block_catch(self, level):
  475. # Raise from the try.
  476. catch = compile_for_llvm("catch", """
  477. def catch(obj):
  478. try:
  479. try:
  480. 1 / 0
  481. finally:
  482. obj["x"] = 2
  483. except:
  484. obj["y"] = 3
  485. """, level)
  486. obj = {}
  487. self.assertEquals(None, catch(obj))
  488. self.assertEquals({"x": 2, "y": 3}, obj)
  489. # And raise from the finally.
  490. catch = compile_for_llvm("catch", """
  491. def catch(obj):
  492. try:
  493. try:
  494. obj["x"] = 2
  495. finally:
  496. raise ZeroDivisionError
  497. except:
  498. obj["y"] = 3
  499. """, level)
  500. obj = {}
  501. self.assertEquals(None, catch(obj))
  502. self.assertEquals({"x": 2, "y": 3}, obj)
  503. @at_each_optimization_level
  504. def test_nested_except_goes_through_finally(self, level):
  505. # Raise from the try.
  506. catch = compile_for_llvm("catch", """
  507. def catch(obj):
  508. try:
  509. try:
  510. 1 / 0
  511. except:
  512. obj["x"] = 2
  513. finally:
  514. obj["y"] = 3
  515. """, level)
  516. obj = {}
  517. self.assertEquals(None, catch(obj))
  518. self.assertEquals({"x": 2, "y": 3}, obj)
  519. # And raise from the except.
  520. catch = compile_for_llvm("catch", """
  521. def catch(obj):
  522. try:
  523. try:
  524. raise UnboundLocalError
  525. except:
  526. 1 / 0
  527. finally:
  528. obj["y"] = 3
  529. """, level)
  530. obj = {}
  531. self.assertRaises(ZeroDivisionError, catch, obj)
  532. self.assertEquals({"y": 3}, obj)
  533. @at_each_optimization_level
  534. def test_finally_in_finally(self, level):
  535. catch = compile_for_llvm("catch", """
  536. def catch(obj):
  537. try:
  538. raise ZeroDivisionError
  539. finally:
  540. try:
  541. a = a
  542. finally:
  543. obj["x"] = 2
  544. """, level)
  545. obj = {}
  546. self.assertRaises(UnboundLocalError, catch, obj)
  547. self.assertEquals({"x": 2}, obj)
  548. @at_each_optimization_level
  549. def test_subexception_caught_in_finally(self, level):
  550. catch = compile_for_llvm("catch", """
  551. def catch(obj):
  552. try:
  553. 1 / 0
  554. finally:
  555. try:
  556. a = a
  557. except:
  558. obj["x"] = 2
  559. """, level)
  560. obj = {}
  561. self.assertRaises(ZeroDivisionError, catch, obj)
  562. self.assertEquals({"x": 2}, obj)
  563. @at_each_optimization_level
  564. def test_delete_fast(self, level):
  565. delit = compile_for_llvm('delit', """
  566. def delit(x):
  567. y = 2
  568. z = 3
  569. del y
  570. del x
  571. return z
  572. """, level)
  573. self.assertEquals(delit(1), 3)
  574. useit = compile_for_llvm('useit', """
  575. def useit(x):
  576. del x
  577. return x
  578. """, level)
  579. self.assertRaises(UnboundLocalError, useit, 1)
  580. misuseit = compile_for_llvm('misuseit', 'def misuseit(x): del y',
  581. level)
  582. self.assertRaises(UnboundLocalError, misuseit, 1)
  583. reuseit = compile_for_llvm('reuseit', """
  584. def reuseit(x):
  585. del x
  586. x = 3
  587. return x
  588. """, level)
  589. self.assertEquals(reuseit(1), 3)
  590. @at_each_optimization_level
  591. def test_call_function(self, level):
  592. f1 = compile_for_llvm("f1", "def f1(x): return x()", level)
  593. self.assertEquals(f1(lambda: 5), 5)
  594. def raise_exc():
  595. raise ValueError
  596. self.assertRaises(ValueError, f1, raise_exc)
  597. f2 = compile_for_llvm("f2", "def f2(x, y, z): return x(y, 2, z)",
  598. level)
  599. self.assertEquals(f2(lambda *args: args, 1, 3), (1, 2, 3))
  600. f3 = compile_for_llvm("f3", "def f3(x, y, z): return x(y(z()))",
  601. level)
  602. self.assertEquals(f3(lambda x: x+1, lambda x: x+2, lambda: 0), 3)
  603. @at_each_optimization_level
  604. def test_load_global(self, level):
  605. our_globals = dict(globals()) # Isolate the test's global effects.
  606. testvalue = 'test global value'
  607. loadglobal = compile_for_llvm('loadglobal',
  608. 'def loadglobal(): return testvalue',
  609. level, our_globals)
  610. our_globals['testvalue'] = testvalue
  611. self.assertEquals(loadglobal(), testvalue)
  612. loadbuiltin = compile_for_llvm('loadbuiltin',
  613. 'def loadbuiltin(): return str',
  614. level)
  615. self.assertEquals(loadbuiltin(), str)
  616. nosuchglobal = compile_for_llvm('nosuchglobal', '''
  617. def nosuchglobal():
  618. return there_better_be_no_such_global
  619. ''', level)
  620. self.assertRaises(NameError, nosuchglobal)
  621. @at_each_optimization_level
  622. def test_store_global(self, level):
  623. our_globals = dict(globals()) # Isolate the test's global effects.
  624. setglobal = compile_for_llvm('setglobal', '''
  625. def setglobal(x):
  626. global _test_global
  627. _test_global = x
  628. ''', level, our_globals)
  629. testvalue = "test global value"
  630. self.assertTrue('_test_global' not in our_globals)
  631. setglobal(testvalue)
  632. self.assertContains('_test_global', our_globals)
  633. self.assertEquals(our_globals['_test_global'], testvalue)
  634. @at_each_optimization_level
  635. def test_delete_global(self, level):
  636. our_globals = dict(globals()) # Isolate the test's global effects.
  637. delglobal = compile_for_llvm('delglobal', '''
  638. def delglobal():
  639. global _test_global
  640. del _test_global
  641. ''', level, our_globals)
  642. our_globals['_test_global'] = 'test global value'
  643. self.assertContains('_test_global', our_globals)
  644. delglobal()
  645. self.assertTrue('_test_global' not in our_globals)
  646. @at_each_optimization_level
  647. def test_load_name(self, level):
  648. our_globals = dict(globals()) # Isolate the test's global effects.
  649. testvalue = 'test name value'
  650. loadlocal = compile_for_llvm('loadlocal', '''
  651. def loadlocal():
  652. exec 'testvalue = "Hello"'
  653. return testvalue
  654. ''', level, our_globals)
  655. our_globals['testvalue'] = testvalue
  656. self.assertEquals(loadlocal(), 'Hello')
  657. our_globals = dict(globals())
  658. loadglobal = compile_for_llvm('loadglobal', '''
  659. def loadglobal():
  660. exec ''
  661. return testvalue
  662. ''', level, our_globals)
  663. our_globals['testvalue'] = testvalue
  664. self.assertEquals(loadglobal(), testvalue)
  665. loadbuiltin = compile_for_llvm('loadbuiltin', '''
  666. def loadbuiltin():
  667. exec ''
  668. return str
  669. ''', level)
  670. self.assertEquals(loadbuiltin(), str)
  671. nosuchname = compile_for_llvm('nosuchname', '''
  672. def nosuchname():
  673. exec ''
  674. return there_better_be_no_such_name
  675. ''', level)
  676. self.assertRaises(NameError, nosuchname)
  677. @at_each_optimization_level
  678. def test_store_name(self, level):
  679. set_local = compile('a = 3', '<string>', 'exec')
  680. if level is not None:
  681. set_local.co_optimization = level
  682. set_local.co_use_jit = True
  683. exec set_local
  684. self.assertEquals(a, 3)
  685. @at_each_optimization_level
  686. def test_delete_name(self, level):
  687. do_del = compile('del a', '<string>', 'exec')
  688. if level is not None:
  689. do_del.co_optimization = level
  690. do_del.co_use_jit = True
  691. exec 'a = 3'
  692. self.assertEquals(a, 3)
  693. exec do_del
  694. try:
  695. a
  696. except NameError:
  697. pass
  698. else:
  699. self.fail('Expected "a" to be deleted')
  700. try:
  701. exec compile('del nonexistent', '<string>', 'exec')
  702. except NameError, e:
  703. self.assertEquals(e.args, ('name \'nonexistent\' is not defined',))
  704. else:
  705. self.fail('Expected not to find "nonexistent"')
  706. @at_each_optimization_level
  707. def test_simple_if_stmt(self, level):
  708. simple_if = compile_for_llvm("simple_if", """
  709. def simple_if(x):
  710. if x:
  711. return "true"
  712. """, level)
  713. self.assertEquals(simple_if(True), "true")
  714. self.assertEquals(simple_if(False), None)
  715. simple_if_else = compile_for_llvm("simple_if_else", """
  716. def simple_if_else(x):
  717. if x:
  718. return "true"
  719. else:
  720. return "false"
  721. """, level)
  722. self.assertEquals(simple_if_else("not false"), "true")
  723. self.assertEquals(simple_if_else(""), "false")
  724. @at_each_optimization_level
  725. def test_if_stmt_exceptions(self, level):
  726. if_exception = compile_for_llvm("if_exception", """
  727. def if_exception(x):
  728. if x:
  729. return 1
  730. """, level)
  731. class Unboolable(object):
  732. def __nonzero__(self):
  733. raise RuntimeError
  734. self.assertRaises(RuntimeError, if_exception, Unboolable())
  735. @at_each_optimization_level
  736. def test_complex_if(self, level):
  737. complex_if = compile_for_llvm("complex_if", """
  738. def complex_if(x, y, z):
  739. if x:
  740. if y:
  741. return 1
  742. else:
  743. if z:
  744. return 2
  745. return 1 / 0
  746. else:
  747. return 3
  748. """, level)
  749. self.assertEquals(complex_if(True, True, False), 1)
  750. self.assertEquals(complex_if(True, False, True), 2)
  751. self.assertEquals(complex_if(False, True, True), 3)
  752. self.assertRaises(ZeroDivisionError, complex_if, True, False, False)
  753. # Asserts aren't compiled when -O is passed.
  754. if sys.flags.optimize < 1:
  755. @at_each_optimization_level
  756. def test_assert(self, level):
  757. f = compile_for_llvm("f", "def f(x): assert x", level)
  758. self.assertEquals(f(1), None)
  759. self.assertRaises(AssertionError, f, 0)
  760. @at_each_optimization_level
  761. def test_and(self, level):
  762. and1 = compile_for_llvm("and1",
  763. "def and1(x, y): return x and y", level)
  764. self.assertEquals(and1("x", "y"), "y")
  765. self.assertEquals(and1((), "y"), ())
  766. self.assertEquals(and1((), ""), ())
  767. and2 = compile_for_llvm("and2",
  768. "def and2(x, y): return x+1 and y+1",
  769. level)
  770. self.assertEquals(and2(-1, "5"), 0)
  771. self.assertRaises(TypeError, and2, "5", 5)
  772. self.assertRaises(TypeError, and2, 5, "5")
  773. @at_each_optimization_level
  774. def test_or(self, level):
  775. or1 = compile_for_llvm("or1", "def or1(x, y): return x or y", level)
  776. self.assertEquals(or1("x", "y"), "x")
  777. self.assertEquals(or1((), "y"), "y")
  778. self.assertEquals(or1((), ""), "")
  779. or2 = compile_for_llvm("or2",
  780. "def or2(x, y): return x+1 or y+1", level)
  781. self.assertEquals(or2(5, "5"), 6)
  782. self.assertRaises(TypeError, or2, "5", 5)
  783. self.assertRaises(TypeError, or2, -1, "5")
  784. @at_each_optimization_level
  785. def test_complex_or(self, level):
  786. complex_or = compile_for_llvm('complex_or', '''
  787. def complex_or(a, b, c):
  788. return a or b or c
  789. ''', level)
  790. self.assertEquals(complex_or(1, 2, 0), 1)
  791. self.assertEquals(complex_or(1, 2, 3), 1)
  792. self.assertEquals(complex_or(3, 0, 0), 3)
  793. self.assertEquals(complex_or(0, 3, 0), 3)
  794. self.assertEquals(complex_or(0, 0, 1), 1)
  795. self.assertEquals(complex_or(0, 0, 0), 0)
  796. complex_or_and = compile_for_llvm('complex_or_and', '''
  797. def complex_or_and(a, b, c):
  798. return a or b and c
  799. ''', level)
  800. self.assertEquals(complex_or_and(3, 0, 0), 3)
  801. self.assertEquals(complex_or_and("", 3, 0), 0)
  802. self.assertEquals(complex_or_and("", 0, 1), 0)
  803. self.assertEquals(complex_or_and(0, 3, 1), 1)
  804. @at_each_optimization_level
  805. def test_complex_and(self, level):
  806. complex_and = compile_for_llvm('complex_and', '''
  807. def complex_and(a, b, c):
  808. return a and b and c
  809. ''', level)
  810. self.assertEquals(complex_and(3, 0, ""), 0)
  811. self.assertEquals(complex_and(3, 2, 0), 0)
  812. self.assertEquals(complex_and(3, 2, 1), 1)
  813. self.assertEquals(complex_and(0, 3, 2), 0)
  814. self.assertEquals(complex_and(3, 0, 2), 0)
  815. complex_and_or = compile_for_llvm('complex_and_or', '''
  816. def complex_and_or(a, b, c):
  817. return a and b or c
  818. ''', level)
  819. self.assertEquals(complex_and_or(3, "", 0), 0)
  820. self.assertEquals(complex_and_or(1, 3, 0), 3)
  821. self.assertEquals(complex_and_or(1, 3, 2), 3)
  822. self.assertEquals(complex_and_or(0, 3, 1), 1)
  823. @at_each_optimization_level
  824. def test_break(self, level):
  825. break_one = compile_for_llvm("break_one", """
  826. def break_one(x):
  827. for y in [1, 2]:
  828. x["break"] = y
  829. break
  830. x["post break"] = y
  831. else:
  832. x["else"] = True
  833. return x
  834. """, level)
  835. self.assertEqual(break_one({}), {"break": 1})
  836. nested = compile_for_llvm("nested", """
  837. def nested(x):
  838. for y in [1, 2]:
  839. for z in [3, 4]:
  840. x["break"] = z
  841. break
  842. x["post break"] = z
  843. else:
  844. x["inner else"] = True
  845. x["outer"] = y
  846. else:
  847. x["else"] = True
  848. return x
  849. """, level)
  850. self.assertEqual(nested({}), {"break": 3, "outer": 2, "else": True})
  851. @at_each_optimization_level
  852. def test_continue(self, level):
  853. # CONTINUE_LOOP is only used inside a try/except block. Otherwise,
  854. # the continue statement is lowered to a JUMP_ABSOLUTE.
  855. continue_one = compile_for_llvm("continue_one", """
  856. def continue_one(x):
  857. for y in [1, 2]:
  858. if y:
  859. x["continue"] = y
  860. try:
  861. continue
  862. except:
  863. pass
  864. finally:
  865. x["finally"] = y
  866. 1 / 0
  867. else:
  868. x["else"] = True
  869. return x
  870. """, level)
  871. self.assertEqual(continue_one({}), {"continue": 2, "else": True,
  872. "finally": 2})
  873. nested = compile_for_llvm("nested", """
  874. def nested(x):
  875. for y in [1, 2]:
  876. for z in [3, 4]:
  877. if z:
  878. x["continue"] = z
  879. try:
  880. continue
  881. except:
  882. pass
  883. 1 / 0
  884. else:
  885. x["inner else"] = True
  886. x["outer"] = y
  887. else:
  888. x["else"] = True
  889. return x
  890. """, level)
  891. self.assertEqual(nested({}), {"continue": 4, "outer": 2,
  892. "inner else": True, "else": True})
  893. @at_each_optimization_level
  894. def test_load_attr(self, level):
  895. load_attr = compile_for_llvm('load_attr',
  896. 'def load_attr(o): return o.attr',
  897. level)
  898. load_attr.attr = 1
  899. self.assertEquals(load_attr(load_attr), 1)
  900. self.assertRaises(AttributeError, load_attr, object())
  901. @at_each_optimization_level
  902. def test_store_attr(self, level):
  903. store_attr = compile_for_llvm('store_attr',
  904. 'def store_attr(o): o.attr = 2',
  905. level)
  906. store_attr(store_attr)
  907. self.assertEquals(store_attr.attr, 2)
  908. self.assertRaises(AttributeError, store_attr, object())
  909. @at_each_optimization_level
  910. def test_delete_attr(self, level):
  911. delete_attr = compile_for_llvm('delete_attr',
  912. 'def delete_attr(o): del o.attr',
  913. level)
  914. delete_attr.attr = 3
  915. delete_attr(delete_attr)
  916. self.assertFalse(hasattr(delete_attr, 'attr'))
  917. self.assertRaises(AttributeError, delete_attr, object())
  918. @at_each_optimization_level
  919. def test_call_varargs(self, level):
  920. f1 = compile_for_llvm("f1", "def f1(x, args): return x(*args)",
  921. level)
  922. def receiver1(a, b):
  923. return a, b
  924. self.assertEquals(f1(receiver1, (1, 2)), (1, 2))
  925. self.assertRaises(TypeError, f1, receiver1, None)
  926. self.assertRaises(TypeError, f1, None, (1, 2))
  927. f2 = compile_for_llvm("f2",
  928. "def f2(x, args): return x(1, 2, *args)",
  929. level)
  930. def receiver2(a, *args):
  931. return a, args
  932. self.assertEquals(f2(receiver2, (3, 4, 5)), (1, (2, 3, 4, 5)))
  933. @at_each_optimization_level
  934. def test_call_kwargs(self, level):
  935. f = compile_for_llvm("f",
  936. "def f(x, kwargs): return x(a=1, **kwargs)",
  937. level)
  938. def receiver(**kwargs):
  939. return kwargs
  940. self.assertEquals(f(receiver, {'b': 2, 'c': 3}),
  941. {'a': 1, 'b': 2, 'c': 3})
  942. @at_each_optimization_level
  943. def test_call_args_kwargs(self, level):
  944. f = compile_for_llvm("f", """
  945. def f(x, args, kwargs):
  946. return x(1, d=4, *args, **kwargs)
  947. """, level)
  948. def receiver(*args, **kwargs):
  949. return args, kwargs
  950. self.assertEquals(f(receiver, (2, 3), {'e': 5, 'f': 6}),
  951. ((1, 2, 3), {'d': 4, 'e': 5, 'f': 6}))
  952. @at_each_optimization_level
  953. def test_varargs_func(self, level):
  954. f = compile_for_llvm("f", """
  955. def f(*args):
  956. return zip(*args)
  957. """, level)
  958. self.assertEqual(f([1], [2]), [(1, 2)])
  959. @at_each_optimization_level
  960. def test_kwargs_func(self, level):
  961. f = compile_for_llvm("f", """
  962. def f(**kwargs):
  963. return dict(**kwargs)
  964. """, level)
  965. self.assertEqual(f(a=3), {"a": 3})
  966. @at_each_optimization_level
  967. def test_build_slice(self, level):
  968. class Sliceable(object):
  969. def __getitem__(self, item):
  970. return item
  971. # Test BUILD_SLICE_TWO; make sure we didn't swap arguments.
  972. slice_two = compile_for_llvm('slice_two',
  973. 'def slice_two(o): return o[1:2:]',
  974. level)
  975. self.assertEquals(slice_two(Sliceable()), slice(1, 2, None))
  976. # Test BUILD_SLICE_THREE.
  977. slice_three = compile_for_llvm('slice_three',
  978. 'def slice_three(o): return o[1:2:3]',
  979. level)
  980. self.assertEquals(slice_three(Sliceable()), slice(1, 2, 3))
  981. # No way to make BUILD_SLICE_* raise exceptions.
  982. @at_each_optimization_level
  983. def test_with(self, level):
  984. class SimpleCM(object):
  985. def __enter__(self):
  986. self.enter = True
  987. def __exit__(self, *exc_info):
  988. self.exit = True
  989. with_simple = compile_for_llvm('with_simple', '''
  990. def with_simple(self, x):
  991. with x:
  992. self.assertEqual(x.__dict__, {"enter": True})
  993. self.assertEqual(x.__dict__, {"enter": True, "exit": True})
  994. ''', level)
  995. with_simple(self, SimpleCM())
  996. with_raise = compile_for_llvm('with_raise', '''
  997. def with_raise(self, x):
  998. with x:
  999. self.assertEqual(x.__dict__, {"enter": True})
  1000. raise ArithmeticError
  1001. ''', level)
  1002. x = SimpleCM()
  1003. self.assertRaises(ArithmeticError, with_raise, self, x)
  1004. self.assertEqual(x.__dict__, {'enter': True, 'exit': True})
  1005. with_return = compile_for_llvm('with_return', '''
  1006. def with_return(self, x):
  1007. with x:
  1008. self.assertEqual(x.__dict__, {"enter": True})
  1009. return 55
  1010. ''', level)
  1011. x = SimpleCM()
  1012. self.assertEqual(with_return(self, x), 55)
  1013. self.assertEqual(x.__dict__, {'enter': True, 'exit': True})
  1014. class SwallowingCM(object):
  1015. def __enter__(self):
  1016. self.enter = True
  1017. def __exit__(self, *exc_info):
  1018. self.exit = True
  1019. return True # Swallow the raised exception
  1020. with_swallow = compile_for_llvm('with_swallow', '''
  1021. def with_swallow(self, x):
  1022. with x:
  1023. self.assertEqual(x.__dict__, {"enter": True})
  1024. raise ArithmeticError
  1025. return 55
  1026. ''', level)
  1027. x = SwallowingCM()
  1028. self.assertEqual(with_swallow(self, x), 55)
  1029. self.assertEqual(x.__dict__, {'enter': True, 'exit': True})
  1030. class BustedExitCM(object):
  1031. def __enter__(self):
  1032. self.enter = True
  1033. def __exit__(self, *exc_info):
  1034. self.exit = True
  1035. class A(object):
  1036. def __nonzero__(self):
  1037. raise ArithmeticError
  1038. return A() # Test error paths in WITH_CLEANUP
  1039. with_ignored_bad_exit = compile_for_llvm('with_ignored_bad_exit', '''
  1040. def with_ignored_bad_exit(self, x):
  1041. with x:
  1042. self.assertEqual(x.__dict__, {"enter": True})
  1043. return 55
  1044. ''', level)
  1045. x = BustedExitCM()
  1046. self.assertEqual(with_ignored_bad_exit(self, x), 55)
  1047. self.assertEqual(x.__dict__, {'enter': True, 'exit': True})
  1048. with_bad_exit = compile_for_llvm('with_bad_exit', '''
  1049. def with_bad_exit(self, x):
  1050. with x:
  1051. self.assertEqual(x.__dict__, {"enter": True})
  1052. raise KeyError
  1053. return 55
  1054. ''', level)
  1055. x = BustedExitCM()
  1056. self.assertRaises(ArithmeticError, with_bad_exit, self, x)
  1057. self.assertEqual(x.__dict__, {'enter': True, 'exit': True})
  1058. class RaisingCM(object):
  1059. def __enter__(self):
  1060. self.enter = True
  1061. def __exit__(self, *exc_info):
  1062. self.exit = True
  1063. raise ArithmeticError
  1064. with_error = compile_for_llvm('with_error', '''
  1065. def with_error(self, x):
  1066. with x:
  1067. return 55
  1068. ''', level)
  1069. x = RaisingCM()
  1070. self.assertRaises(ArithmeticError, with_error, self, x)
  1071. self.assertEqual(x.__dict__, {'enter': True, 'exit': True})
  1072. class NestedCM(object):
  1073. def __init__(self):
  1074. self.enter = 0
  1075. self.exit = 0
  1076. def __enter__(self):
  1077. self.enter += 1
  1078. def __exit__(self, *exc_info):
  1079. self.exit += 1
  1080. with_yield = compile_for_llvm('with_yield', '''
  1081. def with_yield(self, x):
  1082. with x:
  1083. self.assertEqual(x.__dict__, {"enter": 1, "exit": 0})
  1084. yield 7
  1085. self.assertEqual(x.__dict__, {"enter": 1, "exit": 0})
  1086. yield 8
  1087. self.assertEqual(x.__dict__, {"enter": 1, "exit": 1})
  1088. ''', level)
  1089. x = NestedCM()
  1090. self.assertEqual(list(with_yield(self, x)), [7, 8])
  1091. with_nested = compile_for_llvm('with_nested', '''
  1092. def with_nested(self, x):
  1093. with x:
  1094. self.assertEqual(x.__dict__, {"enter": 1, "exit": 0})
  1095. with x:
  1096. self.assertEqual(x.__dict__, {"enter": 2, "exit": 0})
  1097. self.assertEqual(x.__dict__, {"enter": 2, "exit": 1})
  1098. self.assertEqual(x.__dict__, {"enter": 2, "exit": 2})
  1099. ''', level)
  1100. x = NestedCM()
  1101. with_nested(self, x)
  1102. @at_each_optimization_level
  1103. def test_raise(self, level):
  1104. raise_onearg = compile_for_llvm('raise_onearg', '''
  1105. def raise_onearg(x):
  1106. raise x
  1107. ''', level)
  1108. self.assertRaises(OpExc, raise_onearg, OpExc);
  1109. raise_twoargs = compile_for_llvm('raise_twoargs', '''
  1110. def raise_twoargs(x, y):
  1111. raise x, y
  1112. ''', level)
  1113. self.assertRaisesWithArgs(OpExc, ('twoarg',),
  1114. raise_twoargs, OpExc, OpExc('twoarg'));
  1115. @at_each_optimization_level
  1116. def test_reraise(self, level):
  1117. raise_noargs = compile_for_llvm('raise_noargs', '''
  1118. def raise_noargs():
  1119. raise
  1120. ''', level)
  1121. exc = OpExc('exc')
  1122. def setup_traceback(e):
  1123. raise e
  1124. try:
  1125. setup_traceback(exc)
  1126. except OpExc:
  1127. # orig_tb and exc re-used for raise_threeargs.
  1128. orig_tb = sys.exc_info()[2]
  1129. try:
  1130. raise_noargs()
  1131. except OpExc, e:
  1132. new_tb = sys.exc_info()[2]
  1133. # Test that we got the right exception and the right
  1134. # traceback. Test both equality and identity for more
  1135. # convenient error displays when things aren't as expected.
  1136. self.assertEquals(e, exc)
  1137. self.assertTrue(e is exc)
  1138. self.assertEquals(new_tb.tb_next, orig_tb)
  1139. self.assertTrue(new_tb.tb_next is orig_tb)
  1140. else:
  1141. self.fail('expected OpExc exception')
  1142. else:
  1143. self.fail('expected OpExc exception')
  1144. raise_threeargs = compile_for_llvm('raise_threeargs', '''
  1145. def raise_threeargs(x, y, z):
  1146. raise x, y, z
  1147. ''', level)
  1148. # Explicit version of the no-args raise.
  1149. try:
  1150. # Re-using exc and orig_tb from raise_noargs.
  1151. raise_threeargs(OpExc, exc, orig_tb)
  1152. except OpExc, e:
  1153. new_tb = sys.exc_info()[2]
  1154. self.assertEquals(e, exc)
  1155. self.assertTrue(e is exc)
  1156. self.assertEquals(new_tb.tb_next, orig_tb)
  1157. self.assertTrue(new_tb.tb_next is orig_tb)
  1158. else:
  1159. self.fail('expected OpExc exception')
  1160. @at_each_optimization_level
  1161. def test_complex_reraise(self, level):
  1162. reraise = compile_for_llvm('reraise', '''
  1163. def reraise(raiser, exctype):
  1164. try:
  1165. raiser()
  1166. except:
  1167. try:
  1168. raise
  1169. except exctype:
  1170. return "inner"
  1171. return "middle"
  1172. return "outer"
  1173. ''', level)
  1174. def raiser():
  1175. raise ZeroDivisionError
  1176. self.assertEquals(reraise(raiser, ZeroDivisionError),
  1177. "inner")
  1178. self.assertRaises(ZeroDivisionError, reraise, raiser, TypeError)
  1179. @at_each_optimization_level
  1180. def test_simple_yield(self, level):
  1181. generator = compile_for_llvm("generator", """
  1182. def generator():
  1183. yield 1
  1184. yield 2
  1185. yield 3
  1186. """, level)
  1187. g = generator()
  1188. self.assertEquals(1, g.next())
  1189. self.assertEquals(2, g.next())
  1190. self.assertEquals(3, g.next())
  1191. self.assertRaises(StopIteration, g.next)
  1192. @at_each_optimization_level
  1193. def test_yield_in_loop(self, level):
  1194. generator = compile_for_llvm("generator", """
  1195. def generator(x):
  1196. for i in x:
  1197. yield i
  1198. """, level)
  1199. g = generator([1, 2, 3, 4])
  1200. self.assertEquals([1, 2, 3, 4], list(g))
  1201. cross_product = compile_for_llvm("cross_product", """
  1202. def cross_product(x, y):
  1203. for i in x:
  1204. for j in y:
  1205. yield (i, j)
  1206. """, level)
  1207. g = cross_product([1, 2], [3, 4])
  1208. self.assertEquals([(1,3), (1,4), (2,3), (2,4)], list(g))
  1209. @at_each_optimization_level
  1210. def test_yield_saves_block_stack(self, level):
  1211. generator = compile_for_llvm("generator", """
  1212. def generator(x):
  1213. yield "starting"
  1214. for i in x:
  1215. try:
  1216. try:
  1217. 1 / i
  1218. yield ("survived", i)
  1219. finally:
  1220. yield ("finally", i)
  1221. except ZeroDivisionError:
  1222. yield "caught exception"
  1223. yield "done looping"
  1224. """, level)
  1225. self.assertEquals(list(generator([0, 1, 2])),
  1226. ["starting",
  1227. ("finally", 0),
  1228. "caught exception",
  1229. ("survived", 1),
  1230. ("finally", 1),
  1231. ("survived", 2),
  1232. ("finally", 2),
  1233. "done looping"])
  1234. @at_each_optimization_level
  1235. def test_generator_send(self, level):
  1236. generator = compile_for_llvm("generator", """
  1237. def generator():
  1238. yield (yield 1)
  1239. """, level)
  1240. g = generator()
  1241. self.assertEquals(1, g.next())
  1242. self.assertEquals("Hello world", g.send("Hello world"))
  1243. self.assertRaises(StopIteration, g.send, 3)
  1244. @at_each_optimization_level
  1245. def test_generator_throw(self, level):
  1246. generator = compile_for_llvm("generator", """
  1247. def generator(obj):
  1248. try:
  1249. yield "starting"
  1250. except ArithmeticError:
  1251. obj["caught"] = 1
  1252. finally:
  1253. obj["finally"] = 1
  1254. yield "done"
  1255. """, level)
  1256. obj = {}
  1257. g = generator(obj)
  1258. self.assertEquals("starting", g.next())
  1259. self.assertEquals("done", g.throw(ArithmeticError))
  1260. self.assertEquals(None, g.close())
  1261. self.assertEquals({"caught": 1, "finally": 1}, obj)
  1262. obj = {}
  1263. g = generator(obj)
  1264. self.assertEquals("starting", g.next())
  1265. self.assertRaises(UnboundLocalError, g.throw, UnboundLocalError)
  1266. self.assertRaises(StopIteration, g.next)
  1267. self.assertEquals({"finally": 1}, obj)
  1268. # Getting this to work under -Xjit=always is a pain in the ass, and not
  1269. # worth the effort IMHO.
  1270. if _llvm.get_jit_control() != "always":
  1271. def test_toggle_generator(self):
  1272. # Toggling between native code and the interpreter between yields
  1273. # used to cause crashes because f_lasti doesn't get translated
  1274. # between the scheme used for LLVM and the scheme used for the
  1275. # interpreter. Currently, due to our generator pseudo
  1276. # on-stack-replacement, these assignments take effect on generator
  1277. # reentry.
  1278. def generator():
  1279. yield 1
  1280. generator.func_code.co_use_jit = True
  1281. yield 2
  1282. generator.func_code.co_use_jit = False
  1283. yield 3
  1284. self.assertEqual(list(generator()), [1, 2, 3])
  1285. @at_each_optimization_level
  1286. def test_closure(self, level):
  1287. make_closure = compile_for_llvm('make_closure', '''
  1288. def make_closure(a, level):
  1289. b = 5
  1290. c = 3
  1291. def inner(d, e=5):
  1292. c = d + 1
  1293. return a, b, c, d, e
  1294. if level is not None:
  1295. inner.__code__.co_use_jit = True
  1296. inner.__code__.co_optimization = level
  1297. b = 2
  1298. return inner
  1299. ''', level)
  1300. inner = make_closure(1, level)
  1301. self.assertEquals(inner(4), (1, 2, 5, 4, 5))
  1302. self.assertRaises(TypeError, inner, "5")
  1303. @at_each_optimization_level
  1304. def test_closure_unbound_freevar(self, level):
  1305. unbound_freevar = compile_for_llvm('unbound_freevar', '''
  1306. def unbound_freevar(level):
  1307. if 0:
  1308. b = 2
  1309. def inner():
  1310. return b
  1311. if level is not None:
  1312. inner.__code__.co_use_jit = True
  1313. inner.__code__.co_optimization = level
  1314. return inner
  1315. ''', level)
  1316. inner = unbound_freevar(level)
  1317. self.assertRaisesWithArgs(NameError,
  1318. ("free variable 'b' referenced before "
  1319. "assignment in enclosing scope",), inner)
  1320. @at_each_optimization_level
  1321. def test_closure_unbound_local(self, level):
  1322. unbound_local = compile_for_llvm('unbound_local', '''
  1323. def unbound_local(level):
  1324. def inner():
  1325. if 0:
  1326. b = 3
  1327. return b
  1328. if level is not None:
  1329. inner.__code__.co_use_jit = True
  1330. inner.__code__.co_optimization = level
  1331. return inner
  1332. ''', level)
  1333. inner = unbound_local(level)
  1334. self.assertRaisesWithArgs(UnboundLocalError,
  1335. ("local variable 'b' referenced before assignment",), inner)
  1336. @at_each_optimization_level
  1337. def test_ends_with_unconditional_jump(self, level):
  1338. foo = compile_for_llvm('foo', '''
  1339. from opcode import opmap
  1340. from types import CodeType, FunctionType
  1341. foo_bytecode = [
  1342. opmap["JUMP_FORWARD"], 4, 0, # 0 JUMP_FORWARD 4 (to 7)
  1343. opmap["LOAD_CONST"], 0, 0, # 3 LOAD_CONST 0 (1)
  1344. opmap["RETURN_VALUE"], # 6 RETURN_VALUE
  1345. opmap["JUMP_ABSOLUTE"], 3, 0, # 7 JUMP_ABSOLUTE 3
  1346. ]
  1347. foo_code = CodeType(0, 0, 1, 0, "".join(chr(x) for x in foo_bytecode),
  1348. (1,), (), (), "<string>", "foo", 1, "")
  1349. foo = FunctionType(foo_code, globals())
  1350. ''', level)
  1351. self.assertEquals(1, foo())
  1352. class LoopExceptionInteractionTests(LlvmTestCase):
  1353. @at_each_optimization_level
  1354. def test_except_through_loop_caught(self, level):
  1355. nested = compile_for_llvm('nested', '''
  1356. def nested(lst, obj):
  1357. try:
  1358. for x in lst:
  1359. raise UnboundLocalError
  1360. except:
  1361. obj["x"] = 2
  1362. # Make sure the block stack is ok.
  1363. try:
  1364. for x in lst:
  1365. return x
  1366. finally:
  1367. obj["y"] = 3
  1368. ''', level)
  1369. obj = {}
  1370. self.assertEquals(1, nested([1,2,3], obj))
  1371. self.assertEquals({"x": 2, "y": 3}, obj)
  1372. @at_each_optimization_level
  1373. def test_except_in_loop(self, level):
  1374. nested = compile_for_llvm('nested', '''
  1375. def nested(lst, obj):
  1376. try:
  1377. for x in lst:
  1378. try:
  1379. a = a
  1380. except ZeroDivisionError:
  1381. obj["x"] = 2
  1382. except UnboundLocalError:
  1383. obj["z"] = 4
  1384. # Make sure the block stack is ok.
  1385. try:
  1386. for x in lst:
  1387. return x
  1388. finally:
  1389. obj["y"] = 3
  1390. ''', level)
  1391. obj = {}
  1392. self.assertEquals(1, nested([1,2,3], obj))
  1393. self.assertEquals({"z": 4, "y": 3}, obj)
  1394. @at_each_optimization_level
  1395. def test_except_through_loop_finally(self, level):
  1396. nested = compile_for_llvm('nested', '''
  1397. def nested(lst, obj):
  1398. try:
  1399. for x in lst:
  1400. a = a
  1401. finally:
  1402. obj["x"] = 2
  1403. ''', level)
  1404. obj = {}
  1405. self.assertRaises(UnboundLocalError, nested, [1,2,3], obj)
  1406. self.assertEquals({"x": 2}, obj)
  1407. @at_each_optimization_level
  1408. def test_break_in_try(self, level):
  1409. break_one = compile_for_llvm("break_one", """
  1410. def break_one(x):
  1411. for y in [1, 2]:
  1412. try:
  1413. x["break"] = y
  1414. break
  1415. x["post break"] = y
  1416. except ZeroDivisionError:
  1417. x["except"] = 77
  1418. finally:
  1419. x["finally"] = y
  1420. else:
  1421. x["else"] = True
  1422. # Make sure the block stack is ok.
  1423. try:
  1424. 1 / 0
  1425. except ZeroDivisionError:
  1426. x["except"] = ZeroDivisionError
  1427. return x
  1428. """, level)
  1429. self.assertEqual(break_one({}), {"break": 1, "finally": 1,
  1430. "except": ZeroDivisionError})
  1431. def cause_bail_on_next_line():
  1432. sys.settrace(lambda *args: None)
  1433. class BailoutTests(ExtraAssertsTestCase):
  1434. @at_each_optimization_level
  1435. def test_bail_inside_loop(self, level):
  1436. # We had a bug where the block stack in the compiled version
  1437. # of the below function used contiguous small integers to
  1438. # identify block handlers. When we bailed out to the
  1439. # interpreter, it expected an handler's identifier to be the
  1440. # index of the opcode that started the code for the handler.
  1441. # This mismatch caused a crash.
  1442. loop = compile_for_llvm("loop", """
  1443. def loop():
  1444. for i in [1, 2]:
  1445. # Use try/finally to get "break" to emit a BREAK_LOOP opcode
  1446. # instead of just jumping out of the loop.
  1447. try:
  1448. cause_bail_on_next_line()
  1449. break
  1450. finally:
  1451. pass
  1452. return i
  1453. """, level)
  1454. orig_trace = sys.gettrace()
  1455. try:
  1456. self.assertEquals(loop(), 1)
  1457. finally:
  1458. sys.settrace(orig_trace)
  1459. def test_use_correct_unwind_reason_when_bailing(self):