blob: 000549f5b6f1143df81a077b0eed02f6a97defe8 [file] [log] [blame]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001# Minimal tests for dis module
2
Zachary Ware38c707e2015-04-13 15:00:43 -05003from test.support import captured_stdout
Joannah Nanjekye92777d52019-09-12 10:02:59 +01004from test.support.bytecode_helper import BytecodeTestCase
Guido van Rossumd8faa362007-04-27 19:54:29 +00005import unittest
Skip Montanaroadd0ccc2003-02-27 21:27:07 +00006import sys
7import dis
Guido van Rossum34d19282007-08-09 01:03:29 +00008import io
Zachary Waree80e8062013-12-26 09:53:49 -06009import re
Nick Coghlanb39fd0c2013-05-06 23:59:20 +100010import types
Nick Coghlan90b8e7d2013-11-06 22:08:36 +100011import contextlib
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000012
Nick Coghlan50c48b82013-11-23 00:57:00 +100013def get_tb():
14 def _error():
15 try:
16 1 / 0
17 except Exception as e:
18 tb = e.__traceback__
19 return tb
20
21 tb = _error()
22 while tb.tb_next:
23 tb = tb.tb_next
24 return tb
25
26TRACEBACK_CODE = get_tb().tb_frame.f_code
27
Benjamin Petersond6afe722011-03-15 14:44:52 -050028class _C:
29 def __init__(self, x):
30 self.x = x == 1
31
Serhiy Storchaka585c93d2016-04-23 09:23:52 +030032 @staticmethod
33 def sm(x):
34 x = x == 1
35
36 @classmethod
37 def cm(cls, x):
38 cls.x = x == 1
39
Benjamin Petersond6afe722011-03-15 14:44:52 -050040dis_c_instance_method = """\
Serhiy Storchaka247763d2016-04-12 08:46:28 +030041%3d 0 LOAD_FAST 1 (x)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030042 2 LOAD_CONST 1 (1)
43 4 COMPARE_OP 2 (==)
44 6 LOAD_FAST 0 (self)
45 8 STORE_ATTR 0 (x)
46 10 LOAD_CONST 0 (None)
47 12 RETURN_VALUE
Benjamin Petersond6afe722011-03-15 14:44:52 -050048""" % (_C.__init__.__code__.co_firstlineno + 1,)
49
50dis_c_instance_method_bytes = """\
Nick Coghlanb39fd0c2013-05-06 23:59:20 +100051 0 LOAD_FAST 1 (1)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030052 2 LOAD_CONST 1 (1)
53 4 COMPARE_OP 2 (==)
54 6 LOAD_FAST 0 (0)
55 8 STORE_ATTR 0 (0)
56 10 LOAD_CONST 0 (0)
57 12 RETURN_VALUE
Benjamin Petersond6afe722011-03-15 14:44:52 -050058"""
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000059
Serhiy Storchaka585c93d2016-04-23 09:23:52 +030060dis_c_class_method = """\
61%3d 0 LOAD_FAST 1 (x)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030062 2 LOAD_CONST 1 (1)
63 4 COMPARE_OP 2 (==)
64 6 LOAD_FAST 0 (cls)
65 8 STORE_ATTR 0 (x)
66 10 LOAD_CONST 0 (None)
67 12 RETURN_VALUE
Serhiy Storchaka585c93d2016-04-23 09:23:52 +030068""" % (_C.cm.__code__.co_firstlineno + 2,)
69
70dis_c_static_method = """\
71%3d 0 LOAD_FAST 0 (x)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030072 2 LOAD_CONST 1 (1)
73 4 COMPARE_OP 2 (==)
74 6 STORE_FAST 0 (x)
75 8 LOAD_CONST 0 (None)
76 10 RETURN_VALUE
Serhiy Storchaka585c93d2016-04-23 09:23:52 +030077""" % (_C.sm.__code__.co_firstlineno + 2,)
78
79# Class disassembling info has an extra newline at end.
80dis_c = """\
81Disassembly of %s:
82%s
83Disassembly of %s:
84%s
85Disassembly of %s:
86%s
87""" % (_C.__init__.__name__, dis_c_instance_method,
88 _C.cm.__name__, dis_c_class_method,
89 _C.sm.__name__, dis_c_static_method)
90
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000091def _f(a):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000092 print(a)
Tim Peterseabafeb2003-03-07 15:55:36 +000093 return 1
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000094
95dis_f = """\
Serhiy Storchaka247763d2016-04-12 08:46:28 +030096%3d 0 LOAD_GLOBAL 0 (print)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030097 2 LOAD_FAST 0 (a)
Victor Stinnerf9b760f2016-09-09 10:17:08 -070098 4 CALL_FUNCTION 1
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030099 6 POP_TOP
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000100
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300101%3d 8 LOAD_CONST 1 (1)
102 10 RETURN_VALUE
Georg Brandlebbf63b2010-10-14 07:23:01 +0000103""" % (_f.__code__.co_firstlineno + 1,
104 _f.__code__.co_firstlineno + 2)
Michael W. Hudson26848a32003-04-29 17:07:36 +0000105
106
Benjamin Petersond6afe722011-03-15 14:44:52 -0500107dis_f_co_code = """\
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000108 0 LOAD_GLOBAL 0 (0)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300109 2 LOAD_FAST 0 (0)
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700110 4 CALL_FUNCTION 1
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300111 6 POP_TOP
112 8 LOAD_CONST 1 (1)
113 10 RETURN_VALUE
Benjamin Petersond6afe722011-03-15 14:44:52 -0500114"""
115
116
Michael W. Hudson26848a32003-04-29 17:07:36 +0000117def bug708901():
118 for res in range(1,
119 10):
120 pass
121
122dis_bug708901 = """\
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200123%3d 0 LOAD_GLOBAL 0 (range)
124 2 LOAD_CONST 1 (1)
Michael W. Hudson26848a32003-04-29 17:07:36 +0000125
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200126%3d 4 LOAD_CONST 2 (10)
Serhiy Storchakada8d72c2018-09-17 15:17:29 +0300127
128%3d 6 CALL_FUNCTION 2
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200129 8 GET_ITER
Mark Shannonfcb55c02021-04-01 16:00:31 +0100130 >> 10 FOR_ITER 2 (to 16)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200131 12 STORE_FAST 0 (res)
Michael W. Hudson26848a32003-04-29 17:07:36 +0000132
Mark Shannonfcb55c02021-04-01 16:00:31 +0100133%3d 14 JUMP_ABSOLUTE 5 (to 10)
Mark Shannon5977a792020-12-02 13:31:40 +0000134
135%3d >> 16 LOAD_CONST 0 (None)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200136 18 RETURN_VALUE
Georg Brandlebbf63b2010-10-14 07:23:01 +0000137""" % (bug708901.__code__.co_firstlineno + 1,
138 bug708901.__code__.co_firstlineno + 2,
Serhiy Storchakada8d72c2018-09-17 15:17:29 +0300139 bug708901.__code__.co_firstlineno + 1,
Mark Shannon5977a792020-12-02 13:31:40 +0000140 bug708901.__code__.co_firstlineno + 3,
141 bug708901.__code__.co_firstlineno + 1)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000142
Neal Norwitz51abbc72005-12-18 07:06:23 +0000143
144def bug1333982(x=[]):
145 assert 0, ([s for s in x] +
146 1)
147 pass
148
149dis_bug1333982 = """\
Mark Shannon266b4622020-11-17 19:30:14 +0000150%3d 0 LOAD_ASSERTION_ERROR
151 2 LOAD_CONST 2 (<code object <listcomp> at 0x..., file "%s", line %d>)
152 4 LOAD_CONST 3 ('bug1333982.<locals>.<listcomp>')
153 6 MAKE_FUNCTION 0
154 8 LOAD_FAST 0 (x)
155 10 GET_ITER
156 12 CALL_FUNCTION 1
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300157
Mark Shannon266b4622020-11-17 19:30:14 +0000158%3d 14 LOAD_CONST 4 (1)
Serhiy Storchakada8d72c2018-09-17 15:17:29 +0300159
Mark Shannon266b4622020-11-17 19:30:14 +0000160%3d 16 BINARY_ADD
161 18 CALL_FUNCTION 1
162 20 RAISE_VARARGS 1
Georg Brandlebbf63b2010-10-14 07:23:01 +0000163""" % (bug1333982.__code__.co_firstlineno + 1,
Zachary Waree80e8062013-12-26 09:53:49 -0600164 __file__,
165 bug1333982.__code__.co_firstlineno + 1,
Georg Brandlebbf63b2010-10-14 07:23:01 +0000166 bug1333982.__code__.co_firstlineno + 2,
Mark Shannon266b4622020-11-17 19:30:14 +0000167 bug1333982.__code__.co_firstlineno + 1)
Neal Norwitz51abbc72005-12-18 07:06:23 +0000168
Yurii Karabasf24b8102020-12-04 17:20:53 +0200169
170def bug42562():
171 pass
172
173
174# Set line number for 'pass' to None
Mark Shannonc76da792021-04-29 13:12:51 +0100175bug42562.__code__ = bug42562.__code__.replace(co_linetable=b'\x04\x80')
Yurii Karabasf24b8102020-12-04 17:20:53 +0200176
177
178dis_bug42562 = """\
179 0 LOAD_CONST 0 (None)
180 2 RETURN_VALUE
181"""
182
Irit Katrielc5bfb882021-11-09 22:05:30 +0000183# Extended arg followed by NOP
184code_bug_45757 = bytes([
185 0x90, 0x01, # EXTENDED_ARG 0x01
186 0x09, 0xFF, # NOP 0xFF
187 0x90, 0x01, # EXTENDED_ARG 0x01
188 0x64, 0x29, # LOAD_CONST 0x29
189 0x53, 0x00, # RETURN_VALUE 0x00
190 ])
191
192dis_bug_45757 = """\
193 0 EXTENDED_ARG 1
194 2 NOP
195 4 EXTENDED_ARG 1
196 6 LOAD_CONST 297 (297)
197 8 RETURN_VALUE
198"""
199
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000200_BIG_LINENO_FORMAT = """\
201%3d 0 LOAD_GLOBAL 0 (spam)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300202 2 POP_TOP
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000203 4 LOAD_CONST 0 (None)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300204 6 RETURN_VALUE
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000205"""
206
Serhiy Storchakad90045f2017-04-19 20:36:31 +0300207_BIG_LINENO_FORMAT2 = """\
208%4d 0 LOAD_GLOBAL 0 (spam)
209 2 POP_TOP
210 4 LOAD_CONST 0 (None)
211 6 RETURN_VALUE
212"""
213
Guido van Rossume7ba4952007-06-06 23:52:48 +0000214dis_module_expected_results = """\
215Disassembly of f:
216 4 0 LOAD_CONST 0 (None)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300217 2 RETURN_VALUE
Guido van Rossume7ba4952007-06-06 23:52:48 +0000218
219Disassembly of g:
220 5 0 LOAD_CONST 0 (None)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300221 2 RETURN_VALUE
Guido van Rossume7ba4952007-06-06 23:52:48 +0000222
223"""
224
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000225expr_str = "x + 1"
226
227dis_expr_str = """\
228 1 0 LOAD_NAME 0 (x)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300229 2 LOAD_CONST 0 (1)
230 4 BINARY_ADD
231 6 RETURN_VALUE
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000232"""
233
234simple_stmt_str = "x = x + 1"
235
236dis_simple_stmt_str = """\
237 1 0 LOAD_NAME 0 (x)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300238 2 LOAD_CONST 0 (1)
239 4 BINARY_ADD
240 6 STORE_NAME 0 (x)
241 8 LOAD_CONST 1 (None)
242 10 RETURN_VALUE
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000243"""
244
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700245annot_stmt_str = """\
246
247x: int = 1
248y: fun(1)
249lst[fun(0)]: int = 1
250"""
251# leading newline is for a reason (tests lineno)
252
253dis_annot_stmt_str = """\
254 2 0 SETUP_ANNOTATIONS
255 2 LOAD_CONST 0 (1)
256 4 STORE_NAME 0 (x)
Pablo Galindob0544ba2021-04-21 12:41:19 +0100257 6 LOAD_NAME 1 (int)
258 8 LOAD_NAME 2 (__annotations__)
259 10 LOAD_CONST 1 ('x')
Mark Shannon332cd5e2018-01-30 00:41:04 +0000260 12 STORE_SUBSCR
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700261
Pablo Galindob0544ba2021-04-21 12:41:19 +0100262 3 14 LOAD_NAME 3 (fun)
263 16 LOAD_CONST 0 (1)
264 18 CALL_FUNCTION 1
265 20 LOAD_NAME 2 (__annotations__)
266 22 LOAD_CONST 2 ('y')
267 24 STORE_SUBSCR
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700268
Pablo Galindob0544ba2021-04-21 12:41:19 +0100269 4 26 LOAD_CONST 0 (1)
270 28 LOAD_NAME 4 (lst)
271 30 LOAD_NAME 3 (fun)
272 32 LOAD_CONST 3 (0)
273 34 CALL_FUNCTION 1
274 36 STORE_SUBSCR
275 38 LOAD_NAME 1 (int)
276 40 POP_TOP
277 42 LOAD_CONST 4 (None)
278 44 RETURN_VALUE
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700279"""
280
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000281compound_stmt_str = """\
282x = 0
283while 1:
284 x += 1"""
285# Trailing newline has been deliberately omitted
286
287dis_compound_stmt_str = """\
288 1 0 LOAD_CONST 0 (0)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300289 2 STORE_NAME 0 (x)
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000290
Mark Shannon8473cf82020-12-15 11:07:50 +0000291 2 4 NOP
292
293 3 >> 6 LOAD_NAME 0 (x)
294 8 LOAD_CONST 1 (1)
295 10 INPLACE_ADD
296 12 STORE_NAME 0 (x)
297
Mark Shannonfcb55c02021-04-01 16:00:31 +0100298 2 14 JUMP_ABSOLUTE 3 (to 6)
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000299"""
Guido van Rossume7ba4952007-06-06 23:52:48 +0000300
Nick Coghlan50c48b82013-11-23 00:57:00 +1000301dis_traceback = """\
Mark Shannonfcb55c02021-04-01 16:00:31 +0100302%3d 0 SETUP_FINALLY 7 (to 16)
Nick Coghlan50c48b82013-11-23 00:57:00 +1000303
Serhiy Storchakab0f80b02016-05-24 09:15:14 +0300304%3d 2 LOAD_CONST 1 (1)
305 4 LOAD_CONST 2 (0)
306 --> 6 BINARY_TRUE_DIVIDE
307 8 POP_TOP
308 10 POP_BLOCK
Nick Coghlan50c48b82013-11-23 00:57:00 +1000309
Mark Shannoncc75ab72020-11-12 19:49:33 +0000310%3d 12 LOAD_FAST 1 (tb)
311 14 RETURN_VALUE
Nick Coghlan50c48b82013-11-23 00:57:00 +1000312
Mark Shannoncc75ab72020-11-12 19:49:33 +0000313%3d >> 16 DUP_TOP
314 18 LOAD_GLOBAL 0 (Exception)
Mark Shannonfcb55c02021-04-01 16:00:31 +0100315 20 JUMP_IF_NOT_EXC_MATCH 29 (to 58)
Mark Shannoncc75ab72020-11-12 19:49:33 +0000316 22 POP_TOP
317 24 STORE_FAST 0 (e)
318 26 POP_TOP
Mark Shannonfcb55c02021-04-01 16:00:31 +0100319 28 SETUP_FINALLY 10 (to 50)
Nick Coghlan50c48b82013-11-23 00:57:00 +1000320
Mark Shannoncc75ab72020-11-12 19:49:33 +0000321%3d 30 LOAD_FAST 0 (e)
322 32 LOAD_ATTR 1 (__traceback__)
323 34 STORE_FAST 1 (tb)
324 36 POP_BLOCK
325 38 POP_EXCEPT
326 40 LOAD_CONST 0 (None)
327 42 STORE_FAST 0 (e)
328 44 DELETE_FAST 0 (e)
329
330%3d 46 LOAD_FAST 1 (tb)
331 48 RETURN_VALUE
332 >> 50 LOAD_CONST 0 (None)
333 52 STORE_FAST 0 (e)
334 54 DELETE_FAST 0 (e)
Mark Shannonbf353f32020-12-17 13:55:28 +0000335 56 RERAISE 1
Mark Shannon5977a792020-12-02 13:31:40 +0000336
Mark Shannonbf353f32020-12-17 13:55:28 +0000337%3d >> 58 RERAISE 0
Nick Coghlan50c48b82013-11-23 00:57:00 +1000338""" % (TRACEBACK_CODE.co_firstlineno + 1,
339 TRACEBACK_CODE.co_firstlineno + 2,
Mark Shannoncc75ab72020-11-12 19:49:33 +0000340 TRACEBACK_CODE.co_firstlineno + 5,
Nick Coghlan50c48b82013-11-23 00:57:00 +1000341 TRACEBACK_CODE.co_firstlineno + 3,
342 TRACEBACK_CODE.co_firstlineno + 4,
Mark Shannon5977a792020-12-02 13:31:40 +0000343 TRACEBACK_CODE.co_firstlineno + 5,
344 TRACEBACK_CODE.co_firstlineno + 3)
Nick Coghlan50c48b82013-11-23 00:57:00 +1000345
Serhiy Storchakadd102f72016-10-08 12:34:25 +0300346def _fstring(a, b, c, d):
347 return f'{a} {b:4} {c!r} {d!r:4}'
348
349dis_fstring = """\
350%3d 0 LOAD_FAST 0 (a)
351 2 FORMAT_VALUE 0
352 4 LOAD_CONST 1 (' ')
353 6 LOAD_FAST 1 (b)
354 8 LOAD_CONST 2 ('4')
355 10 FORMAT_VALUE 4 (with format)
356 12 LOAD_CONST 1 (' ')
357 14 LOAD_FAST 2 (c)
358 16 FORMAT_VALUE 2 (repr)
359 18 LOAD_CONST 1 (' ')
360 20 LOAD_FAST 3 (d)
361 22 LOAD_CONST 2 ('4')
362 24 FORMAT_VALUE 6 (repr, with format)
363 26 BUILD_STRING 7
364 28 RETURN_VALUE
365""" % (_fstring.__code__.co_firstlineno + 1,)
366
Mark Shannon88dce262019-12-30 09:53:36 +0000367def _tryfinally(a, b):
368 try:
369 return a
370 finally:
371 b()
372
373def _tryfinallyconst(b):
374 try:
375 return 1
376 finally:
377 b()
378
379dis_tryfinally = """\
Mark Shannonfcb55c02021-04-01 16:00:31 +0100380%3d 0 SETUP_FINALLY 6 (to 14)
Mark Shannon88dce262019-12-30 09:53:36 +0000381
382%3d 2 LOAD_FAST 0 (a)
383 4 POP_BLOCK
384
385%3d 6 LOAD_FAST 1 (b)
386 8 CALL_FUNCTION 0
387 10 POP_TOP
Mark Shannon5274b682020-12-16 13:07:01 +0000388 12 RETURN_VALUE
389 >> 14 LOAD_FAST 1 (b)
Mark Shannon88dce262019-12-30 09:53:36 +0000390 16 CALL_FUNCTION 0
391 18 POP_TOP
Mark Shannonbf353f32020-12-17 13:55:28 +0000392 20 RERAISE 0
Mark Shannon88dce262019-12-30 09:53:36 +0000393""" % (_tryfinally.__code__.co_firstlineno + 1,
394 _tryfinally.__code__.co_firstlineno + 2,
395 _tryfinally.__code__.co_firstlineno + 4,
Mark Shannon88dce262019-12-30 09:53:36 +0000396 )
397
398dis_tryfinallyconst = """\
Mark Shannonfcb55c02021-04-01 16:00:31 +0100399%3d 0 SETUP_FINALLY 6 (to 14)
Mark Shannon88dce262019-12-30 09:53:36 +0000400
401%3d 2 POP_BLOCK
402
403%3d 4 LOAD_FAST 0 (b)
404 6 CALL_FUNCTION 0
405 8 POP_TOP
Mark Shannon5274b682020-12-16 13:07:01 +0000406 10 LOAD_CONST 1 (1)
Mark Shannon88dce262019-12-30 09:53:36 +0000407 12 RETURN_VALUE
Mark Shannon5274b682020-12-16 13:07:01 +0000408 >> 14 LOAD_FAST 0 (b)
Mark Shannon88dce262019-12-30 09:53:36 +0000409 16 CALL_FUNCTION 0
410 18 POP_TOP
Mark Shannonbf353f32020-12-17 13:55:28 +0000411 20 RERAISE 0
Mark Shannon88dce262019-12-30 09:53:36 +0000412""" % (_tryfinallyconst.__code__.co_firstlineno + 1,
413 _tryfinallyconst.__code__.co_firstlineno + 2,
414 _tryfinallyconst.__code__.co_firstlineno + 4,
Mark Shannon88dce262019-12-30 09:53:36 +0000415 )
416
Nick Coghlanefd5df92014-07-25 23:02:56 +1000417def _g(x):
418 yield x
419
syncosmicfe2b56a2017-08-17 19:29:21 -0700420async def _ag(x):
421 yield x
422
423async def _co(x):
424 async for item in _ag(x):
425 pass
426
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300427def _h(y):
428 def foo(x):
429 '''funcdoc'''
430 return [x + z for z in y]
431 return foo
432
433dis_nested_0 = """\
434%3d 0 LOAD_CLOSURE 0 (y)
435 2 BUILD_TUPLE 1
436 4 LOAD_CONST 1 (<code object foo at 0x..., file "%s", line %d>)
437 6 LOAD_CONST 2 ('_h.<locals>.foo')
Serhiy Storchakae2732d32018-03-11 11:07:06 +0200438 8 MAKE_FUNCTION 8 (closure)
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300439 10 STORE_FAST 1 (foo)
440
441%3d 12 LOAD_FAST 1 (foo)
442 14 RETURN_VALUE
443""" % (_h.__code__.co_firstlineno + 1,
444 __file__,
445 _h.__code__.co_firstlineno + 1,
446 _h.__code__.co_firstlineno + 4,
447)
448
449dis_nested_1 = """%s
450Disassembly of <code object foo at 0x..., file "%s", line %d>:
451%3d 0 LOAD_CLOSURE 0 (x)
452 2 BUILD_TUPLE 1
453 4 LOAD_CONST 1 (<code object <listcomp> at 0x..., file "%s", line %d>)
454 6 LOAD_CONST 2 ('_h.<locals>.foo.<locals>.<listcomp>')
Serhiy Storchakae2732d32018-03-11 11:07:06 +0200455 8 MAKE_FUNCTION 8 (closure)
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300456 10 LOAD_DEREF 1 (y)
457 12 GET_ITER
458 14 CALL_FUNCTION 1
459 16 RETURN_VALUE
460""" % (dis_nested_0,
461 __file__,
462 _h.__code__.co_firstlineno + 1,
463 _h.__code__.co_firstlineno + 3,
464 __file__,
465 _h.__code__.co_firstlineno + 3,
466)
467
468dis_nested_2 = """%s
469Disassembly of <code object <listcomp> at 0x..., file "%s", line %d>:
470%3d 0 BUILD_LIST 0
471 2 LOAD_FAST 0 (.0)
Mark Shannonfcb55c02021-04-01 16:00:31 +0100472 >> 4 FOR_ITER 6 (to 18)
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300473 6 STORE_FAST 1 (z)
474 8 LOAD_DEREF 0 (x)
475 10 LOAD_FAST 1 (z)
476 12 BINARY_ADD
477 14 LIST_APPEND 2
Mark Shannonfcb55c02021-04-01 16:00:31 +0100478 16 JUMP_ABSOLUTE 2 (to 4)
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300479 >> 18 RETURN_VALUE
480""" % (dis_nested_1,
481 __file__,
482 _h.__code__.co_firstlineno + 3,
483 _h.__code__.co_firstlineno + 3,
484)
485
syncosmicfe2b56a2017-08-17 19:29:21 -0700486
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000487class DisTests(unittest.TestCase):
Benjamin Petersond6afe722011-03-15 14:44:52 -0500488
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300489 maxDiff = None
490
491 def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs):
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000492 # We want to test the default printing behaviour, not the file arg
493 output = io.StringIO()
494 with contextlib.redirect_stdout(output):
Benjamin Petersond6afe722011-03-15 14:44:52 -0500495 if wrapper:
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300496 dis.dis(func, **kwargs)
Benjamin Petersond6afe722011-03-15 14:44:52 -0500497 else:
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300498 dis.disassemble(func, lasti, **kwargs)
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000499 return output.getvalue()
Benjamin Petersond6afe722011-03-15 14:44:52 -0500500
501 def get_disassemble_as_string(self, func, lasti=-1):
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000502 return self.get_disassembly(func, lasti, False)
Benjamin Petersond6afe722011-03-15 14:44:52 -0500503
Zachary Warebb4b7c12013-12-26 09:55:24 -0600504 def strip_addresses(self, text):
505 return re.sub(r'\b0x[0-9A-Fa-f]+\b', '0x...', text)
Benjamin Petersond6afe722011-03-15 14:44:52 -0500506
507 def do_disassembly_test(self, func, expected):
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300508 got = self.get_disassembly(func, depth=0)
Zachary Warebb4b7c12013-12-26 09:55:24 -0600509 if got != expected:
510 got = self.strip_addresses(got)
511 self.assertEqual(got, expected)
Michael W. Hudson26848a32003-04-29 17:07:36 +0000512
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000513 def test_opmap(self):
Benjamin Peterson76f7f4d2011-07-17 22:49:50 -0500514 self.assertEqual(dis.opmap["NOP"], 9)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000515 self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst)
516 self.assertIn(dis.opmap["STORE_NAME"], dis.hasname)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000517
518 def test_opname(self):
519 self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST")
520
521 def test_boundaries(self):
522 self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG)
523 self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT)
524
Serhiy Storchakad90045f2017-04-19 20:36:31 +0300525 def test_widths(self):
526 for opcode, opname in enumerate(dis.opname):
527 if opname in ('BUILD_MAP_UNPACK_WITH_CALL',
Mark Shannon9af0e472020-01-14 10:12:45 +0000528 'BUILD_TUPLE_UNPACK_WITH_CALL',
529 'JUMP_IF_NOT_EXC_MATCH'):
Serhiy Storchakad90045f2017-04-19 20:36:31 +0300530 continue
531 with self.subTest(opname=opname):
532 width = dis._OPNAME_WIDTH
533 if opcode < dis.HAVE_ARGUMENT:
534 width += 1 + dis._OPARG_WIDTH
535 self.assertLessEqual(len(opname), width)
536
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000537 def test_dis(self):
Michael W. Hudson26848a32003-04-29 17:07:36 +0000538 self.do_disassembly_test(_f, dis_f)
539
540 def test_bug_708901(self):
541 self.do_disassembly_test(bug708901, dis_bug708901)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000542
Neal Norwitz51abbc72005-12-18 07:06:23 +0000543 def test_bug_1333982(self):
Tim Peters83a8c392005-12-25 22:52:32 +0000544 # This one is checking bytecodes generated for an `assert` statement,
545 # so fails if the tests are run with -O. Skip this test then.
Zachary Waree80e8062013-12-26 09:53:49 -0600546 if not __debug__:
547 self.skipTest('need asserts, run without -O')
Zachary Ware9fe6d862013-12-08 00:20:35 -0600548
Zachary Waree80e8062013-12-26 09:53:49 -0600549 self.do_disassembly_test(bug1333982, dis_bug1333982)
Neal Norwitz51abbc72005-12-18 07:06:23 +0000550
Yurii Karabasf24b8102020-12-04 17:20:53 +0200551 def test_bug_42562(self):
552 self.do_disassembly_test(bug42562, dis_bug42562)
553
Irit Katrielc5bfb882021-11-09 22:05:30 +0000554 def test_bug_45757(self):
555 # Extended arg followed by NOP
556 self.do_disassembly_test(code_bug_45757, dis_bug_45757)
557
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558 def test_big_linenos(self):
559 def func(count):
560 namespace = {}
561 func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"])
Georg Brandl7cae87c2006-09-06 06:51:57 +0000562 exec(func, namespace)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000563 return namespace['foo']
564
565 # Test all small ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000566 for i in range(1, 300):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000567 expected = _BIG_LINENO_FORMAT % (i + 2)
568 self.do_disassembly_test(func(i), expected)
569
570 # Test some larger ranges too
Serhiy Storchakad90045f2017-04-19 20:36:31 +0300571 for i in range(300, 1000, 10):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000572 expected = _BIG_LINENO_FORMAT % (i + 2)
573 self.do_disassembly_test(func(i), expected)
574
Serhiy Storchakad90045f2017-04-19 20:36:31 +0300575 for i in range(1000, 5000, 10):
576 expected = _BIG_LINENO_FORMAT2 % (i + 2)
577 self.do_disassembly_test(func(i), expected)
578
Guido van Rossume7ba4952007-06-06 23:52:48 +0000579 from test import dis_module
580 self.do_disassembly_test(dis_module, dis_module_expected_results)
581
Serhiy Storchakad90045f2017-04-19 20:36:31 +0300582 def test_big_offsets(self):
583 def func(count):
584 namespace = {}
585 func = "def foo(x):\n " + ";".join(["x = x + 1"] * count) + "\n return x"
586 exec(func, namespace)
587 return namespace['foo']
588
589 def expected(count, w):
590 s = ['''\
591 %*d LOAD_FAST 0 (x)
592 %*d LOAD_CONST 1 (1)
593 %*d BINARY_ADD
594 %*d STORE_FAST 0 (x)
595''' % (w, 8*i, w, 8*i + 2, w, 8*i + 4, w, 8*i + 6)
596 for i in range(count)]
597 s += ['''\
598
599 3 %*d LOAD_FAST 0 (x)
600 %*d RETURN_VALUE
601''' % (w, 8*count, w, 8*count + 2)]
602 s[0] = ' 2' + s[0][3:]
603 return ''.join(s)
604
605 for i in range(1, 5):
606 self.do_disassembly_test(func(i), expected(i, 4))
607 self.do_disassembly_test(func(1249), expected(1249, 4))
608 self.do_disassembly_test(func(1250), expected(1250, 5))
609
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000610 def test_disassemble_str(self):
611 self.do_disassembly_test(expr_str, dis_expr_str)
612 self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700613 self.do_disassembly_test(annot_stmt_str, dis_annot_stmt_str)
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000614 self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str)
615
Benjamin Petersond6afe722011-03-15 14:44:52 -0500616 def test_disassemble_bytes(self):
617 self.do_disassembly_test(_f.__code__.co_code, dis_f_co_code)
618
Serhiy Storchaka585c93d2016-04-23 09:23:52 +0300619 def test_disassemble_class(self):
620 self.do_disassembly_test(_C, dis_c)
621
622 def test_disassemble_instance_method(self):
Benjamin Petersond6afe722011-03-15 14:44:52 -0500623 self.do_disassembly_test(_C(1).__init__, dis_c_instance_method)
624
Serhiy Storchaka585c93d2016-04-23 09:23:52 +0300625 def test_disassemble_instance_method_bytes(self):
Benjamin Petersond6afe722011-03-15 14:44:52 -0500626 method_bytecode = _C(1).__init__.__code__.co_code
627 self.do_disassembly_test(method_bytecode, dis_c_instance_method_bytes)
628
Serhiy Storchaka585c93d2016-04-23 09:23:52 +0300629 def test_disassemble_static_method(self):
630 self.do_disassembly_test(_C.sm, dis_c_static_method)
631
632 def test_disassemble_class_method(self):
633 self.do_disassembly_test(_C.cm, dis_c_class_method)
634
Nick Coghlanefd5df92014-07-25 23:02:56 +1000635 def test_disassemble_generator(self):
syncosmicfe2b56a2017-08-17 19:29:21 -0700636 gen_func_disas = self.get_disassembly(_g) # Generator function
637 gen_disas = self.get_disassembly(_g(1)) # Generator iterator
Nick Coghlanefd5df92014-07-25 23:02:56 +1000638 self.assertEqual(gen_disas, gen_func_disas)
639
syncosmicfe2b56a2017-08-17 19:29:21 -0700640 def test_disassemble_async_generator(self):
641 agen_func_disas = self.get_disassembly(_ag) # Async generator function
642 agen_disas = self.get_disassembly(_ag(1)) # Async generator iterator
643 self.assertEqual(agen_disas, agen_func_disas)
644
645 def test_disassemble_coroutine(self):
646 coro_func_disas = self.get_disassembly(_co) # Coroutine function
647 coro = _co(1) # Coroutine object
648 coro.close() # Avoid a RuntimeWarning (never awaited)
649 coro_disas = self.get_disassembly(coro)
650 self.assertEqual(coro_disas, coro_func_disas)
651
Serhiy Storchakadd102f72016-10-08 12:34:25 +0300652 def test_disassemble_fstring(self):
653 self.do_disassembly_test(_fstring, dis_fstring)
654
Mark Shannon88dce262019-12-30 09:53:36 +0000655 def test_disassemble_try_finally(self):
656 self.do_disassembly_test(_tryfinally, dis_tryfinally)
657 self.do_disassembly_test(_tryfinallyconst, dis_tryfinallyconst)
658
Benjamin Petersond6afe722011-03-15 14:44:52 -0500659 def test_dis_none(self):
Benjamin Peterson47afc2a2011-03-15 15:54:50 -0500660 try:
661 del sys.last_traceback
662 except AttributeError:
663 pass
Benjamin Petersond6afe722011-03-15 14:44:52 -0500664 self.assertRaises(RuntimeError, dis.dis, None)
665
Benjamin Petersond6afe722011-03-15 14:44:52 -0500666 def test_dis_traceback(self):
Benjamin Peterson47afc2a2011-03-15 15:54:50 -0500667 try:
668 del sys.last_traceback
669 except AttributeError:
670 pass
Benjamin Petersond6afe722011-03-15 14:44:52 -0500671
672 try:
673 1/0
674 except Exception as e:
675 tb = e.__traceback__
676 sys.last_traceback = tb
Benjamin Petersond6afe722011-03-15 14:44:52 -0500677
678 tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti)
679 self.do_disassembly_test(None, tb_dis)
680
681 def test_dis_object(self):
682 self.assertRaises(TypeError, dis.dis, object())
683
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300684 def test_disassemble_recursive(self):
685 def check(expected, **kwargs):
686 dis = self.get_disassembly(_h, **kwargs)
687 dis = self.strip_addresses(dis)
688 self.assertEqual(dis, expected)
689
690 check(dis_nested_0, depth=0)
691 check(dis_nested_1, depth=1)
692 check(dis_nested_2, depth=2)
693 check(dis_nested_2, depth=3)
694 check(dis_nested_2, depth=None)
695 check(dis_nested_2)
696
697
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000698class DisWithFileTests(DisTests):
699
700 # Run the tests again, using the file arg instead of print
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300701 def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs):
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000702 output = io.StringIO()
703 if wrapper:
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300704 dis.dis(func, file=output, **kwargs)
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000705 else:
Serhiy Storchaka1efbf922017-06-11 14:09:39 +0300706 dis.disassemble(func, lasti, file=output, **kwargs)
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000707 return output.getvalue()
708
709
Mark Shannon266b4622020-11-17 19:30:14 +0000710if sys.flags.optimize:
711 code_info_consts = "0: None"
712else:
Ɓukasz Langad41abe82021-09-08 18:25:09 +0200713 code_info_consts = "0: 'Formatted details of methods, functions, or code.'"
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000714
Mark Shannon266b4622020-11-17 19:30:14 +0000715code_info_code_info = f"""\
Nick Coghlaneae2da12010-08-17 08:03:36 +0000716Name: code_info
Nick Coghlan46e63802010-08-17 11:28:07 +0000717Filename: (.*)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000718Argument count: 1
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100719Positional-only arguments: 0
Nick Coghlaneae2da12010-08-17 08:03:36 +0000720Kw-only arguments: 0
721Number of locals: 1
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000722Stack size: 3
Nick Coghlaneae2da12010-08-17 08:03:36 +0000723Flags: OPTIMIZED, NEWLOCALS, NOFREE
724Constants:
Mark Shannon266b4622020-11-17 19:30:14 +0000725 {code_info_consts}
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000726Names:
727 0: _format_code_info
728 1: _get_code_object
Nick Coghlaneae2da12010-08-17 08:03:36 +0000729Variable names:
Mark Shannon266b4622020-11-17 19:30:14 +0000730 0: x"""
731
Nick Coghlaneae2da12010-08-17 08:03:36 +0000732
733@staticmethod
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100734def tricky(a, b, /, x, y, z=True, *args, c, d, e=[], **kwds):
Nick Coghlaneae2da12010-08-17 08:03:36 +0000735 def f(c=c):
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100736 print(a, b, x, y, z, c, d, e, f)
737 yield a, b, x, y, z, c, d, e, f
Nick Coghlaneae2da12010-08-17 08:03:36 +0000738
Nick Coghlaneae2da12010-08-17 08:03:36 +0000739code_info_tricky = """\
740Name: tricky
Nick Coghlan46e63802010-08-17 11:28:07 +0000741Filename: (.*)
Pablo Galindocd74e662019-06-01 18:08:04 +0100742Argument count: 5
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100743Positional-only arguments: 2
Nick Coghlaneae2da12010-08-17 08:03:36 +0000744Kw-only arguments: 3
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100745Number of locals: 10
746Stack size: 9
Nick Coghlaneae2da12010-08-17 08:03:36 +0000747Flags: OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR
748Constants:
749 0: None
Nick Coghlan46e63802010-08-17 11:28:07 +0000750 1: <code object f at (.*), file "(.*)", line (.*)>
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100751 2: 'tricky.<locals>.f'
Nick Coghlaneae2da12010-08-17 08:03:36 +0000752Variable names:
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100753 0: a
754 1: b
755 2: x
756 3: y
757 4: z
758 5: c
759 6: d
760 7: e
761 8: args
762 9: kwds
Nick Coghlaneae2da12010-08-17 08:03:36 +0000763Cell variables:
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100764 0: [abedfxyz]
765 1: [abedfxyz]
766 2: [abedfxyz]
767 3: [abedfxyz]
768 4: [abedfxyz]
769 5: [abedfxyz]"""
Georg Brandla1082272012-02-20 21:41:03 +0100770# NOTE: the order of the cell variables above depends on dictionary order!
Nick Coghlan46e63802010-08-17 11:28:07 +0000771
772co_tricky_nested_f = tricky.__func__.__code__.co_consts[1]
Nick Coghlaneae2da12010-08-17 08:03:36 +0000773
774code_info_tricky_nested_f = """\
Nick Coghlan46e63802010-08-17 11:28:07 +0000775Filename: (.*)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000776Argument count: 1
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100777Positional-only arguments: 0
Nick Coghlaneae2da12010-08-17 08:03:36 +0000778Kw-only arguments: 0
779Number of locals: 1
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100780Stack size: 10
Nick Coghlaneae2da12010-08-17 08:03:36 +0000781Flags: OPTIMIZED, NEWLOCALS, NESTED
782Constants:
783 0: None
784Names:
785 0: print
786Variable names:
787 0: c
788Free variables:
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100789 0: [abedfxyz]
790 1: [abedfxyz]
791 2: [abedfxyz]
792 3: [abedfxyz]
793 4: [abedfxyz]
794 5: [abedfxyz]"""
Nick Coghlaneae2da12010-08-17 08:03:36 +0000795
796code_info_expr_str = """\
797Name: <module>
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000798Filename: <disassembly>
Nick Coghlaneae2da12010-08-17 08:03:36 +0000799Argument count: 0
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100800Positional-only arguments: 0
Nick Coghlaneae2da12010-08-17 08:03:36 +0000801Kw-only arguments: 0
802Number of locals: 0
803Stack size: 2
804Flags: NOFREE
805Constants:
806 0: 1
807Names:
808 0: x"""
809
810code_info_simple_stmt_str = """\
811Name: <module>
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000812Filename: <disassembly>
Nick Coghlaneae2da12010-08-17 08:03:36 +0000813Argument count: 0
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100814Positional-only arguments: 0
Nick Coghlaneae2da12010-08-17 08:03:36 +0000815Kw-only arguments: 0
816Number of locals: 0
817Stack size: 2
818Flags: NOFREE
819Constants:
820 0: 1
821 1: None
822Names:
823 0: x"""
824
825code_info_compound_stmt_str = """\
826Name: <module>
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000827Filename: <disassembly>
Nick Coghlaneae2da12010-08-17 08:03:36 +0000828Argument count: 0
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100829Positional-only arguments: 0
Nick Coghlaneae2da12010-08-17 08:03:36 +0000830Kw-only arguments: 0
831Number of locals: 0
832Stack size: 2
833Flags: NOFREE
834Constants:
835 0: 0
836 1: 1
Nick Coghlaneae2da12010-08-17 08:03:36 +0000837Names:
838 0: x"""
839
Yury Selivanov75445082015-05-11 22:57:16 -0400840
841async def async_def():
842 await 1
843 async for a in b: pass
844 async with c as d: pass
845
846code_info_async_def = """\
847Name: async_def
848Filename: (.*)
849Argument count: 0
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100850Positional-only arguments: 0
Yury Selivanov75445082015-05-11 22:57:16 -0400851Kw-only arguments: 0
852Number of locals: 2
Mark Shannonfee55262019-11-21 09:11:43 +0000853Stack size: 9
Yury Selivanoveb636452016-09-08 22:01:51 -0700854Flags: OPTIMIZED, NEWLOCALS, NOFREE, COROUTINE
Yury Selivanov75445082015-05-11 22:57:16 -0400855Constants:
856 0: None
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200857 1: 1
858Names:
859 0: b
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200860 1: c
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200861Variable names:
862 0: a
863 1: d"""
Yury Selivanov75445082015-05-11 22:57:16 -0400864
Nick Coghlaneae2da12010-08-17 08:03:36 +0000865class CodeInfoTests(unittest.TestCase):
866 test_pairs = [
867 (dis.code_info, code_info_code_info),
868 (tricky, code_info_tricky),
869 (co_tricky_nested_f, code_info_tricky_nested_f),
870 (expr_str, code_info_expr_str),
871 (simple_stmt_str, code_info_simple_stmt_str),
872 (compound_stmt_str, code_info_compound_stmt_str),
Yury Selivanov75445082015-05-11 22:57:16 -0400873 (async_def, code_info_async_def)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000874 ]
875
876 def test_code_info(self):
877 self.maxDiff = 1000
878 for x, expected in self.test_pairs:
Ezio Melottied3a7d22010-12-01 02:32:32 +0000879 self.assertRegex(dis.code_info(x), expected)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000880
881 def test_show_code(self):
882 self.maxDiff = 1000
883 for x, expected in self.test_pairs:
884 with captured_stdout() as output:
885 dis.show_code(x)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000886 self.assertRegex(output.getvalue(), expected+"\n")
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000887 output = io.StringIO()
888 dis.show_code(x, file=output)
889 self.assertRegex(output.getvalue(), expected)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000890
Benjamin Petersond6afe722011-03-15 14:44:52 -0500891 def test_code_info_object(self):
892 self.assertRaises(TypeError, dis.code_info, object())
893
894 def test_pretty_flags_no_flags(self):
895 self.assertEqual(dis.pretty_flags(0), '0x0')
896
897
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000898# Fodder for instruction introspection tests
899# Editing any of these may require recalculating the expected output
900def outer(a=1, b=2):
901 def f(c=3, d=4):
902 def inner(e=5, f=6):
903 print(a, b, c, d, e, f)
904 print(a, b, c, d)
905 return inner
906 print(a, b, '', 1, [], {}, "Hello world!")
907 return f
908
909def jumpy():
910 # This won't actually run (but that's OK, we only disassemble it)
911 for i in range(10):
912 print(i)
913 if i < 4:
914 continue
915 if i > 6:
916 break
917 else:
918 print("I can haz else clause?")
919 while i:
920 print(i)
921 i -= 1
922 if i > 6:
923 continue
924 if i < 4:
925 break
926 else:
927 print("Who let lolcatz into this test suite?")
928 try:
929 1 / 0
930 except ZeroDivisionError:
931 print("Here we go, here we go, here we go...")
932 else:
933 with i as dodgy:
934 print("Never reach this")
935 finally:
936 print("OK, now we're done")
937
938# End fodder for opinfo generation tests
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000939expected_outer_line = 1
940_line_offset = outer.__code__.co_firstlineno - 1
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000941code_object_f = outer.__code__.co_consts[3]
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000942expected_f_line = code_object_f.co_firstlineno - _line_offset
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000943code_object_inner = code_object_f.co_consts[3]
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000944expected_inner_line = code_object_inner.co_firstlineno - _line_offset
945expected_jumpy_line = 1
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000946
947# The following lines are useful to regenerate the expected results after
948# either the fodder is modified or the bytecode generation changes
949# After regeneration, update the references to code_object_f and
950# code_object_inner before rerunning the tests
951
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000952#_instructions = dis.get_instructions(outer, first_line=expected_outer_line)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000953#print('expected_opinfo_outer = [\n ',
954 #',\n '.join(map(str, _instructions)), ',\n]', sep='')
Antoine Pitroue7811fc2014-09-18 03:06:50 +0200955#_instructions = dis.get_instructions(outer(), first_line=expected_f_line)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000956#print('expected_opinfo_f = [\n ',
957 #',\n '.join(map(str, _instructions)), ',\n]', sep='')
Antoine Pitroue7811fc2014-09-18 03:06:50 +0200958#_instructions = dis.get_instructions(outer()(), first_line=expected_inner_line)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000959#print('expected_opinfo_inner = [\n ',
960 #',\n '.join(map(str, _instructions)), ',\n]', sep='')
Nick Coghlan90b8e7d2013-11-06 22:08:36 +1000961#_instructions = dis.get_instructions(jumpy, first_line=expected_jumpy_line)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000962#print('expected_opinfo_jumpy = [\n ',
963 #',\n '.join(map(str, _instructions)), ',\n]', sep='')
964
965
966Instruction = dis.Instruction
967expected_opinfo_outer = [
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300968 Instruction(opname='LOAD_CONST', opcode=100, arg=8, argval=(3, 4), argrepr='(3, 4)', offset=0, starts_line=2, is_jump_target=False),
969 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=0, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False),
970 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=1, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False),
971 Instruction(opname='BUILD_TUPLE', opcode=102, arg=2, argval=2, argrepr='', offset=6, starts_line=None, is_jump_target=False),
972 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=code_object_f, argrepr=repr(code_object_f), offset=8, starts_line=None, is_jump_target=False),
973 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='outer.<locals>.f', argrepr="'outer.<locals>.f'", offset=10, starts_line=None, is_jump_target=False),
Serhiy Storchakae2732d32018-03-11 11:07:06 +0200974 Instruction(opname='MAKE_FUNCTION', opcode=132, arg=9, argval=9, argrepr='defaults, closure', offset=12, starts_line=None, is_jump_target=False),
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300975 Instruction(opname='STORE_FAST', opcode=125, arg=2, argval='f', argrepr='f', offset=14, starts_line=None, is_jump_target=False),
976 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=16, starts_line=7, is_jump_target=False),
977 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=18, starts_line=None, is_jump_target=False),
978 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='b', argrepr='b', offset=20, starts_line=None, is_jump_target=False),
979 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval='', argrepr="''", offset=22, starts_line=None, is_jump_target=False),
980 Instruction(opname='LOAD_CONST', opcode=100, arg=6, argval=1, argrepr='1', offset=24, starts_line=None, is_jump_target=False),
981 Instruction(opname='BUILD_LIST', opcode=103, arg=0, argval=0, argrepr='', offset=26, starts_line=None, is_jump_target=False),
982 Instruction(opname='BUILD_MAP', opcode=105, arg=0, argval=0, argrepr='', offset=28, starts_line=None, is_jump_target=False),
983 Instruction(opname='LOAD_CONST', opcode=100, arg=7, argval='Hello world!', argrepr="'Hello world!'", offset=30, starts_line=None, is_jump_target=False),
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700984 Instruction(opname='CALL_FUNCTION', opcode=131, arg=7, argval=7, argrepr='', offset=32, starts_line=None, is_jump_target=False),
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300985 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=34, starts_line=None, is_jump_target=False),
986 Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='f', argrepr='f', offset=36, starts_line=8, is_jump_target=False),
987 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=38, starts_line=None, is_jump_target=False),
Nick Coghlanb39fd0c2013-05-06 23:59:20 +1000988]
989
990expected_opinfo_f = [
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300991 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=(5, 6), argrepr='(5, 6)', offset=0, starts_line=3, is_jump_target=False),
992 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=2, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False),
993 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=3, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False),
994 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=0, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False),
995 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=1, argval='d', argrepr='d', offset=8, starts_line=None, is_jump_target=False),
996 Instruction(opname='BUILD_TUPLE', opcode=102, arg=4, argval=4, argrepr='', offset=10, starts_line=None, is_jump_target=False),
997 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=code_object_inner, argrepr=repr(code_object_inner), offset=12, starts_line=None, is_jump_target=False),
998 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='outer.<locals>.f.<locals>.inner', argrepr="'outer.<locals>.f.<locals>.inner'", offset=14, starts_line=None, is_jump_target=False),
Serhiy Storchakae2732d32018-03-11 11:07:06 +0200999 Instruction(opname='MAKE_FUNCTION', opcode=132, arg=9, argval=9, argrepr='defaults, closure', offset=16, starts_line=None, is_jump_target=False),
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001000 Instruction(opname='STORE_FAST', opcode=125, arg=2, argval='inner', argrepr='inner', offset=18, starts_line=None, is_jump_target=False),
1001 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=20, starts_line=5, is_jump_target=False),
1002 Instruction(opname='LOAD_DEREF', opcode=136, arg=2, argval='a', argrepr='a', offset=22, starts_line=None, is_jump_target=False),
1003 Instruction(opname='LOAD_DEREF', opcode=136, arg=3, argval='b', argrepr='b', offset=24, starts_line=None, is_jump_target=False),
1004 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='c', argrepr='c', offset=26, starts_line=None, is_jump_target=False),
1005 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='d', argrepr='d', offset=28, starts_line=None, is_jump_target=False),
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001006 Instruction(opname='CALL_FUNCTION', opcode=131, arg=4, argval=4, argrepr='', offset=30, starts_line=None, is_jump_target=False),
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001007 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=32, starts_line=None, is_jump_target=False),
1008 Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='inner', argrepr='inner', offset=34, starts_line=6, is_jump_target=False),
1009 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=36, starts_line=None, is_jump_target=False),
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001010]
1011
1012expected_opinfo_inner = [
1013 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=0, starts_line=4, is_jump_target=False),
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001014 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False),
1015 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False),
1016 Instruction(opname='LOAD_DEREF', opcode=136, arg=2, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False),
1017 Instruction(opname='LOAD_DEREF', opcode=136, arg=3, argval='d', argrepr='d', offset=8, starts_line=None, is_jump_target=False),
1018 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='e', argrepr='e', offset=10, starts_line=None, is_jump_target=False),
1019 Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='f', argrepr='f', offset=12, starts_line=None, is_jump_target=False),
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001020 Instruction(opname='CALL_FUNCTION', opcode=131, arg=6, argval=6, argrepr='', offset=14, starts_line=None, is_jump_target=False),
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001021 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=16, starts_line=None, is_jump_target=False),
1022 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=18, starts_line=None, is_jump_target=False),
1023 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=20, starts_line=None, is_jump_target=False),
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001024]
1025
1026expected_opinfo_jumpy = [
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001027 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='range', argrepr='range', offset=0, starts_line=3, is_jump_target=False),
1028 Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval=10, argrepr='10', offset=2, starts_line=None, is_jump_target=False),
1029 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=4, starts_line=None, is_jump_target=False),
1030 Instruction(opname='GET_ITER', opcode=68, arg=None, argval=None, argrepr='', offset=6, starts_line=None, is_jump_target=False),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001031 Instruction(opname='FOR_ITER', opcode=93, arg=17, argval=44, argrepr='to 44', offset=8, starts_line=None, is_jump_target=True),
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001032 Instruction(opname='STORE_FAST', opcode=125, arg=0, argval='i', argrepr='i', offset=10, starts_line=None, is_jump_target=False),
1033 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=12, starts_line=4, is_jump_target=False),
1034 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=14, starts_line=None, is_jump_target=False),
1035 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=16, starts_line=None, is_jump_target=False),
1036 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=18, starts_line=None, is_jump_target=False),
1037 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=20, starts_line=5, is_jump_target=False),
1038 Instruction(opname='LOAD_CONST', opcode=100, arg=2, argval=4, argrepr='4', offset=22, starts_line=None, is_jump_target=False),
1039 Instruction(opname='COMPARE_OP', opcode=107, arg=0, argval='<', argrepr='<', offset=24, starts_line=None, is_jump_target=False),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001040 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=15, argval=30, argrepr='to 30', offset=26, starts_line=None, is_jump_target=False),
1041 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=4, argval=8, argrepr='to 8', offset=28, starts_line=6, is_jump_target=False),
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001042 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=30, starts_line=7, is_jump_target=True),
1043 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=6, argrepr='6', offset=32, starts_line=None, is_jump_target=False),
1044 Instruction(opname='COMPARE_OP', opcode=107, arg=4, argval='>', argrepr='>', offset=34, starts_line=None, is_jump_target=False),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001045 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=21, argval=42, argrepr='to 42', offset=36, starts_line=None, is_jump_target=False),
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001046 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=38, starts_line=8, is_jump_target=False),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001047 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=26, argval=52, argrepr='to 52', offset=40, starts_line=None, is_jump_target=False),
1048 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=4, argval=8, argrepr='to 8', offset=42, starts_line=7, is_jump_target=True),
Mark Shannon28b75c82020-12-23 11:43:10 +00001049 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=44, starts_line=10, is_jump_target=True),
1050 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='I can haz else clause?', argrepr="'I can haz else clause?'", offset=46, starts_line=None, is_jump_target=False),
1051 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=48, starts_line=None, is_jump_target=False),
1052 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=50, starts_line=None, is_jump_target=False),
1053 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=52, starts_line=11, is_jump_target=True),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001054 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=48, argval=96, argrepr='to 96', offset=54, starts_line=None, is_jump_target=False),
Mark Shannon28b75c82020-12-23 11:43:10 +00001055 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=56, starts_line=12, is_jump_target=True),
1056 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=58, starts_line=None, is_jump_target=False),
1057 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=60, starts_line=None, is_jump_target=False),
1058 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=62, starts_line=None, is_jump_target=False),
1059 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=64, starts_line=13, is_jump_target=False),
1060 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=1, argrepr='1', offset=66, starts_line=None, is_jump_target=False),
1061 Instruction(opname='INPLACE_SUBTRACT', opcode=56, arg=None, argval=None, argrepr='', offset=68, starts_line=None, is_jump_target=False),
1062 Instruction(opname='STORE_FAST', opcode=125, arg=0, argval='i', argrepr='i', offset=70, starts_line=None, is_jump_target=False),
1063 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=72, starts_line=14, is_jump_target=False),
1064 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=6, argrepr='6', offset=74, starts_line=None, is_jump_target=False),
1065 Instruction(opname='COMPARE_OP', opcode=107, arg=4, argval='>', argrepr='>', offset=76, starts_line=None, is_jump_target=False),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001066 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=41, argval=82, argrepr='to 82', offset=78, starts_line=None, is_jump_target=False),
1067 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=26, argval=52, argrepr='to 52', offset=80, starts_line=15, is_jump_target=False),
Mark Shannon28b75c82020-12-23 11:43:10 +00001068 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=82, starts_line=16, is_jump_target=True),
1069 Instruction(opname='LOAD_CONST', opcode=100, arg=2, argval=4, argrepr='4', offset=84, starts_line=None, is_jump_target=False),
1070 Instruction(opname='COMPARE_OP', opcode=107, arg=0, argval='<', argrepr='<', offset=86, starts_line=None, is_jump_target=False),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001071 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=46, argval=92, argrepr='to 92', offset=88, starts_line=None, is_jump_target=False),
1072 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=52, argval=104, argrepr='to 104', offset=90, starts_line=17, is_jump_target=False),
Mark Shannon28b75c82020-12-23 11:43:10 +00001073 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=92, starts_line=11, is_jump_target=True),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001074 Instruction(opname='POP_JUMP_IF_TRUE', opcode=115, arg=28, argval=56, argrepr='to 56', offset=94, starts_line=None, is_jump_target=False),
Mark Shannon28b75c82020-12-23 11:43:10 +00001075 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=96, starts_line=19, is_jump_target=True),
1076 Instruction(opname='LOAD_CONST', opcode=100, arg=6, argval='Who let lolcatz into this test suite?', argrepr="'Who let lolcatz into this test suite?'", offset=98, starts_line=None, is_jump_target=False),
1077 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=100, starts_line=None, is_jump_target=False),
1078 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=102, starts_line=None, is_jump_target=False),
Mark Shannon762ef852021-08-09 10:54:48 +01001079 Instruction(opname='SETUP_FINALLY', opcode=122, arg=63, argval=232, argrepr='to 232', offset=104, starts_line=20, is_jump_target=True),
Mark Shannonfcb55c02021-04-01 16:00:31 +01001080 Instruction(opname='SETUP_FINALLY', opcode=122, arg=6, argval=120, argrepr='to 120', offset=106, starts_line=None, is_jump_target=False),
Mark Shannon28b75c82020-12-23 11:43:10 +00001081 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=1, argrepr='1', offset=108, starts_line=21, is_jump_target=False),
1082 Instruction(opname='LOAD_CONST', opcode=100, arg=7, argval=0, argrepr='0', offset=110, starts_line=None, is_jump_target=False),
1083 Instruction(opname='BINARY_TRUE_DIVIDE', opcode=27, arg=None, argval=None, argrepr='', offset=112, starts_line=None, is_jump_target=False),
1084 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=114, starts_line=None, is_jump_target=False),
1085 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=116, starts_line=None, is_jump_target=False),
Mark Shannon762ef852021-08-09 10:54:48 +01001086 Instruction(opname='JUMP_FORWARD', opcode=110, arg=13, argval=146, argrepr='to 146', offset=118, starts_line=None, is_jump_target=False),
Mark Shannon28b75c82020-12-23 11:43:10 +00001087 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=120, starts_line=22, is_jump_target=True),
1088 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=2, argval='ZeroDivisionError', argrepr='ZeroDivisionError', offset=122, starts_line=None, is_jump_target=False),
Mark Shannon762ef852021-08-09 10:54:48 +01001089 Instruction(opname='JUMP_IF_NOT_EXC_MATCH', opcode=121, arg=72, argval=144, argrepr='to 144', offset=124, starts_line=None, is_jump_target=False),
Mark Shannon8473cf82020-12-15 11:07:50 +00001090 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=126, starts_line=None, is_jump_target=False),
1091 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=128, starts_line=None, is_jump_target=False),
Mark Shannon28b75c82020-12-23 11:43:10 +00001092 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=130, starts_line=None, is_jump_target=False),
1093 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=132, starts_line=23, is_jump_target=False),
1094 Instruction(opname='LOAD_CONST', opcode=100, arg=8, argval='Here we go, here we go, here we go...', argrepr="'Here we go, here we go, here we go...'", offset=134, starts_line=None, is_jump_target=False),
1095 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=136, starts_line=None, is_jump_target=False),
1096 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=138, starts_line=None, is_jump_target=False),
1097 Instruction(opname='POP_EXCEPT', opcode=89, arg=None, argval=None, argrepr='', offset=140, starts_line=None, is_jump_target=False),
Mark Shannon762ef852021-08-09 10:54:48 +01001098 Instruction(opname='JUMP_FORWARD', opcode=110, arg=30, argval=204, argrepr='to 204', offset=142, starts_line=None, is_jump_target=False),
1099 Instruction(opname='RERAISE', opcode=119, arg=0, argval=0, argrepr='', offset=144, starts_line=22, is_jump_target=True),
1100 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=146, starts_line=25, is_jump_target=True),
1101 Instruction(opname='SETUP_WITH', opcode=143, arg=12, argval=174, argrepr='to 174', offset=148, starts_line=None, is_jump_target=False),
1102 Instruction(opname='STORE_FAST', opcode=125, arg=1, argval='dodgy', argrepr='dodgy', offset=150, starts_line=None, is_jump_target=False),
1103 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=152, starts_line=26, is_jump_target=False),
1104 Instruction(opname='LOAD_CONST', opcode=100, arg=9, argval='Never reach this', argrepr="'Never reach this'", offset=154, starts_line=None, is_jump_target=False),
1105 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=156, starts_line=None, is_jump_target=False),
1106 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=158, starts_line=None, is_jump_target=False),
1107 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=160, starts_line=None, is_jump_target=False),
1108 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=162, starts_line=25, is_jump_target=False),
Mark Shannon28b75c82020-12-23 11:43:10 +00001109 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=164, starts_line=None, is_jump_target=False),
Mark Shannon762ef852021-08-09 10:54:48 +01001110 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=166, starts_line=None, is_jump_target=False),
1111 Instruction(opname='CALL_FUNCTION', opcode=131, arg=3, argval=3, argrepr='', offset=168, starts_line=None, is_jump_target=False),
1112 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=170, starts_line=None, is_jump_target=False),
1113 Instruction(opname='JUMP_FORWARD', opcode=110, arg=22, argval=218, argrepr='to 218', offset=172, starts_line=None, is_jump_target=False),
1114 Instruction(opname='WITH_EXCEPT_START', opcode=49, arg=None, argval=None, argrepr='', offset=174, starts_line=None, is_jump_target=True),
1115 Instruction(opname='POP_JUMP_IF_TRUE', opcode=115, arg=90, argval=180, argrepr='to 180', offset=176, starts_line=None, is_jump_target=False),
1116 Instruction(opname='RERAISE', opcode=119, arg=1, argval=1, argrepr='', offset=178, starts_line=None, is_jump_target=False),
1117 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=180, starts_line=None, is_jump_target=True),
Mark Shannon28b75c82020-12-23 11:43:10 +00001118 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=182, starts_line=None, is_jump_target=False),
Mark Shannon762ef852021-08-09 10:54:48 +01001119 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=184, starts_line=None, is_jump_target=False),
1120 Instruction(opname='POP_EXCEPT', opcode=89, arg=None, argval=None, argrepr='', offset=186, starts_line=None, is_jump_target=False),
1121 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=188, starts_line=None, is_jump_target=False),
1122 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=190, starts_line=None, is_jump_target=False),
1123 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=192, starts_line=28, is_jump_target=False),
1124 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=194, starts_line=None, is_jump_target=False),
1125 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=196, starts_line=None, is_jump_target=False),
1126 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=198, starts_line=None, is_jump_target=False),
1127 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=200, starts_line=None, is_jump_target=False),
1128 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=202, starts_line=None, is_jump_target=False),
1129 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=204, starts_line=23, is_jump_target=True),
1130 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=206, starts_line=28, is_jump_target=False),
1131 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=208, starts_line=None, is_jump_target=False),
1132 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=210, starts_line=None, is_jump_target=False),
1133 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=212, starts_line=None, is_jump_target=False),
1134 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=214, starts_line=None, is_jump_target=False),
1135 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=216, starts_line=None, is_jump_target=False),
1136 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=218, starts_line=25, is_jump_target=True),
1137 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=220, starts_line=28, is_jump_target=False),
1138 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=222, starts_line=None, is_jump_target=False),
1139 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=224, starts_line=None, is_jump_target=False),
1140 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=226, starts_line=None, is_jump_target=False),
1141 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=228, starts_line=None, is_jump_target=False),
1142 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=230, starts_line=None, is_jump_target=False),
1143 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=232, starts_line=None, is_jump_target=True),
1144 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=234, starts_line=None, is_jump_target=False),
1145 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=236, starts_line=None, is_jump_target=False),
1146 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=238, starts_line=None, is_jump_target=False),
1147 Instruction(opname='RERAISE', opcode=119, arg=0, argval=0, argrepr='', offset=240, starts_line=None, is_jump_target=False),
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001148]
1149
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001150# One last piece of inspect fodder to check the default line number handling
1151def simple(): pass
1152expected_opinfo_simple = [
1153 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=0, starts_line=simple.__code__.co_firstlineno, is_jump_target=False),
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001154 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=2, starts_line=None, is_jump_target=False)
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001155]
1156
1157
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001158class InstructionTests(BytecodeTestCase):
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001159
Mark Shannonfee55262019-11-21 09:11:43 +00001160 def __init__(self, *args):
1161 super().__init__(*args)
1162 self.maxDiff = None
1163
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001164 def test_default_first_line(self):
1165 actual = dis.get_instructions(simple)
1166 self.assertEqual(list(actual), expected_opinfo_simple)
1167
1168 def test_first_line_set_to_None(self):
1169 actual = dis.get_instructions(simple, first_line=None)
1170 self.assertEqual(list(actual), expected_opinfo_simple)
1171
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001172 def test_outer(self):
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001173 actual = dis.get_instructions(outer, first_line=expected_outer_line)
1174 self.assertEqual(list(actual), expected_opinfo_outer)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001175
1176 def test_nested(self):
1177 with captured_stdout():
1178 f = outer()
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001179 actual = dis.get_instructions(f, first_line=expected_f_line)
1180 self.assertEqual(list(actual), expected_opinfo_f)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001181
1182 def test_doubly_nested(self):
1183 with captured_stdout():
1184 inner = outer()()
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001185 actual = dis.get_instructions(inner, first_line=expected_inner_line)
1186 self.assertEqual(list(actual), expected_opinfo_inner)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001187
1188 def test_jumpy(self):
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001189 actual = dis.get_instructions(jumpy, first_line=expected_jumpy_line)
1190 self.assertEqual(list(actual), expected_opinfo_jumpy)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001191
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001192# get_instructions has its own tests above, so can rely on it to validate
1193# the object oriented API
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001194class BytecodeTests(unittest.TestCase):
Mark Shannonfee55262019-11-21 09:11:43 +00001195
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001196 def test_instantiation(self):
1197 # Test with function, method, code string and code object
1198 for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001199 with self.subTest(obj=obj):
1200 b = dis.Bytecode(obj)
1201 self.assertIsInstance(b.codeobj, types.CodeType)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001202
1203 self.assertRaises(TypeError, dis.Bytecode, object())
1204
1205 def test_iteration(self):
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001206 for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
1207 with self.subTest(obj=obj):
1208 via_object = list(dis.Bytecode(obj))
1209 via_generator = list(dis.get_instructions(obj))
1210 self.assertEqual(via_object, via_generator)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001211
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001212 def test_explicit_first_line(self):
1213 actual = dis.Bytecode(outer, first_line=expected_outer_line)
1214 self.assertEqual(list(actual), expected_opinfo_outer)
1215
1216 def test_source_line_in_disassembly(self):
1217 # Use the line in the source code
syncosmicfe2b56a2017-08-17 19:29:21 -07001218 actual = dis.Bytecode(simple).dis()
1219 actual = actual.strip().partition(" ")[0] # extract the line no
1220 expected = str(simple.__code__.co_firstlineno)
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001221 self.assertEqual(actual, expected)
1222 # Use an explicit first line number
syncosmicfe2b56a2017-08-17 19:29:21 -07001223 actual = dis.Bytecode(simple, first_line=350).dis()
1224 actual = actual.strip().partition(" ")[0] # extract the line no
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001225 self.assertEqual(actual, "350")
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001226
1227 def test_info(self):
1228 self.maxDiff = 1000
1229 for x, expected in CodeInfoTests.test_pairs:
1230 b = dis.Bytecode(x)
1231 self.assertRegex(b.info(), expected)
1232
Nick Coghlan90b8e7d2013-11-06 22:08:36 +10001233 def test_disassembled(self):
1234 actual = dis.Bytecode(_f).dis()
1235 self.assertEqual(actual, dis_f)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001236
Nick Coghlan50c48b82013-11-23 00:57:00 +10001237 def test_from_traceback(self):
1238 tb = get_tb()
1239 b = dis.Bytecode.from_traceback(tb)
1240 while tb.tb_next: tb = tb.tb_next
1241
1242 self.assertEqual(b.current_offset, tb.tb_lasti)
1243
1244 def test_from_traceback_dis(self):
1245 tb = get_tb()
1246 b = dis.Bytecode.from_traceback(tb)
1247 self.assertEqual(b.dis(), dis_traceback)
Nick Coghlanb39fd0c2013-05-06 23:59:20 +10001248
Max Bernstein6e799be2020-12-17 16:30:29 -08001249
1250class TestBytecodeTestCase(BytecodeTestCase):
1251 def test_assert_not_in_with_op_not_in_bytecode(self):
1252 code = compile("a = 1", "<string>", "exec")
1253 self.assertInBytecode(code, "LOAD_CONST", 1)
1254 self.assertNotInBytecode(code, "LOAD_NAME")
1255 self.assertNotInBytecode(code, "LOAD_NAME", "a")
1256
1257 def test_assert_not_in_with_arg_not_in_bytecode(self):
1258 code = compile("a = 1", "<string>", "exec")
1259 self.assertInBytecode(code, "LOAD_CONST")
1260 self.assertInBytecode(code, "LOAD_CONST", 1)
1261 self.assertNotInBytecode(code, "LOAD_CONST", 2)
1262
1263 def test_assert_not_in_with_arg_in_bytecode(self):
1264 code = compile("a = 1", "<string>", "exec")
1265 with self.assertRaises(AssertionError):
1266 self.assertNotInBytecode(code, "LOAD_CONST", 1)
1267
Ɓukasz Langafd6b70d2021-11-03 16:53:36 +01001268
1269class TestDisTraceback(unittest.TestCase):
1270 def setUp(self) -> None:
1271 try: # We need to clean up existing tracebacks
1272 del sys.last_traceback
1273 except AttributeError:
1274 pass
1275 return super().setUp()
1276
1277 def get_disassembly(self, tb):
1278 output = io.StringIO()
1279 with contextlib.redirect_stdout(output):
1280 dis.distb(tb)
1281 return output.getvalue()
1282
1283 def test_distb_empty(self):
1284 with self.assertRaises(RuntimeError):
1285 dis.distb()
1286
1287 def test_distb_last_traceback(self):
1288 # We need to have an existing last traceback in `sys`:
1289 tb = get_tb()
1290 sys.last_traceback = tb
1291
1292 self.assertEqual(self.get_disassembly(None), dis_traceback)
1293
1294 def test_distb_explicit_arg(self):
1295 tb = get_tb()
1296
1297 self.assertEqual(self.get_disassembly(tb), dis_traceback)
1298
1299
1300class TestDisTracebackWithFile(TestDisTraceback):
1301 # Run the `distb` tests again, using the file arg instead of print
1302 def get_disassembly(self, tb):
1303 output = io.StringIO()
1304 with contextlib.redirect_stdout(output):
1305 dis.distb(tb, file=output)
1306 return output.getvalue()
1307
1308
Skip Montanaroadd0ccc2003-02-27 21:27:07 +00001309if __name__ == "__main__":
Zachary Waree80e8062013-12-26 09:53:49 -06001310 unittest.main()