test_compile.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. import dis
  2. import math
  3. import os
  4. import unittest
  5. import sys
  6. import ast
  7. import _ast
  8. import tempfile
  9. import types
  10. import textwrap
  11. from test import support
  12. from test.support import script_helper, requires_debug_ranges
  13. from test.support.os_helper import FakePath
  14. class TestSpecifics(unittest.TestCase):
  15. def compile_single(self, source):
  16. compile(source, "<single>", "single")
  17. def assertInvalidSingle(self, source):
  18. self.assertRaises(SyntaxError, self.compile_single, source)
  19. def test_no_ending_newline(self):
  20. compile("hi", "<test>", "exec")
  21. compile("hi\r", "<test>", "exec")
  22. def test_empty(self):
  23. compile("", "<test>", "exec")
  24. def test_other_newlines(self):
  25. compile("\r\n", "<test>", "exec")
  26. compile("\r", "<test>", "exec")
  27. compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
  28. compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
  29. def test_debug_assignment(self):
  30. # catch assignments to __debug__
  31. self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
  32. import builtins
  33. prev = builtins.__debug__
  34. setattr(builtins, '__debug__', 'sure')
  35. self.assertEqual(__debug__, prev)
  36. setattr(builtins, '__debug__', prev)
  37. def test_argument_handling(self):
  38. # detect duplicate positional and keyword arguments
  39. self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
  40. self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
  41. self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
  42. self.assertRaises(SyntaxError, exec, 'def f(a, a): pass')
  43. self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass')
  44. self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
  45. def test_syntax_error(self):
  46. self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
  47. def test_none_keyword_arg(self):
  48. self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
  49. def test_duplicate_global_local(self):
  50. self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
  51. def test_exec_with_general_mapping_for_locals(self):
  52. class M:
  53. "Test mapping interface versus possible calls from eval()."
  54. def __getitem__(self, key):
  55. if key == 'a':
  56. return 12
  57. raise KeyError
  58. def __setitem__(self, key, value):
  59. self.results = (key, value)
  60. def keys(self):
  61. return list('xyz')
  62. m = M()
  63. g = globals()
  64. exec('z = a', g, m)
  65. self.assertEqual(m.results, ('z', 12))
  66. try:
  67. exec('z = b', g, m)
  68. except NameError:
  69. pass
  70. else:
  71. self.fail('Did not detect a KeyError')
  72. exec('z = dir()', g, m)
  73. self.assertEqual(m.results, ('z', list('xyz')))
  74. exec('z = globals()', g, m)
  75. self.assertEqual(m.results, ('z', g))
  76. exec('z = locals()', g, m)
  77. self.assertEqual(m.results, ('z', m))
  78. self.assertRaises(TypeError, exec, 'z = b', m)
  79. class A:
  80. "Non-mapping"
  81. pass
  82. m = A()
  83. self.assertRaises(TypeError, exec, 'z = a', g, m)
  84. # Verify that dict subclasses work as well
  85. class D(dict):
  86. def __getitem__(self, key):
  87. if key == 'a':
  88. return 12
  89. return dict.__getitem__(self, key)
  90. d = D()
  91. exec('z = a', g, d)
  92. self.assertEqual(d['z'], 12)
  93. def test_extended_arg(self):
  94. # default: 1000 * 2.5 = 2500 repetitions
  95. repeat = int(sys.getrecursionlimit() * 2.5)
  96. longexpr = 'x = x or ' + '-x' * repeat
  97. g = {}
  98. code = '''
  99. def f(x):
  100. %s
  101. %s
  102. %s
  103. %s
  104. %s
  105. %s
  106. %s
  107. %s
  108. %s
  109. %s
  110. # the expressions above have no effect, x == argument
  111. while x:
  112. x -= 1
  113. # EXTENDED_ARG/JUMP_ABSOLUTE here
  114. return x
  115. ''' % ((longexpr,)*10)
  116. exec(code, g)
  117. self.assertEqual(g['f'](5), 0)
  118. def test_argument_order(self):
  119. self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass')
  120. def test_float_literals(self):
  121. # testing bad float literals
  122. self.assertRaises(SyntaxError, eval, "2e")
  123. self.assertRaises(SyntaxError, eval, "2.0e+")
  124. self.assertRaises(SyntaxError, eval, "1e-")
  125. self.assertRaises(SyntaxError, eval, "3-4e/21")
  126. def test_indentation(self):
  127. # testing compile() of indented block w/o trailing newline"
  128. s = """
  129. if 1:
  130. if 2:
  131. pass"""
  132. compile(s, "<string>", "exec")
  133. # This test is probably specific to CPython and may not generalize
  134. # to other implementations. We are trying to ensure that when
  135. # the first line of code starts after 256, correct line numbers
  136. # in tracebacks are still produced.
  137. def test_leading_newlines(self):
  138. s256 = "".join(["\n"] * 256 + ["spam"])
  139. co = compile(s256, 'fn', 'exec')
  140. self.assertEqual(co.co_firstlineno, 1)
  141. lines = list(co.co_lines())
  142. self.assertEqual(lines[0][2], 0)
  143. self.assertEqual(lines[1][2], 257)
  144. def test_literals_with_leading_zeroes(self):
  145. for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
  146. "080000000000000", "000000000000009", "000000000000008",
  147. "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
  148. "0b101j", "0o153j", "0b100e1", "0o777e1", "0777",
  149. "000777", "000000000000007"]:
  150. self.assertRaises(SyntaxError, eval, arg)
  151. self.assertEqual(eval("0xff"), 255)
  152. self.assertEqual(eval("0777."), 777)
  153. self.assertEqual(eval("0777.0"), 777)
  154. self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
  155. self.assertEqual(eval("0777e1"), 7770)
  156. self.assertEqual(eval("0e0"), 0)
  157. self.assertEqual(eval("0000e-012"), 0)
  158. self.assertEqual(eval("09.5"), 9.5)
  159. self.assertEqual(eval("0777j"), 777j)
  160. self.assertEqual(eval("000"), 0)
  161. self.assertEqual(eval("00j"), 0j)
  162. self.assertEqual(eval("00.0"), 0)
  163. self.assertEqual(eval("0e3"), 0)
  164. self.assertEqual(eval("090000000000000."), 90000000000000.)
  165. self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
  166. self.assertEqual(eval("090000000000000e0"), 90000000000000.)
  167. self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
  168. self.assertEqual(eval("090000000000000j"), 90000000000000j)
  169. self.assertEqual(eval("000000000000008."), 8.)
  170. self.assertEqual(eval("000000000000009."), 9.)
  171. self.assertEqual(eval("0b101010"), 42)
  172. self.assertEqual(eval("-0b000000000010"), -2)
  173. self.assertEqual(eval("0o777"), 511)
  174. self.assertEqual(eval("-0o0000010"), -8)
  175. def test_int_literals_too_long(self):
  176. n = 3000
  177. source = f"a = 1\nb = 2\nc = {'3'*n}\nd = 4"
  178. with support.adjust_int_max_str_digits(n):
  179. compile(source, "<long_int_pass>", "exec") # no errors.
  180. with support.adjust_int_max_str_digits(n-1):
  181. with self.assertRaises(SyntaxError) as err_ctx:
  182. compile(source, "<long_int_fail>", "exec")
  183. exc = err_ctx.exception
  184. self.assertEqual(exc.lineno, 3)
  185. self.assertIn('Exceeds the limit ', str(exc))
  186. self.assertIn(' Consider hexadecimal ', str(exc))
  187. def test_unary_minus(self):
  188. # Verify treatment of unary minus on negative numbers SF bug #660455
  189. if sys.maxsize == 2147483647:
  190. # 32-bit machine
  191. all_one_bits = '0xffffffff'
  192. self.assertEqual(eval(all_one_bits), 4294967295)
  193. self.assertEqual(eval("-" + all_one_bits), -4294967295)
  194. elif sys.maxsize == 9223372036854775807:
  195. # 64-bit machine
  196. all_one_bits = '0xffffffffffffffff'
  197. self.assertEqual(eval(all_one_bits), 18446744073709551615)
  198. self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
  199. else:
  200. self.fail("How many bits *does* this machine have???")
  201. # Verify treatment of constant folding on -(sys.maxsize+1)
  202. # i.e. -2147483648 on 32 bit platforms. Should return int.
  203. self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int)
  204. self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int)
  205. if sys.maxsize == 9223372036854775807:
  206. def test_32_63_bit_values(self):
  207. a = +4294967296 # 1 << 32
  208. b = -4294967296 # 1 << 32
  209. c = +281474976710656 # 1 << 48
  210. d = -281474976710656 # 1 << 48
  211. e = +4611686018427387904 # 1 << 62
  212. f = -4611686018427387904 # 1 << 62
  213. g = +9223372036854775807 # 1 << 63 - 1
  214. h = -9223372036854775807 # 1 << 63 - 1
  215. for variable in self.test_32_63_bit_values.__code__.co_consts:
  216. if variable is not None:
  217. self.assertIsInstance(variable, int)
  218. def test_sequence_unpacking_error(self):
  219. # Verify sequence packing/unpacking with "or". SF bug #757818
  220. i,j = (1, -1) or (-1, 1)
  221. self.assertEqual(i, 1)
  222. self.assertEqual(j, -1)
  223. def test_none_assignment(self):
  224. stmts = [
  225. 'None = 0',
  226. 'None += 0',
  227. '__builtins__.None = 0',
  228. 'def None(): pass',
  229. 'class None: pass',
  230. '(a, None) = 0, 0',
  231. 'for None in range(10): pass',
  232. 'def f(None): pass',
  233. 'import None',
  234. 'import x as None',
  235. 'from x import None',
  236. 'from x import y as None'
  237. ]
  238. for stmt in stmts:
  239. stmt += "\n"
  240. self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
  241. self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
  242. def test_import(self):
  243. succeed = [
  244. 'import sys',
  245. 'import os, sys',
  246. 'import os as bar',
  247. 'import os.path as bar',
  248. 'from __future__ import nested_scopes, generators',
  249. 'from __future__ import (nested_scopes,\ngenerators)',
  250. 'from __future__ import (nested_scopes,\ngenerators,)',
  251. 'from sys import stdin, stderr, stdout',
  252. 'from sys import (stdin, stderr,\nstdout)',
  253. 'from sys import (stdin, stderr,\nstdout,)',
  254. 'from sys import (stdin\n, stderr, stdout)',
  255. 'from sys import (stdin\n, stderr, stdout,)',
  256. 'from sys import stdin as si, stdout as so, stderr as se',
  257. 'from sys import (stdin as si, stdout as so, stderr as se)',
  258. 'from sys import (stdin as si, stdout as so, stderr as se,)',
  259. ]
  260. fail = [
  261. 'import (os, sys)',
  262. 'import (os), (sys)',
  263. 'import ((os), (sys))',
  264. 'import (sys',
  265. 'import sys)',
  266. 'import (os,)',
  267. 'import os As bar',
  268. 'import os.path a bar',
  269. 'from sys import stdin As stdout',
  270. 'from sys import stdin a stdout',
  271. 'from (sys) import stdin',
  272. 'from __future__ import (nested_scopes',
  273. 'from __future__ import nested_scopes)',
  274. 'from __future__ import nested_scopes,\ngenerators',
  275. 'from sys import (stdin',
  276. 'from sys import stdin)',
  277. 'from sys import stdin, stdout,\nstderr',
  278. 'from sys import stdin si',
  279. 'from sys import stdin,',
  280. 'from sys import (*)',
  281. 'from sys import (stdin,, stdout, stderr)',
  282. 'from sys import (stdin, stdout),',
  283. ]
  284. for stmt in succeed:
  285. compile(stmt, 'tmp', 'exec')
  286. for stmt in fail:
  287. self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
  288. def test_for_distinct_code_objects(self):
  289. # SF bug 1048870
  290. def f():
  291. f1 = lambda x=1: x
  292. f2 = lambda x=2: x
  293. return f1, f2
  294. f1, f2 = f()
  295. self.assertNotEqual(id(f1.__code__), id(f2.__code__))
  296. def test_lambda_doc(self):
  297. l = lambda: "foo"
  298. self.assertIsNone(l.__doc__)
  299. def test_encoding(self):
  300. code = b'# -*- coding: badencoding -*-\npass\n'
  301. self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec')
  302. code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n'
  303. compile(code, 'tmp', 'exec')
  304. self.assertEqual(eval(code), '\xc2\xa4')
  305. code = '"\xc2\xa4"\n'
  306. self.assertEqual(eval(code), '\xc2\xa4')
  307. code = b'"\xc2\xa4"\n'
  308. self.assertEqual(eval(code), '\xa4')
  309. code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n'
  310. self.assertEqual(eval(code), '\xc2\xa4')
  311. code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n'
  312. self.assertEqual(eval(code), '\xa4')
  313. code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n'
  314. self.assertEqual(eval(code), '\xc2\u20ac')
  315. code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
  316. self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4')
  317. code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
  318. self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4')
  319. def test_subscripts(self):
  320. # SF bug 1448804
  321. # Class to make testing subscript results easy
  322. class str_map(object):
  323. def __init__(self):
  324. self.data = {}
  325. def __getitem__(self, key):
  326. return self.data[str(key)]
  327. def __setitem__(self, key, value):
  328. self.data[str(key)] = value
  329. def __delitem__(self, key):
  330. del self.data[str(key)]
  331. def __contains__(self, key):
  332. return str(key) in self.data
  333. d = str_map()
  334. # Index
  335. d[1] = 1
  336. self.assertEqual(d[1], 1)
  337. d[1] += 1
  338. self.assertEqual(d[1], 2)
  339. del d[1]
  340. self.assertNotIn(1, d)
  341. # Tuple of indices
  342. d[1, 1] = 1
  343. self.assertEqual(d[1, 1], 1)
  344. d[1, 1] += 1
  345. self.assertEqual(d[1, 1], 2)
  346. del d[1, 1]
  347. self.assertNotIn((1, 1), d)
  348. # Simple slice
  349. d[1:2] = 1
  350. self.assertEqual(d[1:2], 1)
  351. d[1:2] += 1
  352. self.assertEqual(d[1:2], 2)
  353. del d[1:2]
  354. self.assertNotIn(slice(1, 2), d)
  355. # Tuple of simple slices
  356. d[1:2, 1:2] = 1
  357. self.assertEqual(d[1:2, 1:2], 1)
  358. d[1:2, 1:2] += 1
  359. self.assertEqual(d[1:2, 1:2], 2)
  360. del d[1:2, 1:2]
  361. self.assertNotIn((slice(1, 2), slice(1, 2)), d)
  362. # Extended slice
  363. d[1:2:3] = 1
  364. self.assertEqual(d[1:2:3], 1)
  365. d[1:2:3] += 1
  366. self.assertEqual(d[1:2:3], 2)
  367. del d[1:2:3]
  368. self.assertNotIn(slice(1, 2, 3), d)
  369. # Tuple of extended slices
  370. d[1:2:3, 1:2:3] = 1
  371. self.assertEqual(d[1:2:3, 1:2:3], 1)
  372. d[1:2:3, 1:2:3] += 1
  373. self.assertEqual(d[1:2:3, 1:2:3], 2)
  374. del d[1:2:3, 1:2:3]
  375. self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
  376. # Ellipsis
  377. d[...] = 1
  378. self.assertEqual(d[...], 1)
  379. d[...] += 1
  380. self.assertEqual(d[...], 2)
  381. del d[...]
  382. self.assertNotIn(Ellipsis, d)
  383. # Tuple of Ellipses
  384. d[..., ...] = 1
  385. self.assertEqual(d[..., ...], 1)
  386. d[..., ...] += 1
  387. self.assertEqual(d[..., ...], 2)
  388. del d[..., ...]
  389. self.assertNotIn((Ellipsis, Ellipsis), d)
  390. def test_annotation_limit(self):
  391. # more than 255 annotations, should compile ok
  392. s = "def f(%s): pass"
  393. s %= ', '.join('a%d:%d' % (i,i) for i in range(300))
  394. compile(s, '?', 'exec')
  395. def test_mangling(self):
  396. class A:
  397. def f():
  398. __mangled = 1
  399. __not_mangled__ = 2
  400. import __mangled_mod
  401. import __package__.module
  402. self.assertIn("_A__mangled", A.f.__code__.co_varnames)
  403. self.assertIn("__not_mangled__", A.f.__code__.co_varnames)
  404. self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
  405. self.assertIn("__package__", A.f.__code__.co_varnames)
  406. def test_compile_ast(self):
  407. fname = __file__
  408. if fname.lower().endswith('pyc'):
  409. fname = fname[:-1]
  410. with open(fname, encoding='utf-8') as f:
  411. fcontents = f.read()
  412. sample_code = [
  413. ['<assign>', 'x = 5'],
  414. ['<ifblock>', """if True:\n pass\n"""],
  415. ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
  416. ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
  417. [fname, fcontents],
  418. ]
  419. for fname, code in sample_code:
  420. co1 = compile(code, '%s1' % fname, 'exec')
  421. ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
  422. self.assertTrue(type(ast) == _ast.Module)
  423. co2 = compile(ast, '%s3' % fname, 'exec')
  424. self.assertEqual(co1, co2)
  425. # the code object's filename comes from the second compilation step
  426. self.assertEqual(co2.co_filename, '%s3' % fname)
  427. # raise exception when node type doesn't match with compile mode
  428. co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
  429. self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
  430. # raise exception when node type is no start node
  431. self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
  432. # raise exception when node has invalid children
  433. ast = _ast.Module()
  434. ast.body = [_ast.BoolOp()]
  435. self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
  436. def test_dict_evaluation_order(self):
  437. i = 0
  438. def f():
  439. nonlocal i
  440. i += 1
  441. return i
  442. d = {f(): f(), f(): f()}
  443. self.assertEqual(d, {1: 2, 3: 4})
  444. def test_compile_filename(self):
  445. for filename in 'file.py', b'file.py':
  446. code = compile('pass', filename, 'exec')
  447. self.assertEqual(code.co_filename, 'file.py')
  448. for filename in bytearray(b'file.py'), memoryview(b'file.py'):
  449. with self.assertWarns(DeprecationWarning):
  450. code = compile('pass', filename, 'exec')
  451. self.assertEqual(code.co_filename, 'file.py')
  452. self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
  453. @support.cpython_only
  454. def test_same_filename_used(self):
  455. s = """def f(): pass\ndef g(): pass"""
  456. c = compile(s, "myfile", "exec")
  457. for obj in c.co_consts:
  458. if isinstance(obj, types.CodeType):
  459. self.assertIs(obj.co_filename, c.co_filename)
  460. def test_single_statement(self):
  461. self.compile_single("1 + 2")
  462. self.compile_single("\n1 + 2")
  463. self.compile_single("1 + 2\n")
  464. self.compile_single("1 + 2\n\n")
  465. self.compile_single("1 + 2\t\t\n")
  466. self.compile_single("1 + 2\t\t\n ")
  467. self.compile_single("1 + 2 # one plus two")
  468. self.compile_single("1; 2")
  469. self.compile_single("import sys; sys")
  470. self.compile_single("def f():\n pass")
  471. self.compile_single("while False:\n pass")
  472. self.compile_single("if x:\n f(x)")
  473. self.compile_single("if x:\n f(x)\nelse:\n g(x)")
  474. self.compile_single("class T:\n pass")
  475. self.compile_single("c = '''\na=1\nb=2\nc=3\n'''")
  476. def test_bad_single_statement(self):
  477. self.assertInvalidSingle('1\n2')
  478. self.assertInvalidSingle('def f(): pass')
  479. self.assertInvalidSingle('a = 13\nb = 187')
  480. self.assertInvalidSingle('del x\ndel y')
  481. self.assertInvalidSingle('f()\ng()')
  482. self.assertInvalidSingle('f()\n# blah\nblah()')
  483. self.assertInvalidSingle('f()\nxy # blah\nblah()')
  484. self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
  485. self.assertInvalidSingle("c = '''\nd=1\n'''\na = 1\n\nb = 2\n")
  486. def test_particularly_evil_undecodable(self):
  487. # Issue 24022
  488. src = b'0000\x00\n00000000000\n\x00\n\x9e\n'
  489. with tempfile.TemporaryDirectory() as tmpd:
  490. fn = os.path.join(tmpd, "bad.py")
  491. with open(fn, "wb") as fp:
  492. fp.write(src)
  493. res = script_helper.run_python_until_end(fn)[0]
  494. self.assertIn(b"Non-UTF-8", res.err)
  495. def test_yet_more_evil_still_undecodable(self):
  496. # Issue #25388
  497. src = b"#\x00\n#\xfd\n"
  498. with tempfile.TemporaryDirectory() as tmpd:
  499. fn = os.path.join(tmpd, "bad.py")
  500. with open(fn, "wb") as fp:
  501. fp.write(src)
  502. res = script_helper.run_python_until_end(fn)[0]
  503. self.assertIn(b"Non-UTF-8", res.err)
  504. @support.cpython_only
  505. def test_compiler_recursion_limit(self):
  506. # Expected limit is sys.getrecursionlimit() * the scaling factor
  507. # in symtable.c (currently 3)
  508. # We expect to fail *at* that limit, because we use up some of
  509. # the stack depth limit in the test suite code
  510. # So we check the expected limit and 75% of that
  511. # XXX (ncoghlan): duplicating the scaling factor here is a little
  512. # ugly. Perhaps it should be exposed somewhere...
  513. fail_depth = sys.getrecursionlimit() * 3
  514. crash_depth = sys.getrecursionlimit() * 300
  515. success_depth = int(fail_depth * 0.75)
  516. def check_limit(prefix, repeated, mode="single"):
  517. expect_ok = prefix + repeated * success_depth
  518. compile(expect_ok, '<test>', mode)
  519. for depth in (fail_depth, crash_depth):
  520. broken = prefix + repeated * depth
  521. details = "Compiling ({!r} + {!r} * {})".format(
  522. prefix, repeated, depth)
  523. with self.assertRaises(RecursionError, msg=details):
  524. compile(broken, '<test>', mode)
  525. check_limit("a", "()")
  526. check_limit("a", ".b")
  527. check_limit("a", "[0]")
  528. check_limit("a", "*a")
  529. # XXX Crashes in the parser.
  530. # check_limit("a", " if a else a")
  531. # check_limit("if a: pass", "\nelif a: pass", mode="exec")
  532. def test_null_terminated(self):
  533. # The source code is null-terminated internally, but bytes-like
  534. # objects are accepted, which could be not terminated.
  535. with self.assertRaisesRegex(ValueError, "cannot contain null"):
  536. compile("123\x00", "<dummy>", "eval")
  537. with self.assertRaisesRegex(ValueError, "cannot contain null"):
  538. compile(memoryview(b"123\x00"), "<dummy>", "eval")
  539. code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval")
  540. self.assertEqual(eval(code), 23)
  541. code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval")
  542. self.assertEqual(eval(code), 23)
  543. code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval")
  544. self.assertEqual(eval(code), 23)
  545. # Also test when eval() and exec() do the compilation step
  546. self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23)
  547. namespace = dict()
  548. exec(memoryview(b"ax = 123")[1:-1], namespace)
  549. self.assertEqual(namespace['x'], 12)
  550. def check_constant(self, func, expected):
  551. for const in func.__code__.co_consts:
  552. if repr(const) == repr(expected):
  553. break
  554. else:
  555. self.fail("unable to find constant %r in %r"
  556. % (expected, func.__code__.co_consts))
  557. # Merging equal constants is not a strict requirement for the Python
  558. # semantics, it's a more an implementation detail.
  559. @support.cpython_only
  560. def test_merge_constants(self):
  561. # Issue #25843: compile() must merge constants which are equal
  562. # and have the same type.
  563. def check_same_constant(const):
  564. ns = {}
  565. code = "f1, f2 = lambda: %r, lambda: %r" % (const, const)
  566. exec(code, ns)
  567. f1 = ns['f1']
  568. f2 = ns['f2']
  569. self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
  570. self.check_constant(f1, const)
  571. self.assertEqual(repr(f1()), repr(const))
  572. check_same_constant(None)
  573. check_same_constant(0)
  574. check_same_constant(0.0)
  575. check_same_constant(b'abc')
  576. check_same_constant('abc')
  577. # Note: "lambda: ..." emits "LOAD_CONST Ellipsis",
  578. # whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis"
  579. f1, f2 = lambda: ..., lambda: ...
  580. self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
  581. self.check_constant(f1, Ellipsis)
  582. self.assertEqual(repr(f1()), repr(Ellipsis))
  583. # Merge constants in tuple or frozenset
  584. f1, f2 = lambda: "not a name", lambda: ("not a name",)
  585. f3 = lambda x: x in {("not a name",)}
  586. self.assertIs(f1.__code__.co_consts[1],
  587. f2.__code__.co_consts[1][0])
  588. self.assertIs(next(iter(f3.__code__.co_consts[1])),
  589. f2.__code__.co_consts[1])
  590. # {0} is converted to a constant frozenset({0}) by the peephole
  591. # optimizer
  592. f1, f2 = lambda x: x in {0}, lambda x: x in {0}
  593. self.assertIs(f1.__code__.co_consts, f2.__code__.co_consts)
  594. self.check_constant(f1, frozenset({0}))
  595. self.assertTrue(f1(0))
  596. # Merging equal co_linetable is not a strict requirement
  597. # for the Python semantics, it's a more an implementation detail.
  598. @support.cpython_only
  599. def test_merge_code_attrs(self):
  600. # See https://bugs.python.org/issue42217
  601. f1 = lambda x: x.y.z
  602. f2 = lambda a: a.b.c
  603. self.assertIs(f1.__code__.co_linetable, f2.__code__.co_linetable)
  604. # Stripping unused constants is not a strict requirement for the
  605. # Python semantics, it's a more an implementation detail.
  606. @support.cpython_only
  607. def test_strip_unused_consts(self):
  608. # Python 3.10rc1 appended None to co_consts when None is not used
  609. # at all. See bpo-45056.
  610. def f1():
  611. "docstring"
  612. return 42
  613. self.assertEqual(f1.__code__.co_consts, ("docstring", 42))
  614. # This is a regression test for a CPython specific peephole optimizer
  615. # implementation bug present in a few releases. It's assertion verifies
  616. # that peephole optimization was actually done though that isn't an
  617. # indication of the bugs presence or not (crashing is).
  618. @support.cpython_only
  619. def test_peephole_opt_unreachable_code_array_access_in_bounds(self):
  620. """Regression test for issue35193 when run under clang msan."""
  621. def unused_code_at_end():
  622. return 3
  623. raise RuntimeError("unreachable")
  624. # The above function definition will trigger the out of bounds
  625. # bug in the peephole optimizer as it scans opcodes past the
  626. # RETURN_VALUE opcode. This does not always crash an interpreter.
  627. # When you build with the clang memory sanitizer it reliably aborts.
  628. self.assertEqual(
  629. 'RETURN_VALUE',
  630. list(dis.get_instructions(unused_code_at_end))[-1].opname)
  631. def test_dont_merge_constants(self):
  632. # Issue #25843: compile() must not merge constants which are equal
  633. # but have a different type.
  634. def check_different_constants(const1, const2):
  635. ns = {}
  636. exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns)
  637. f1 = ns['f1']
  638. f2 = ns['f2']
  639. self.assertIsNot(f1.__code__, f2.__code__)
  640. self.assertNotEqual(f1.__code__, f2.__code__)
  641. self.check_constant(f1, const1)
  642. self.check_constant(f2, const2)
  643. self.assertEqual(repr(f1()), repr(const1))
  644. self.assertEqual(repr(f2()), repr(const2))
  645. check_different_constants(0, 0.0)
  646. check_different_constants(+0.0, -0.0)
  647. check_different_constants((0,), (0.0,))
  648. check_different_constants('a', b'a')
  649. check_different_constants(('a',), (b'a',))
  650. # check_different_constants() cannot be used because repr(-0j) is
  651. # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign.
  652. f1, f2 = lambda: +0.0j, lambda: -0.0j
  653. self.assertIsNot(f1.__code__, f2.__code__)
  654. self.check_constant(f1, +0.0j)
  655. self.check_constant(f2, -0.0j)
  656. self.assertEqual(repr(f1()), repr(+0.0j))
  657. self.assertEqual(repr(f2()), repr(-0.0j))
  658. # {0} is converted to a constant frozenset({0}) by the peephole
  659. # optimizer
  660. f1, f2 = lambda x: x in {0}, lambda x: x in {0.0}
  661. self.assertIsNot(f1.__code__, f2.__code__)
  662. self.check_constant(f1, frozenset({0}))
  663. self.check_constant(f2, frozenset({0.0}))
  664. self.assertTrue(f1(0))
  665. self.assertTrue(f2(0.0))
  666. def test_path_like_objects(self):
  667. # An implicit test for PyUnicode_FSDecoder().
  668. compile("42", FakePath("test_compile_pathlike"), "single")
  669. def test_stack_overflow(self):
  670. # bpo-31113: Stack overflow when compile a long sequence of
  671. # complex statements.
  672. compile("if a: b\n" * 200000, "<dummy>", "exec")
  673. # Multiple users rely on the fact that CPython does not generate
  674. # bytecode for dead code blocks. See bpo-37500 for more context.
  675. @support.cpython_only
  676. def test_dead_blocks_do_not_generate_bytecode(self):
  677. def unused_block_if():
  678. if 0:
  679. return 42
  680. def unused_block_while():
  681. while 0:
  682. return 42
  683. def unused_block_if_else():
  684. if 1:
  685. return None
  686. else:
  687. return 42
  688. def unused_block_while_else():
  689. while 1:
  690. return None
  691. else:
  692. return 42
  693. funcs = [unused_block_if, unused_block_while,
  694. unused_block_if_else, unused_block_while_else]
  695. for func in funcs:
  696. opcodes = list(dis.get_instructions(func))
  697. self.assertLessEqual(len(opcodes), 4)
  698. self.assertEqual('LOAD_CONST', opcodes[-2].opname)
  699. self.assertEqual(None, opcodes[-2].argval)
  700. self.assertEqual('RETURN_VALUE', opcodes[-1].opname)
  701. def test_false_while_loop(self):
  702. def break_in_while():
  703. while False:
  704. break
  705. def continue_in_while():
  706. while False:
  707. continue
  708. funcs = [break_in_while, continue_in_while]
  709. # Check that we did not raise but we also don't generate bytecode
  710. for func in funcs:
  711. opcodes = list(dis.get_instructions(func))
  712. self.assertEqual(3, len(opcodes))
  713. self.assertEqual('LOAD_CONST', opcodes[1].opname)
  714. self.assertEqual(None, opcodes[1].argval)
  715. self.assertEqual('RETURN_VALUE', opcodes[2].opname)
  716. def test_consts_in_conditionals(self):
  717. def and_true(x):
  718. return True and x
  719. def and_false(x):
  720. return False and x
  721. def or_true(x):
  722. return True or x
  723. def or_false(x):
  724. return False or x
  725. funcs = [and_true, and_false, or_true, or_false]
  726. # Check that condition is removed.
  727. for func in funcs:
  728. with self.subTest(func=func):
  729. opcodes = list(dis.get_instructions(func))
  730. self.assertLessEqual(len(opcodes), 3)
  731. self.assertIn('LOAD_', opcodes[-2].opname)
  732. self.assertEqual('RETURN_VALUE', opcodes[-1].opname)
  733. def test_imported_load_method(self):
  734. sources = [
  735. """\
  736. import os
  737. def foo():
  738. return os.uname()
  739. """,
  740. """\
  741. import os as operating_system
  742. def foo():
  743. return operating_system.uname()
  744. """,
  745. """\
  746. from os import path
  747. def foo(x):
  748. return path.join(x)
  749. """,
  750. """\
  751. from os import path as os_path
  752. def foo(x):
  753. return os_path.join(x)
  754. """
  755. ]
  756. for source in sources:
  757. namespace = {}
  758. exec(textwrap.dedent(source), namespace)
  759. func = namespace['foo']
  760. with self.subTest(func=func.__name__):
  761. opcodes = list(dis.get_instructions(func))
  762. instructions = [opcode.opname for opcode in opcodes]
  763. self.assertNotIn('LOAD_METHOD', instructions)
  764. self.assertIn('LOAD_ATTR', instructions)
  765. self.assertIn('PRECALL', instructions)
  766. def test_lineno_procedure_call(self):
  767. def call():
  768. (
  769. print()
  770. )
  771. line1 = call.__code__.co_firstlineno + 1
  772. assert line1 not in [line for (_, _, line) in call.__code__.co_lines()]
  773. def test_lineno_after_implicit_return(self):
  774. TRUE = True
  775. # Don't use constant True or False, as compiler will remove test
  776. def if1(x):
  777. x()
  778. if TRUE:
  779. pass
  780. def if2(x):
  781. x()
  782. if TRUE:
  783. pass
  784. else:
  785. pass
  786. def if3(x):
  787. x()
  788. if TRUE:
  789. pass
  790. else:
  791. return None
  792. def if4(x):
  793. x()
  794. if not TRUE:
  795. pass
  796. funcs = [ if1, if2, if3, if4]
  797. lastlines = [ 3, 3, 3, 2]
  798. frame = None
  799. def save_caller_frame():
  800. nonlocal frame
  801. frame = sys._getframe(1)
  802. for func, lastline in zip(funcs, lastlines, strict=True):
  803. with self.subTest(func=func):
  804. func(save_caller_frame)
  805. self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, lastline)
  806. def test_lineno_after_no_code(self):
  807. def no_code1():
  808. "doc string"
  809. def no_code2():
  810. a: int
  811. for func in (no_code1, no_code2):
  812. with self.subTest(func=func):
  813. code = func.__code__
  814. lines = list(code.co_lines())
  815. start, end, line = lines[0]
  816. self.assertEqual(start, 0)
  817. self.assertEqual(line, code.co_firstlineno)
  818. def get_code_lines(self, code):
  819. last_line = -2
  820. res = []
  821. for _, _, line in code.co_lines():
  822. if line is not None and line != last_line:
  823. res.append(line - code.co_firstlineno)
  824. last_line = line
  825. return res
  826. def test_lineno_attribute(self):
  827. def load_attr():
  828. return (
  829. o.
  830. a
  831. )
  832. load_attr_lines = [ 0, 2, 3, 1 ]
  833. def load_method():
  834. return (
  835. o.
  836. m(
  837. 0
  838. )
  839. )
  840. load_method_lines = [ 0, 2, 3, 4, 3, 1 ]
  841. def store_attr():
  842. (
  843. o.
  844. a
  845. ) = (
  846. v
  847. )
  848. store_attr_lines = [ 0, 5, 2, 3 ]
  849. def aug_store_attr():
  850. (
  851. o.
  852. a
  853. ) += (
  854. v
  855. )
  856. aug_store_attr_lines = [ 0, 2, 3, 5, 1, 3 ]
  857. funcs = [ load_attr, load_method, store_attr, aug_store_attr]
  858. func_lines = [ load_attr_lines, load_method_lines,
  859. store_attr_lines, aug_store_attr_lines]
  860. for func, lines in zip(funcs, func_lines, strict=True):
  861. with self.subTest(func=func):
  862. code_lines = self.get_code_lines(func.__code__)
  863. self.assertEqual(lines, code_lines)
  864. def test_line_number_genexp(self):
  865. def return_genexp():
  866. return (1
  867. for
  868. x
  869. in
  870. y)
  871. genexp_lines = [0, 2, 0]
  872. genexp_code = return_genexp.__code__.co_consts[1]
  873. code_lines = self.get_code_lines(genexp_code)
  874. self.assertEqual(genexp_lines, code_lines)
  875. def test_line_number_implicit_return_after_async_for(self):
  876. async def test(aseq):
  877. async for i in aseq:
  878. body
  879. expected_lines = [0, 1, 2, 1]
  880. code_lines = self.get_code_lines(test.__code__)
  881. self.assertEqual(expected_lines, code_lines)
  882. def test_big_dict_literal(self):
  883. # The compiler has a flushing point in "compiler_dict" that calls compiles
  884. # a portion of the dictionary literal when the loop that iterates over the items
  885. # reaches 0xFFFF elements but the code was not including the boundary element,
  886. # dropping the key at position 0xFFFF. See bpo-41531 for more information
  887. dict_size = 0xFFFF + 1
  888. the_dict = "{" + ",".join(f"{x}:{x}" for x in range(dict_size)) + "}"
  889. self.assertEqual(len(eval(the_dict)), dict_size)
  890. def test_redundant_jump_in_if_else_break(self):
  891. # Check if bytecode containing jumps that simply point to the next line
  892. # is generated around if-else-break style structures. See bpo-42615.
  893. def if_else_break():
  894. val = 1
  895. while True:
  896. if val > 0:
  897. val -= 1
  898. else:
  899. break
  900. val = -1
  901. INSTR_SIZE = 2
  902. HANDLED_JUMPS = (
  903. 'POP_JUMP_IF_FALSE',
  904. 'POP_JUMP_IF_TRUE',
  905. 'JUMP_ABSOLUTE',
  906. 'JUMP_FORWARD',
  907. )
  908. for line, instr in enumerate(
  909. dis.Bytecode(if_else_break, show_caches=True)
  910. ):
  911. if instr.opname == 'JUMP_FORWARD':
  912. self.assertNotEqual(instr.arg, 0)
  913. elif instr.opname in HANDLED_JUMPS:
  914. self.assertNotEqual(instr.arg, (line + 1)*INSTR_SIZE)
  915. def test_no_wraparound_jump(self):
  916. # See https://bugs.python.org/issue46724
  917. def while_not_chained(a, b, c):
  918. while not (a < b < c):
  919. pass
  920. for instr in dis.Bytecode(while_not_chained):
  921. self.assertNotEqual(instr.opname, "EXTENDED_ARG")
  922. def test_compare_positions(self):
  923. for opname, op in [
  924. ("COMPARE_OP", "<"),
  925. ("COMPARE_OP", "<="),
  926. ("COMPARE_OP", ">"),
  927. ("COMPARE_OP", ">="),
  928. ("CONTAINS_OP", "in"),
  929. ("CONTAINS_OP", "not in"),
  930. ("IS_OP", "is"),
  931. ("IS_OP", "is not"),
  932. ]:
  933. expr = f'a {op} b {op} c'
  934. expected_positions = 2 * [(2, 2, 0, len(expr))]
  935. for source in [
  936. f"\\\n{expr}", f'if \\\n{expr}: x', f"x if \\\n{expr} else y"
  937. ]:
  938. code = compile(source, "<test>", "exec")
  939. actual_positions = [
  940. instruction.positions
  941. for instruction in dis.get_instructions(code)
  942. if instruction.opname == opname
  943. ]
  944. with self.subTest(source):
  945. self.assertEqual(actual_positions, expected_positions)
  946. @requires_debug_ranges()
  947. class TestSourcePositions(unittest.TestCase):
  948. # Ensure that compiled code snippets have correct line and column numbers
  949. # in `co_positions()`.
  950. def check_positions_against_ast(self, snippet):
  951. # Basic check that makes sure each line and column is at least present
  952. # in one of the AST nodes of the source code.
  953. code = compile(snippet, 'test_compile.py', 'exec')
  954. ast_tree = compile(snippet, 'test_compile.py', 'exec', _ast.PyCF_ONLY_AST)
  955. self.assertTrue(type(ast_tree) == _ast.Module)
  956. # Use an AST visitor that notes all the offsets.
  957. lines, end_lines, columns, end_columns = set(), set(), set(), set()
  958. class SourceOffsetVisitor(ast.NodeVisitor):
  959. def generic_visit(self, node):
  960. super().generic_visit(node)
  961. if not isinstance(node, ast.expr) and not isinstance(node, ast.stmt):
  962. return
  963. lines.add(node.lineno)
  964. end_lines.add(node.end_lineno)
  965. columns.add(node.col_offset)
  966. end_columns.add(node.end_col_offset)
  967. SourceOffsetVisitor().visit(ast_tree)
  968. # Check against the positions in the code object.
  969. for (line, end_line, col, end_col) in code.co_positions():
  970. if line == 0:
  971. continue # This is an artificial module-start line
  972. # If the offset is not None (indicating missing data), ensure that
  973. # it was part of one of the AST nodes.
  974. if line is not None:
  975. self.assertIn(line, lines)
  976. if end_line is not None:
  977. self.assertIn(end_line, end_lines)
  978. if col is not None:
  979. self.assertIn(col, columns)
  980. if end_col is not None:
  981. self.assertIn(end_col, end_columns)
  982. return code, ast_tree
  983. def assertOpcodeSourcePositionIs(self, code, opcode,
  984. line, end_line, column, end_column, occurrence=1):
  985. for instr, position in zip(
  986. dis.Bytecode(code, show_caches=True), code.co_positions(), strict=True
  987. ):
  988. if instr.opname == opcode:
  989. occurrence -= 1
  990. if not occurrence:
  991. self.assertEqual(position[0], line)
  992. self.assertEqual(position[1], end_line)
  993. self.assertEqual(position[2], column)
  994. self.assertEqual(position[3], end_column)
  995. return
  996. self.fail(f"Opcode {opcode} not found in code")
  997. def test_simple_assignment(self):
  998. snippet = "x = 1"
  999. self.check_positions_against_ast(snippet)
  1000. def test_compiles_to_extended_op_arg(self):
  1001. # Make sure we still have valid positions when the code compiles to an
  1002. # EXTENDED_ARG by performing a loop which needs a JUMP_ABSOLUTE after
  1003. # a bunch of opcodes.
  1004. snippet = "x = x\n" * 10_000
  1005. snippet += ("while x != 0:\n"
  1006. " x -= 1\n"
  1007. "while x != 0:\n"
  1008. " x += 1\n"
  1009. )
  1010. compiled_code, _ = self.check_positions_against_ast(snippet)
  1011. self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
  1012. line=10_000 + 2, end_line=10_000 + 2,
  1013. column=2, end_column=8, occurrence=1)
  1014. self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
  1015. line=10_000 + 4, end_line=10_000 + 4,
  1016. column=2, end_column=9, occurrence=2)
  1017. def test_multiline_expression(self):
  1018. snippet = """\
  1019. f(
  1020. 1, 2, 3, 4
  1021. )
  1022. """
  1023. compiled_code, _ = self.check_positions_against_ast(snippet)
  1024. self.assertOpcodeSourcePositionIs(compiled_code, 'CALL',
  1025. line=1, end_line=3, column=0, end_column=1)
  1026. def test_very_long_line_end_offset(self):
  1027. # Make sure we get the correct column offset for offsets
  1028. # too large to store in a byte.
  1029. long_string = "a" * 1000
  1030. snippet = f"g('{long_string}')"
  1031. compiled_code, _ = self.check_positions_against_ast(snippet)
  1032. self.assertOpcodeSourcePositionIs(compiled_code, 'CALL',
  1033. line=1, end_line=1, column=0, end_column=1005)
  1034. def test_complex_single_line_expression(self):
  1035. snippet = "a - b @ (c * x['key'] + 23)"
  1036. compiled_code, _ = self.check_positions_against_ast(snippet)
  1037. self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_SUBSCR',
  1038. line=1, end_line=1, column=13, end_column=21)
  1039. self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
  1040. line=1, end_line=1, column=9, end_column=21, occurrence=1)
  1041. self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
  1042. line=1, end_line=1, column=9, end_column=26, occurrence=2)
  1043. self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
  1044. line=1, end_line=1, column=4, end_column=27, occurrence=3)
  1045. self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
  1046. line=1, end_line=1, column=0, end_column=27, occurrence=4)
  1047. def test_multiline_assert_rewritten_as_method_call(self):
  1048. # GH-94694: Don't crash if pytest rewrites a multiline assert as a
  1049. # method call with the same location information:
  1050. tree = ast.parse("assert (\n42\n)")
  1051. old_node = tree.body[0]
  1052. new_node = ast.Expr(
  1053. ast.Call(
  1054. ast.Attribute(
  1055. ast.Name("spam", ast.Load()),
  1056. "eggs",
  1057. ast.Load(),
  1058. ),
  1059. [],
  1060. [],
  1061. )
  1062. )
  1063. ast.copy_location(new_node, old_node)
  1064. ast.fix_missing_locations(new_node)
  1065. tree.body[0] = new_node
  1066. compile(tree, "<test>", "exec")
  1067. def test_push_null_load_global_positions(self):
  1068. source_template = """
  1069. import abc, dis
  1070. import ast as art
  1071. abc = None
  1072. dix = dis
  1073. ast = art
  1074. def f():
  1075. {}
  1076. """
  1077. for body in [
  1078. " abc.a()",
  1079. " art.a()",
  1080. " ast.a()",
  1081. " dis.a()",
  1082. " dix.a()",
  1083. " abc[...]()",
  1084. " art()()",
  1085. " (ast or ...)()",
  1086. " [dis]()",
  1087. " (dix + ...)()",
  1088. ]:
  1089. with self.subTest(body):
  1090. namespace = {}
  1091. source = textwrap.dedent(source_template.format(body))
  1092. exec(source, namespace)
  1093. code = namespace["f"].__code__
  1094. self.assertOpcodeSourcePositionIs(
  1095. code,
  1096. "LOAD_GLOBAL",
  1097. line=10,
  1098. end_line=10,
  1099. column=4,
  1100. end_column=7,
  1101. )
  1102. def test_attribute_augassign(self):
  1103. source = "(\n lhs \n . \n rhs \n ) += 42"
  1104. code = compile(source, "<test>", "exec")
  1105. self.assertOpcodeSourcePositionIs(
  1106. code, "LOAD_ATTR", line=4, end_line=4, column=5, end_column=8
  1107. )
  1108. self.assertOpcodeSourcePositionIs(
  1109. code, "STORE_ATTR", line=4, end_line=4, column=5, end_column=8
  1110. )
  1111. def test_attribute_del(self):
  1112. source = "del (\n lhs \n . \n rhs \n )"
  1113. code = compile(source, "<test>", "exec")
  1114. self.assertOpcodeSourcePositionIs(
  1115. code, "DELETE_ATTR", line=4, end_line=4, column=5, end_column=8
  1116. )
  1117. def test_attribute_load(self):
  1118. source = "(\n lhs \n . \n rhs \n )"
  1119. code = compile(source, "<test>", "exec")
  1120. self.assertOpcodeSourcePositionIs(
  1121. code, "LOAD_ATTR", line=4, end_line=4, column=5, end_column=8
  1122. )
  1123. def test_attribute_store(self):
  1124. source = "(\n lhs \n . \n rhs \n ) = 42"
  1125. code = compile(source, "<test>", "exec")
  1126. self.assertOpcodeSourcePositionIs(
  1127. code, "STORE_ATTR", line=4, end_line=4, column=5, end_column=8
  1128. )
  1129. def test_method_call(self):
  1130. source = "(\n lhs \n . \n rhs \n )()"
  1131. code = compile(source, "<test>", "exec")
  1132. self.assertOpcodeSourcePositionIs(
  1133. code, "LOAD_METHOD", line=4, end_line=4, column=5, end_column=8
  1134. )
  1135. self.assertOpcodeSourcePositionIs(
  1136. code, "CALL", line=4, end_line=5, column=5, end_column=10
  1137. )
  1138. def test_weird_attribute_position_regressions(self):
  1139. def f():
  1140. (bar.
  1141. baz)
  1142. (bar.
  1143. baz(
  1144. ))
  1145. files().setdefault(
  1146. 0
  1147. ).setdefault(
  1148. 0
  1149. )
  1150. for line, end_line, column, end_column in f.__code__.co_positions():
  1151. self.assertIsNotNone(line)
  1152. self.assertIsNotNone(end_line)
  1153. self.assertIsNotNone(column)
  1154. self.assertIsNotNone(end_column)
  1155. self.assertLessEqual((line, column), (end_line, end_column))
  1156. @support.cpython_only
  1157. def test_column_offset_deduplication(self):
  1158. # GH-95150: Code with different column offsets shouldn't be merged!
  1159. for source in [
  1160. "lambda: a",
  1161. "(a for b in c)",
  1162. "[a for b in c]",
  1163. "{a for b in c}",
  1164. "{a: b for c in d}",
  1165. ]:
  1166. with self.subTest(source):
  1167. code = compile(f"{source}, {source}", "<test>", "eval")
  1168. self.assertEqual(len(code.co_consts), 2)
  1169. self.assertIsInstance(code.co_consts[0], types.CodeType)
  1170. self.assertIsInstance(code.co_consts[1], types.CodeType)
  1171. self.assertNotEqual(code.co_consts[0], code.co_consts[1])
  1172. self.assertNotEqual(
  1173. list(code.co_consts[0].co_positions()),
  1174. list(code.co_consts[1].co_positions()),
  1175. )
  1176. class TestExpressionStackSize(unittest.TestCase):
  1177. # These tests check that the computed stack size for a code object
  1178. # stays within reasonable bounds (see issue #21523 for an example
  1179. # dysfunction).
  1180. N = 100
  1181. def check_stack_size(self, code):
  1182. # To assert that the alleged stack size is not O(N), we
  1183. # check that it is smaller than log(N).
  1184. if isinstance(code, str):
  1185. code = compile(code, "<foo>", "single")
  1186. max_size = math.ceil(math.log(len(code.co_code)))
  1187. self.assertLessEqual(code.co_stacksize, max_size)
  1188. def test_and(self):
  1189. self.check_stack_size("x and " * self.N + "x")
  1190. def test_or(self):
  1191. self.check_stack_size("x or " * self.N + "x")
  1192. def test_and_or(self):
  1193. self.check_stack_size("x and x or " * self.N + "x")
  1194. def test_chained_comparison(self):
  1195. self.check_stack_size("x < " * self.N + "x")
  1196. def test_if_else(self):
  1197. self.check_stack_size("x if x else " * self.N + "x")
  1198. def test_binop(self):
  1199. self.check_stack_size("x + " * self.N + "x")
  1200. def test_list(self):
  1201. self.check_stack_size("[" + "x, " * self.N + "x]")
  1202. def test_tuple(self):
  1203. self.check_stack_size("(" + "x, " * self.N + "x)")
  1204. def test_set(self):
  1205. self.check_stack_size("{" + "x, " * self.N + "x}")
  1206. def test_dict(self):
  1207. self.check_stack_size("{" + "x:x, " * self.N + "x:x}")
  1208. def test_func_args(self):
  1209. self.check_stack_size("f(" + "x, " * self.N + ")")
  1210. def test_func_kwargs(self):
  1211. kwargs = (f'a{i}=x' for i in range(self.N))
  1212. self.check_stack_size("f(" + ", ".join(kwargs) + ")")
  1213. def test_meth_args(self):
  1214. self.check_stack_size("o.m(" + "x, " * self.N + ")")
  1215. def test_meth_kwargs(self):
  1216. kwargs = (f'a{i}=x' for i in range(self.N))
  1217. self.check_stack_size("o.m(" + ", ".join(kwargs) + ")")
  1218. def test_func_and(self):
  1219. code = "def f(x):\n"
  1220. code += " x and x\n" * self.N
  1221. self.check_stack_size(code)
  1222. def test_stack_3050(self):
  1223. M = 3050
  1224. code = "x," * M + "=t"
  1225. # This raised on 3.10.0 to 3.10.5
  1226. compile(code, "<foo>", "single")
  1227. def test_stack_3050_2(self):
  1228. M = 3050
  1229. args = ", ".join(f"arg{i}:type{i}" for i in range(M))
  1230. code = f"def f({args}):\n pass"
  1231. # This raised on 3.10.0 to 3.10.5
  1232. compile(code, "<foo>", "single")
  1233. class TestStackSizeStability(unittest.TestCase):
  1234. # Check that repeating certain snippets doesn't increase the stack size
  1235. # beyond what a single snippet requires.
  1236. def check_stack_size(self, snippet, async_=False):
  1237. def compile_snippet(i):
  1238. ns = {}
  1239. script = """def func():\n""" + i * snippet
  1240. if async_:
  1241. script = "async " + script
  1242. code = compile(script, "<script>", "exec")
  1243. exec(code, ns, ns)
  1244. return ns['func'].__code__
  1245. sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)]
  1246. if len(set(sizes)) != 1:
  1247. import dis, io
  1248. out = io.StringIO()
  1249. dis.dis(compile_snippet(1), file=out)
  1250. self.fail("stack sizes diverge with # of consecutive snippets: "
  1251. "%s\n%s\n%s" % (sizes, snippet, out.getvalue()))
  1252. def test_if(self):
  1253. snippet = """
  1254. if x:
  1255. a
  1256. """
  1257. self.check_stack_size(snippet)
  1258. def test_if_else(self):
  1259. snippet = """
  1260. if x:
  1261. a
  1262. elif y:
  1263. b
  1264. else:
  1265. c
  1266. """
  1267. self.check_stack_size(snippet)
  1268. def test_try_except_bare(self):
  1269. snippet = """
  1270. try:
  1271. a
  1272. except:
  1273. b
  1274. """
  1275. self.check_stack_size(snippet)
  1276. def test_try_except_qualified(self):
  1277. snippet = """
  1278. try:
  1279. a
  1280. except ImportError:
  1281. b
  1282. except:
  1283. c
  1284. else:
  1285. d
  1286. """
  1287. self.check_stack_size(snippet)
  1288. def test_try_except_as(self):
  1289. snippet = """
  1290. try:
  1291. a
  1292. except ImportError as e:
  1293. b
  1294. except:
  1295. c
  1296. else:
  1297. d
  1298. """
  1299. self.check_stack_size(snippet)
  1300. def test_try_except_star_qualified(self):
  1301. snippet = """
  1302. try:
  1303. a
  1304. except* ImportError:
  1305. b
  1306. else:
  1307. c
  1308. """
  1309. self.check_stack_size(snippet)
  1310. def test_try_except_star_as(self):
  1311. snippet = """
  1312. try:
  1313. a
  1314. except* ImportError as e:
  1315. b
  1316. else:
  1317. c
  1318. """
  1319. self.check_stack_size(snippet)
  1320. def test_try_except_star_finally(self):
  1321. snippet = """
  1322. try:
  1323. a
  1324. except* A:
  1325. b
  1326. finally:
  1327. c
  1328. """
  1329. self.check_stack_size(snippet)
  1330. def test_try_finally(self):
  1331. snippet = """
  1332. try:
  1333. a
  1334. finally:
  1335. b
  1336. """
  1337. self.check_stack_size(snippet)
  1338. def test_with(self):
  1339. snippet = """
  1340. with x as y:
  1341. a
  1342. """
  1343. self.check_stack_size(snippet)
  1344. def test_while_else(self):
  1345. snippet = """
  1346. while x:
  1347. a
  1348. else:
  1349. b
  1350. """
  1351. self.check_stack_size(snippet)
  1352. def test_for(self):
  1353. snippet = """
  1354. for x in y:
  1355. a
  1356. """
  1357. self.check_stack_size(snippet)
  1358. def test_for_else(self):
  1359. snippet = """
  1360. for x in y:
  1361. a
  1362. else:
  1363. b
  1364. """
  1365. self.check_stack_size(snippet)
  1366. def test_for_break_continue(self):
  1367. snippet = """
  1368. for x in y:
  1369. if z:
  1370. break
  1371. elif u:
  1372. continue
  1373. else:
  1374. a
  1375. else:
  1376. b
  1377. """
  1378. self.check_stack_size(snippet)
  1379. def test_for_break_continue_inside_try_finally_block(self):
  1380. snippet = """
  1381. for x in y:
  1382. try:
  1383. if z:
  1384. break
  1385. elif u:
  1386. continue
  1387. else:
  1388. a
  1389. finally:
  1390. f
  1391. else:
  1392. b
  1393. """
  1394. self.check_stack_size(snippet)
  1395. def test_for_break_continue_inside_finally_block(self):
  1396. snippet = """
  1397. for x in y:
  1398. try:
  1399. t
  1400. finally:
  1401. if z:
  1402. break
  1403. elif u:
  1404. continue
  1405. else:
  1406. a
  1407. else:
  1408. b
  1409. """
  1410. self.check_stack_size(snippet)
  1411. def test_for_break_continue_inside_except_block(self):
  1412. snippet = """
  1413. for x in y:
  1414. try:
  1415. t
  1416. except:
  1417. if z:
  1418. break
  1419. elif u:
  1420. continue
  1421. else:
  1422. a
  1423. else:
  1424. b
  1425. """
  1426. self.check_stack_size(snippet)
  1427. def test_for_break_continue_inside_with_block(self):
  1428. snippet = """
  1429. for x in y:
  1430. with c:
  1431. if z:
  1432. break
  1433. elif u:
  1434. continue
  1435. else:
  1436. a
  1437. else:
  1438. b
  1439. """
  1440. self.check_stack_size(snippet)
  1441. def test_return_inside_try_finally_block(self):
  1442. snippet = """
  1443. try:
  1444. if z:
  1445. return
  1446. else:
  1447. a
  1448. finally:
  1449. f
  1450. """
  1451. self.check_stack_size(snippet)
  1452. def test_return_inside_finally_block(self):
  1453. snippet = """
  1454. try:
  1455. t
  1456. finally:
  1457. if z:
  1458. return
  1459. else:
  1460. a
  1461. """
  1462. self.check_stack_size(snippet)
  1463. def test_return_inside_except_block(self):
  1464. snippet = """
  1465. try:
  1466. t
  1467. except:
  1468. if z:
  1469. return
  1470. else:
  1471. a
  1472. """
  1473. self.check_stack_size(snippet)
  1474. def test_return_inside_with_block(self):
  1475. snippet = """
  1476. with c:
  1477. if z:
  1478. return
  1479. else:
  1480. a
  1481. """
  1482. self.check_stack_size(snippet)
  1483. def test_async_with(self):
  1484. snippet = """
  1485. async with x as y:
  1486. a
  1487. """
  1488. self.check_stack_size(snippet, async_=True)
  1489. def test_async_for(self):
  1490. snippet = """
  1491. async for x in y:
  1492. a
  1493. """
  1494. self.check_stack_size(snippet, async_=True)
  1495. def test_async_for_else(self):
  1496. snippet = """
  1497. async for x in y:
  1498. a
  1499. else:
  1500. b
  1501. """
  1502. self.check_stack_size(snippet, async_=True)
  1503. def test_for_break_continue_inside_async_with_block(self):
  1504. snippet = """
  1505. for x in y:
  1506. async with c:
  1507. if z:
  1508. break
  1509. elif u:
  1510. continue
  1511. else:
  1512. a
  1513. else:
  1514. b
  1515. """
  1516. self.check_stack_size(snippet, async_=True)
  1517. def test_return_inside_async_with_block(self):
  1518. snippet = """
  1519. async with c:
  1520. if z:
  1521. return
  1522. else:
  1523. a
  1524. """
  1525. self.check_stack_size(snippet, async_=True)
  1526. if __name__ == "__main__":
  1527. unittest.main()