Debian Codegraph @

Lib/test/test_dis.py

raw
1 # Minimal tests for dis module
2
3 import ast
4 import contextlib
5 import dis
6 import functools
7 import io
8 import itertools
9 import opcode
10 import re
11 import sys
12 import tempfile
13 import textwrap
14 import types
15 import unittest
16 from test.support import (captured_stdout, requires_debug_ranges,
17 requires_specialization, cpython_only,
18 os_helper, import_helper, reset_code)
19 from test.support.bytecode_helper import BytecodeTestCase
20
21
22 CACHE = dis.opmap["CACHE"]
23
24 def get_tb():
25 def _error():
26 try:
27 1 / 0
28 except Exception as e:
29 tb = e.__traceback__
30 return tb
31
32 tb = _error()
33 while tb.tb_next:
34 tb = tb.tb_next
35 return tb
36
37 TRACEBACK_CODE = get_tb().tb_frame.f_code
38
39 class _C:
40 def __init__(self, x):
41 self.x = x == 1
42
43 @staticmethod
44 def sm(x):
45 x = x == 1
46
47 @classmethod
48 def cm(cls, x):
49 cls.x = x == 1
50
51 dis_c_instance_method = """\
52 %3d RESUME 0
53
54 %3d LOAD_FAST_BORROW 1 (x)
55 LOAD_SMALL_INT 1
56 COMPARE_OP 72 (==)
57 LOAD_FAST_BORROW 0 (self)
58 STORE_ATTR 0 (x)
59 LOAD_CONST 1 (None)
60 RETURN_VALUE
61 """ % (_C.__init__.__code__.co_firstlineno, _C.__init__.__code__.co_firstlineno + 1,)
62
63 dis_c_instance_method_bytes = """\
64 RESUME 0
65 LOAD_FAST_BORROW 1
66 LOAD_SMALL_INT 1
67 COMPARE_OP 72 (==)
68 LOAD_FAST_BORROW 0
69 STORE_ATTR 0
70 LOAD_CONST 1
71 RETURN_VALUE
72 """
73
74 dis_c_class_method = """\
75 %3d RESUME 0
76
77 %3d LOAD_FAST_BORROW 1 (x)
78 LOAD_SMALL_INT 1
79 COMPARE_OP 72 (==)
80 LOAD_FAST_BORROW 0 (cls)
81 STORE_ATTR 0 (x)
82 LOAD_CONST 1 (None)
83 RETURN_VALUE
84 """ % (_C.cm.__code__.co_firstlineno, _C.cm.__code__.co_firstlineno + 2,)
85
86 dis_c_static_method = """\
87 %3d RESUME 0
88
89 %3d LOAD_FAST_BORROW 0 (x)
90 LOAD_SMALL_INT 1
91 COMPARE_OP 72 (==)
92 STORE_FAST 0 (x)
93 LOAD_CONST 1 (None)
94 RETURN_VALUE
95 """ % (_C.sm.__code__.co_firstlineno, _C.sm.__code__.co_firstlineno + 2,)
96
97 # Class disassembling info has an extra newline at end.
98 dis_c = """\
99 Disassembly of %s:
100 %s
101 Disassembly of %s:
102 %s
103 Disassembly of %s:
104 %s
105 """ % (_C.__init__.__name__, dis_c_instance_method,
106 _C.cm.__name__, dis_c_class_method,
107 _C.sm.__name__, dis_c_static_method)
108
109 def _f(a):
110 print(a)
111 return 1
112
113 dis_f = """\
114 %3d RESUME 0
115
116 %3d LOAD_GLOBAL 1 (print + NULL)
117 LOAD_FAST_BORROW 0 (a)
118 CALL 1
119 POP_TOP
120
121 %3d LOAD_SMALL_INT 1
122 RETURN_VALUE
123 """ % (_f.__code__.co_firstlineno,
124 _f.__code__.co_firstlineno + 1,
125 _f.__code__.co_firstlineno + 2)
126
127 dis_f_with_offsets = """\
128 %3d 0 RESUME 0
129
130 %3d 2 LOAD_GLOBAL 1 (print + NULL)
131 12 LOAD_FAST_BORROW 0 (a)
132 14 CALL 1
133 22 POP_TOP
134
135 %3d 24 LOAD_SMALL_INT 1
136 26 RETURN_VALUE
137 """ % (_f.__code__.co_firstlineno,
138 _f.__code__.co_firstlineno + 1,
139 _f.__code__.co_firstlineno + 2)
140
141 dis_f_with_positions_format = f"""\
142 %-14s RESUME 0
143
144 %-14s LOAD_GLOBAL 1 (print + NULL)
145 %-14s LOAD_FAST_BORROW 0 (a)
146 %-14s CALL 1
147 %-14s POP_TOP
148
149 %-14s LOAD_SMALL_INT 1
150 %-14s RETURN_VALUE
151 """
152
153 dis_f_co_code = """\
154 RESUME 0
155 LOAD_GLOBAL 1
156 LOAD_FAST_BORROW 0
157 CALL 1
158 POP_TOP
159 LOAD_SMALL_INT 1
160 RETURN_VALUE
161 """
162
163 def bug708901():
164 for res in range(1,
165 10):
166 pass
167
168 dis_bug708901 = """\
169 %3d RESUME 0
170
171 %3d LOAD_GLOBAL 1 (range + NULL)
172 LOAD_SMALL_INT 1
173
174 %3d LOAD_SMALL_INT 10
175
176 %3d CALL 2
177 GET_ITER
178 L1: FOR_ITER 3 (to L2)
179 STORE_FAST 0 (res)
180
181 %3d JUMP_BACKWARD 5 (to L1)
182
183 %3d L2: END_FOR
184 POP_ITER
185 LOAD_CONST 1 (None)
186 RETURN_VALUE
187 """ % (bug708901.__code__.co_firstlineno,
188 bug708901.__code__.co_firstlineno + 1,
189 bug708901.__code__.co_firstlineno + 2,
190 bug708901.__code__.co_firstlineno + 1,
191 bug708901.__code__.co_firstlineno + 3,
192 bug708901.__code__.co_firstlineno + 1)
193
194
195 def bug1333982(x=[]):
196 assert 0, ((s for s in x) +
197 1)
198 pass
199
200 dis_bug1333982 = """\
201 %3d RESUME 0
202
203 %3d LOAD_COMMON_CONSTANT 0 (AssertionError)
204 LOAD_CONST 1 (<code object <genexpr> at 0x..., file "%s", line %d>)
205 MAKE_FUNCTION
206 LOAD_FAST_BORROW 0 (x)
207 GET_ITER
208 CALL 0
209
210 %3d LOAD_SMALL_INT 1
211
212 %3d BINARY_OP 0 (+)
213 CALL 0
214 RAISE_VARARGS 1
215 """ % (bug1333982.__code__.co_firstlineno,
216 bug1333982.__code__.co_firstlineno + 1,
217 __file__,
218 bug1333982.__code__.co_firstlineno + 1,
219 bug1333982.__code__.co_firstlineno + 2,
220 bug1333982.__code__.co_firstlineno + 1)
221
222
223 def bug42562():
224 pass
225
226
227 # Set line number for 'pass' to None
228 bug42562.__code__ = bug42562.__code__.replace(co_linetable=b'\xf8')
229
230
231 dis_bug42562 = """\
232 RESUME 0
233 LOAD_CONST 0 (None)
234 RETURN_VALUE
235 """
236
237 # Extended arg followed by NOP
238 code_bug_45757 = bytes([
239 opcode.opmap['EXTENDED_ARG'], 0x01,
240 opcode.opmap['NOP'], 0xFF,
241 opcode.opmap['EXTENDED_ARG'], 0x01,
242 opcode.opmap['LOAD_CONST'], 0x29,
243 opcode.opmap['RETURN_VALUE'], 0x00,
244 ])
245
246 dis_bug_45757 = """\
247 EXTENDED_ARG 1
248 NOP
249 EXTENDED_ARG 1
250 LOAD_CONST 297
251 RETURN_VALUE
252 """
253
254 # [255, 255, 255, 252] is -4 in a 4 byte signed integer
255 bug46724 = bytes([
256 opcode.EXTENDED_ARG, 255,
257 opcode.EXTENDED_ARG, 255,
258 opcode.EXTENDED_ARG, 255,
259 opcode.opmap['JUMP_FORWARD'], 252,
260 ])
261
262
263 dis_bug46724 = """\
264 L1: EXTENDED_ARG 255
265 EXTENDED_ARG 65535
266 EXTENDED_ARG 16777215
267 JUMP_FORWARD -4 (to L1)
268 """
269
270 def func_w_kwargs(a, b, **c):
271 pass
272
273 def wrap_func_w_kwargs():
274 func_w_kwargs(1, 2, c=5)
275
276 dis_kw_names = """\
277 %3d RESUME 0
278
279 %3d LOAD_GLOBAL 1 (func_w_kwargs + NULL)
280 LOAD_SMALL_INT 1
281 LOAD_SMALL_INT 2
282 LOAD_SMALL_INT 5
283 LOAD_CONST 1 (('c',))
284 CALL_KW 3
285 POP_TOP
286 LOAD_CONST 2 (None)
287 RETURN_VALUE
288 """ % (wrap_func_w_kwargs.__code__.co_firstlineno,
289 wrap_func_w_kwargs.__code__.co_firstlineno + 1)
290
291 dis_intrinsic_1_2 = """\
292 0 RESUME 0
293
294 1 LOAD_SMALL_INT 0
295 LOAD_CONST 1 (('*',))
296 IMPORT_NAME 0 (math)
297 CALL_INTRINSIC_1 2 (INTRINSIC_IMPORT_STAR)
298 POP_TOP
299 LOAD_CONST 2 (None)
300 RETURN_VALUE
301 """
302
303 dis_intrinsic_1_5 = """\
304 0 RESUME 0
305
306 1 LOAD_NAME 0 (a)
307 CALL_INTRINSIC_1 5 (INTRINSIC_UNARY_POSITIVE)
308 RETURN_VALUE
309 """
310
311 dis_intrinsic_1_6 = """\
312 0 RESUME 0
313
314 1 BUILD_LIST 0
315 LOAD_NAME 0 (a)
316 LIST_EXTEND 1
317 CALL_INTRINSIC_1 6 (INTRINSIC_LIST_TO_TUPLE)
318 RETURN_VALUE
319 """
320
321 _BIG_LINENO_FORMAT = """\
322 1 RESUME 0
323
324 %3d LOAD_GLOBAL 0 (spam)
325 POP_TOP
326 LOAD_CONST 0 (None)
327 RETURN_VALUE
328 """
329
330 _BIG_LINENO_FORMAT2 = """\
331 1 RESUME 0
332
333 %4d LOAD_GLOBAL 0 (spam)
334 POP_TOP
335 LOAD_CONST 0 (None)
336 RETURN_VALUE
337 """
338
339 dis_module_expected_results = """\
340 Disassembly of f:
341 4 RESUME 0
342 LOAD_CONST 0 (None)
343 RETURN_VALUE
344
345 Disassembly of g:
346 5 RESUME 0
347 LOAD_CONST 0 (None)
348 RETURN_VALUE
349
350 """
351
352 expr_str = "x + 1"
353
354 dis_expr_str = """\
355 0 RESUME 0
356
357 1 LOAD_NAME 0 (x)
358 LOAD_SMALL_INT 1
359 BINARY_OP 0 (+)
360 RETURN_VALUE
361 """
362
363 simple_stmt_str = "x = x + 1"
364
365 dis_simple_stmt_str = """\
366 0 RESUME 0
367
368 1 LOAD_NAME 0 (x)
369 LOAD_SMALL_INT 1
370 BINARY_OP 0 (+)
371 STORE_NAME 0 (x)
372 LOAD_CONST 1 (None)
373 RETURN_VALUE
374 """
375
376 annot_stmt_str = """\
377
378 x: int = 1
379 y: fun(1)
380 lst[fun(0)]: int = 1
381 """
382 # leading newline is for a reason (tests lineno)
383
384 dis_annot_stmt_str = """\
385 -- MAKE_CELL 0 (__conditional_annotations__)
386
387 0 RESUME 0
388
389 2 LOAD_CONST 1 (<code object __annotate__ at 0x..., file "<dis>", line 2>)
390 MAKE_FUNCTION
391 STORE_NAME 4 (__annotate__)
392 BUILD_SET 0
393 STORE_NAME 0 (__conditional_annotations__)
394 LOAD_SMALL_INT 1
395 STORE_NAME 1 (x)
396 LOAD_NAME 0 (__conditional_annotations__)
397 LOAD_SMALL_INT 0
398 SET_ADD 1
399 POP_TOP
400
401 3 LOAD_NAME 0 (__conditional_annotations__)
402 LOAD_SMALL_INT 1
403 SET_ADD 1
404 POP_TOP
405
406 4 LOAD_SMALL_INT 1
407 LOAD_NAME 2 (lst)
408 LOAD_NAME 3 (fun)
409 PUSH_NULL
410 LOAD_SMALL_INT 0
411 CALL 1
412 STORE_SUBSCR
413 LOAD_CONST 2 (None)
414 RETURN_VALUE
415 """
416
417 fn_with_annotate_str = """
418 def foo(a: int, b: str) -> str:
419 return a * b
420 """
421
422 dis_fn_with_annotate_str = """\
423 0 RESUME 0
424
425 2 LOAD_CONST 0 (<code object __annotate__ at 0x..., file "<dis>", line 2>)
426 MAKE_FUNCTION
427 LOAD_CONST 1 (<code object foo at 0x..., file "<dis>", line 2>)
428 MAKE_FUNCTION
429 SET_FUNCTION_ATTRIBUTE 16 (annotate)
430 STORE_NAME 0 (foo)
431 LOAD_CONST 2 (None)
432 RETURN_VALUE
433 """
434
435 compound_stmt_str = """\
436 x = 0
437 while 1:
438 x += 1"""
439 # Trailing newline has been deliberately omitted
440
441 dis_compound_stmt_str = """\
442 0 RESUME 0
443
444 1 LOAD_SMALL_INT 0
445 STORE_NAME 0 (x)
446
447 2 L1: NOP
448
449 3 LOAD_NAME 0 (x)
450 LOAD_SMALL_INT 1
451 BINARY_OP 13 (+=)
452 STORE_NAME 0 (x)
453 JUMP_BACKWARD 12 (to L1)
454 """
455
456 dis_traceback = """\
457 %4d RESUME 0
458
459 %4d NOP
460
461 %4d L1: LOAD_SMALL_INT 1
462 LOAD_SMALL_INT 0
463 --> BINARY_OP 11 (/)
464 POP_TOP
465
466 %4d L2: LOAD_FAST_CHECK 1 (tb)
467 RETURN_VALUE
468
469 -- L3: PUSH_EXC_INFO
470
471 %4d LOAD_GLOBAL 0 (Exception)
472 CHECK_EXC_MATCH
473 POP_JUMP_IF_FALSE 24 (to L7)
474 NOT_TAKEN
475 STORE_FAST 0 (e)
476
477 %4d L4: LOAD_FAST 0 (e)
478 LOAD_ATTR 2 (__traceback__)
479 STORE_FAST 1 (tb)
480 L5: POP_EXCEPT
481 LOAD_CONST 1 (None)
482 STORE_FAST 0 (e)
483 DELETE_FAST 0 (e)
484
485 %4d LOAD_FAST 1 (tb)
486 RETURN_VALUE
487
488 -- L6: LOAD_CONST 1 (None)
489 STORE_FAST 0 (e)
490 DELETE_FAST 0 (e)
491 RERAISE 1
492
493 %4d L7: RERAISE 0
494
495 -- L8: COPY 3
496 POP_EXCEPT
497 RERAISE 1
498 ExceptionTable:
499 L1 to L2 -> L3 [0]
500 L3 to L4 -> L8 [1] lasti
501 L4 to L5 -> L6 [1] lasti
502 L6 to L8 -> L8 [1] lasti
503 """ % (TRACEBACK_CODE.co_firstlineno,
504 TRACEBACK_CODE.co_firstlineno + 1,
505 TRACEBACK_CODE.co_firstlineno + 2,
506 TRACEBACK_CODE.co_firstlineno + 5,
507 TRACEBACK_CODE.co_firstlineno + 3,
508 TRACEBACK_CODE.co_firstlineno + 4,
509 TRACEBACK_CODE.co_firstlineno + 5,
510 TRACEBACK_CODE.co_firstlineno + 3)
511
512 def _fstring(a, b, c, d):
513 return f'{a} {b:4} {c!r} {d!r:4}'
514
515 dis_fstring = """\
516 %3d RESUME 0
517
518 %3d LOAD_FAST_BORROW 0 (a)
519 FORMAT_SIMPLE
520 LOAD_CONST 0 (' ')
521 LOAD_FAST_BORROW 1 (b)
522 LOAD_CONST 1 ('4')
523 FORMAT_WITH_SPEC
524 LOAD_CONST 0 (' ')
525 LOAD_FAST_BORROW 2 (c)
526 CONVERT_VALUE 2 (repr)
527 FORMAT_SIMPLE
528 LOAD_CONST 0 (' ')
529 LOAD_FAST_BORROW 3 (d)
530 CONVERT_VALUE 2 (repr)
531 LOAD_CONST 1 ('4')
532 FORMAT_WITH_SPEC
533 BUILD_STRING 7
534 RETURN_VALUE
535 """ % (_fstring.__code__.co_firstlineno, _fstring.__code__.co_firstlineno + 1)
536
537 def _with(c):
538 with c:
539 x = 1
540 y = 2
541
542 dis_with = """\
543 %4d RESUME 0
544
545 %4d LOAD_FAST_BORROW 0 (c)
546 COPY 1
547 LOAD_SPECIAL 1 (__exit__)
548 SWAP 2
549 SWAP 3
550 LOAD_SPECIAL 0 (__enter__)
551 CALL 0
552 L1: POP_TOP
553
554 %4d LOAD_SMALL_INT 1
555 STORE_FAST 1 (x)
556
557 %4d L2: LOAD_CONST 1 (None)
558 LOAD_CONST 1 (None)
559 LOAD_CONST 1 (None)
560 CALL 3
561 POP_TOP
562
563 %4d LOAD_SMALL_INT 2
564 STORE_FAST 2 (y)
565 LOAD_CONST 1 (None)
566 RETURN_VALUE
567
568 %4d L3: PUSH_EXC_INFO
569 WITH_EXCEPT_START
570 TO_BOOL
571 POP_JUMP_IF_TRUE 2 (to L4)
572 NOT_TAKEN
573 RERAISE 2
574 L4: POP_TOP
575 L5: POP_EXCEPT
576 POP_TOP
577 POP_TOP
578 POP_TOP
579
580 %4d LOAD_SMALL_INT 2
581 STORE_FAST 2 (y)
582 LOAD_CONST 1 (None)
583 RETURN_VALUE
584
585 -- L6: COPY 3
586 POP_EXCEPT
587 RERAISE 1
588 ExceptionTable:
589 L1 to L2 -> L3 [2] lasti
590 L3 to L5 -> L6 [4] lasti
591 """ % (_with.__code__.co_firstlineno,
592 _with.__code__.co_firstlineno + 1,
593 _with.__code__.co_firstlineno + 2,
594 _with.__code__.co_firstlineno + 1,
595 _with.__code__.co_firstlineno + 3,
596 _with.__code__.co_firstlineno + 1,
597 _with.__code__.co_firstlineno + 3,
598 )
599
600 async def _asyncwith(c):
601 async with c:
602 x = 1
603 y = 2
604
605 dis_asyncwith = """\
606 %4d RETURN_GENERATOR
607 POP_TOP
608 L1: RESUME 0
609
610 %4d LOAD_FAST 0 (c)
611 COPY 1
612 LOAD_SPECIAL 3 (__aexit__)
613 SWAP 2
614 SWAP 3
615 LOAD_SPECIAL 2 (__aenter__)
616 CALL 0
617 GET_AWAITABLE 1
618 LOAD_CONST 0 (None)
619 L2: SEND 3 (to L5)
620 L3: YIELD_VALUE 1
621 L4: RESUME 3
622 JUMP_BACKWARD_NO_INTERRUPT 5 (to L2)
623 L5: END_SEND
624 L6: POP_TOP
625
626 %4d LOAD_SMALL_INT 1
627 STORE_FAST 1 (x)
628
629 %4d L7: LOAD_CONST 0 (None)
630 LOAD_CONST 0 (None)
631 LOAD_CONST 0 (None)
632 CALL 3
633 GET_AWAITABLE 2
634 LOAD_CONST 0 (None)
635 L8: SEND 3 (to L11)
636 L9: YIELD_VALUE 1
637 L10: RESUME 3
638 JUMP_BACKWARD_NO_INTERRUPT 5 (to L8)
639 L11: END_SEND
640 POP_TOP
641
642 %4d LOAD_SMALL_INT 2
643 STORE_FAST 2 (y)
644 LOAD_CONST 0 (None)
645 RETURN_VALUE
646
647 %4d L12: CLEANUP_THROW
648 L13: JUMP_BACKWARD_NO_INTERRUPT 26 (to L5)
649 L14: CLEANUP_THROW
650 L15: JUMP_BACKWARD_NO_INTERRUPT 10 (to L11)
651 L16: PUSH_EXC_INFO
652 WITH_EXCEPT_START
653 GET_AWAITABLE 2
654 LOAD_CONST 0 (None)
655 L17: SEND 4 (to L21)
656 L18: YIELD_VALUE 1
657 L19: RESUME 3
658 JUMP_BACKWARD_NO_INTERRUPT 5 (to L17)
659 L20: CLEANUP_THROW
660 L21: END_SEND
661 TO_BOOL
662 POP_JUMP_IF_TRUE 2 (to L24)
663 L22: NOT_TAKEN
664 L23: RERAISE 2
665 L24: POP_TOP
666 L25: POP_EXCEPT
667 POP_TOP
668 POP_TOP
669 POP_TOP
670
671 %4d LOAD_SMALL_INT 2
672 STORE_FAST 2 (y)
673 LOAD_CONST 0 (None)
674 RETURN_VALUE
675
676 -- L26: COPY 3
677 POP_EXCEPT
678 RERAISE 1
679 L27: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR)
680 RERAISE 1
681 ExceptionTable:
682 L1 to L3 -> L27 [0] lasti
683 L3 to L4 -> L12 [4]
684 L4 to L6 -> L27 [0] lasti
685 L6 to L7 -> L16 [2] lasti
686 L7 to L9 -> L27 [0] lasti
687 L9 to L10 -> L14 [2]
688 L10 to L13 -> L27 [0] lasti
689 L14 to L15 -> L27 [0] lasti
690 L16 to L18 -> L26 [4] lasti
691 L18 to L19 -> L20 [7]
692 L19 to L22 -> L26 [4] lasti
693 L23 to L25 -> L26 [4] lasti
694 L25 to L27 -> L27 [0] lasti
695 """ % (_asyncwith.__code__.co_firstlineno,
696 _asyncwith.__code__.co_firstlineno + 1,
697 _asyncwith.__code__.co_firstlineno + 2,
698 _asyncwith.__code__.co_firstlineno + 1,
699 _asyncwith.__code__.co_firstlineno + 3,
700 _asyncwith.__code__.co_firstlineno + 1,
701 _asyncwith.__code__.co_firstlineno + 3,
702 )
703
704
705 def _tryfinally(a, b):
706 try:
707 return a
708 finally:
709 b()
710
711 def _tryfinallyconst(b):
712 try:
713 return 1
714 finally:
715 b()
716
717 dis_tryfinally = """\
718 %4d RESUME 0
719
720 %4d NOP
721
722 %4d L1: LOAD_FAST_BORROW 0 (a)
723
724 %4d L2: LOAD_FAST_BORROW 1 (b)
725 PUSH_NULL
726 CALL 0
727 POP_TOP
728 RETURN_VALUE
729
730 -- L3: PUSH_EXC_INFO
731
732 %4d LOAD_FAST 1 (b)
733 PUSH_NULL
734 CALL 0
735 POP_TOP
736 RERAISE 0
737
738 -- L4: COPY 3
739 POP_EXCEPT
740 RERAISE 1
741 ExceptionTable:
742 L1 to L2 -> L3 [0]
743 L3 to L4 -> L4 [1] lasti
744 """ % (_tryfinally.__code__.co_firstlineno,
745 _tryfinally.__code__.co_firstlineno + 1,
746 _tryfinally.__code__.co_firstlineno + 2,
747 _tryfinally.__code__.co_firstlineno + 4,
748 _tryfinally.__code__.co_firstlineno + 4,
749 )
750
751 dis_tryfinallyconst = """\
752 %4d RESUME 0
753
754 %4d NOP
755
756 %4d NOP
757
758 %4d LOAD_FAST_BORROW 0 (b)
759 PUSH_NULL
760 CALL 0
761 POP_TOP
762 LOAD_SMALL_INT 1
763 RETURN_VALUE
764
765 -- L1: PUSH_EXC_INFO
766
767 %4d LOAD_FAST 0 (b)
768 PUSH_NULL
769 CALL 0
770 POP_TOP
771 RERAISE 0
772
773 -- L2: COPY 3
774 POP_EXCEPT
775 RERAISE 1
776 ExceptionTable:
777 L1 to L2 -> L2 [1] lasti
778 """ % (_tryfinallyconst.__code__.co_firstlineno,
779 _tryfinallyconst.__code__.co_firstlineno + 1,
780 _tryfinallyconst.__code__.co_firstlineno + 2,
781 _tryfinallyconst.__code__.co_firstlineno + 4,
782 _tryfinallyconst.__code__.co_firstlineno + 4,
783 )
784
785 def _g(x):
786 yield x
787
788 async def _ag(x):
789 yield x
790
791 async def _co(x):
792 async for item in _ag(x):
793 pass
794
795 def _h(y):
796 def foo(x):
797 '''funcdoc'''
798 return list(x + z for z in y)
799 return foo
800
801 dis_nested_0 = """\
802 -- MAKE_CELL 0 (y)
803
804 %4d RESUME 0
805
806 %4d LOAD_FAST_BORROW 0 (y)
807 BUILD_TUPLE 1
808 LOAD_CONST 0 (<code object foo at 0x..., file "%s", line %d>)
809 MAKE_FUNCTION
810 SET_FUNCTION_ATTRIBUTE 8 (closure)
811 STORE_FAST 1 (foo)
812
813 %4d LOAD_FAST_BORROW 1 (foo)
814 RETURN_VALUE
815 """ % (_h.__code__.co_firstlineno,
816 _h.__code__.co_firstlineno + 1,
817 __file__,
818 _h.__code__.co_firstlineno + 1,
819 _h.__code__.co_firstlineno + 4,
820 )
821
822 dis_nested_1 = """%s
823 Disassembly of <code object foo at 0x..., file "%s", line %d>:
824 -- COPY_FREE_VARS 1
825 MAKE_CELL 0 (x)
826
827 %4d RESUME 0
828
829 %4d LOAD_GLOBAL 1 (list + NULL)
830 LOAD_FAST_BORROW 0 (x)
831 BUILD_TUPLE 1
832 LOAD_CONST 1 (<code object <genexpr> at 0x..., file "%s", line %d>)
833 MAKE_FUNCTION
834 SET_FUNCTION_ATTRIBUTE 8 (closure)
835 LOAD_DEREF 1 (y)
836 GET_ITER
837 CALL 0
838 CALL 1
839 RETURN_VALUE
840 """ % (dis_nested_0,
841 __file__,
842 _h.__code__.co_firstlineno + 1,
843 _h.__code__.co_firstlineno + 1,
844 _h.__code__.co_firstlineno + 3,
845 __file__,
846 _h.__code__.co_firstlineno + 3,
847 )
848
849 dis_nested_2 = """%s
850 Disassembly of <code object <genexpr> at 0x..., file "%s", line %d>:
851 -- COPY_FREE_VARS 1
852
853 %4d RETURN_GENERATOR
854 POP_TOP
855 L1: RESUME 0
856 LOAD_FAST 0 (.0)
857 L2: FOR_ITER 14 (to L3)
858 STORE_FAST 1 (z)
859 LOAD_DEREF 2 (x)
860 LOAD_FAST_BORROW 1 (z)
861 BINARY_OP 0 (+)
862 YIELD_VALUE 0
863 RESUME 5
864 POP_TOP
865 JUMP_BACKWARD 16 (to L2)
866 L3: END_FOR
867 POP_ITER
868 LOAD_CONST 0 (None)
869 RETURN_VALUE
870
871 -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR)
872 RERAISE 1
873 ExceptionTable:
874 L1 to L4 -> L4 [0] lasti
875 """ % (dis_nested_1,
876 __file__,
877 _h.__code__.co_firstlineno + 3,
878 _h.__code__.co_firstlineno + 3,
879 )
880
881 def load_test(x, y=0):
882 a, b = x, y
883 return a, b
884
885 dis_load_test_quickened_code = """\
886 %3d RESUME_CHECK 0
887
888 %3d LOAD_FAST_LOAD_FAST 1 (x, y)
889 STORE_FAST_STORE_FAST 50 (b, a)
890
891 %3d LOAD_FAST_BORROW_LOAD_FAST_BORROW 35 (a, b)
892 BUILD_TUPLE 2
893 RETURN_VALUE
894 """ % (load_test.__code__.co_firstlineno,
895 load_test.__code__.co_firstlineno + 1,
896 load_test.__code__.co_firstlineno + 2)
897
898 def loop_test():
899 for i in [1, 2, 3] * 3:
900 load_test(i)
901
902 dis_loop_test_quickened_code = """\
903 %3d RESUME_CHECK 0
904
905 %3d BUILD_LIST 0
906 LOAD_CONST_MORTAL 2 ((1, 2, 3))
907 LIST_EXTEND 1
908 LOAD_SMALL_INT 3
909 BINARY_OP 5 (*)
910 GET_ITER
911 L1: FOR_ITER_LIST 14 (to L2)
912 STORE_FAST 0 (i)
913
914 %3d LOAD_GLOBAL_MODULE 1 (load_test + NULL)
915 LOAD_FAST_BORROW 0 (i)
916 CALL_PY_GENERAL 1
917 POP_TOP
918 JUMP_BACKWARD_{: <6} 16 (to L1)
919
920 %3d L2: END_FOR
921 POP_ITER
922 LOAD_CONST_IMMORTAL 1 (None)
923 RETURN_VALUE
924 """ % (loop_test.__code__.co_firstlineno,
925 loop_test.__code__.co_firstlineno + 1,
926 loop_test.__code__.co_firstlineno + 2,
927 loop_test.__code__.co_firstlineno + 1,)
928
929 def extended_arg_quick():
930 *_, _ = ...
931
932 dis_extended_arg_quick_code = """\
933 %3d RESUME 0
934
935 %3d LOAD_CONST 0 (Ellipsis)
936 EXTENDED_ARG 1
937 UNPACK_EX 256
938 POP_TOP
939 STORE_FAST 0 (_)
940 LOAD_CONST 1 (None)
941 RETURN_VALUE
942 """% (extended_arg_quick.__code__.co_firstlineno,
943 extended_arg_quick.__code__.co_firstlineno + 1,)
944
945 class DisTestBase(unittest.TestCase):
946 "Common utilities for DisTests and TestDisTraceback"
947
948 def strip_addresses(self, text):
949 return re.sub(r'\b0x[0-9A-Fa-f]+\b', '0x...', text)
950
951 def assert_exception_table_increasing(self, lines):
952 prev_start, prev_end = -1, -1
953 count = 0
954 for line in lines:
955 m = re.match(r' L(\d+) to L(\d+) -> L\d+ \[\d+\]', line)
956 start, end = [int(g) for g in m.groups()]
957 self.assertGreaterEqual(end, start)
958 self.assertGreaterEqual(start, prev_end)
959 prev_start, prev_end = start, end
960 count += 1
961 return count
962
963 def do_disassembly_compare(self, got, expected):
964 if got != expected:
965 got = self.strip_addresses(got)
966 self.assertEqual(got, expected)
967
968
969 class DisTests(DisTestBase):
970
971 maxDiff = None
972
973 def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs):
974 # We want to test the default printing behaviour, not the file arg
975 output = io.StringIO()
976 with contextlib.redirect_stdout(output):
977 if wrapper:
978 dis.dis(func, **kwargs)
979 else:
980 dis.disassemble(func, lasti, **kwargs)
981 return output.getvalue()
982
983 def get_disassemble_as_string(self, func, lasti=-1):
984 return self.get_disassembly(func, lasti, False)
985
986 def do_disassembly_test(self, func, expected, **kwargs):
987 self.maxDiff = None
988 got = self.get_disassembly(func, depth=0, **kwargs)
989 self.do_disassembly_compare(got, expected)
990 # Add checks for dis.disco
991 if hasattr(func, '__code__'):
992 got_disco = io.StringIO()
993 with contextlib.redirect_stdout(got_disco):
994 dis.disco(func.__code__, **kwargs)
995 self.do_disassembly_compare(got_disco.getvalue(), expected)
996
997 def test_opmap(self):
998 self.assertEqual(dis.opmap["CACHE"], 0)
999 self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst)
1000 self.assertIn(dis.opmap["STORE_NAME"], dis.hasname)
1001
1002 def test_opname(self):
1003 self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST")
1004
1005 def test_boundaries(self):
1006 self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG)
1007
1008 def test_widths(self):
1009 long_opcodes = set(['JUMP_BACKWARD_NO_INTERRUPT',
1010 'LOAD_FAST_BORROW_LOAD_FAST_BORROW',
1011 'INSTRUMENTED_CALL_FUNCTION_EX',
1012 'ANNOTATIONS_PLACEHOLDER'])
1013 for op, opname in enumerate(dis.opname):
1014 if opname in long_opcodes or opname.startswith("INSTRUMENTED"):
1015 continue
1016 if opname in opcode._specialized_opmap:
1017 continue
1018 with self.subTest(opname=opname):
1019 width = dis._OPNAME_WIDTH
1020 if op in dis.hasarg:
1021 width += 1 + dis._OPARG_WIDTH
1022 self.assertLessEqual(len(opname), width)
1023
1024 def test_dis(self):
1025 self.do_disassembly_test(_f, dis_f)
1026
1027 def test_dis_with_offsets(self):
1028 self.do_disassembly_test(_f, dis_f_with_offsets, show_offsets=True)
1029
1030 @requires_debug_ranges()
1031 def test_dis_with_all_positions(self):
1032 def format_instr_positions(instr):
1033 values = tuple('?' if p is None else p for p in instr.positions)
1034 return '%s:%s-%s:%s' % (values[0], values[2], values[1], values[3])
1035
1036 instrs = list(dis.get_instructions(_f))
1037 for instr in instrs:
1038 with self.subTest(instr=instr):
1039 self.assertTrue(all(p is not None for p in instr.positions))
1040 positions = tuple(map(format_instr_positions, instrs))
1041 expected = dis_f_with_positions_format % positions
1042 self.do_disassembly_test(_f, expected, show_positions=True)
1043
1044 @requires_debug_ranges()
1045 def test_dis_with_some_positions(self):
1046 code = ("def f():\n"
1047 " try: pass\n"
1048 " finally:pass")
1049 f = compile(ast.parse(code), "?", "exec").co_consts[0]
1050
1051 expect = '\n'.join([
1052 '1:0-1:0 RESUME 0',
1053 '',
1054 '2:3-3:15 NOP',
1055 '',
1056 '3:11-3:15 LOAD_CONST 0 (None)',
1057 '3:11-3:15 RETURN_VALUE',
1058 '',
1059 ' -- L1: PUSH_EXC_INFO',
1060 '',
1061 '3:11-3:15 RERAISE 0',
1062 '',
1063 ' -- L2: COPY 3',
1064 ' -- POP_EXCEPT',
1065 ' -- RERAISE 1',
1066 'ExceptionTable:',
1067 ' L1 to L2 -> L2 [1] lasti',
1068 '',
1069 ])
1070 self.do_disassembly_test(f, expect, show_positions=True)
1071
1072 @requires_debug_ranges()
1073 def test_dis_with_linenos_but_no_columns(self):
1074 code = "def f():\n\tx = 1"
1075 tree = ast.parse(code)
1076 func = tree.body[0]
1077 ass_x = func.body[0].targets[0]
1078 # remove columns information but keep line information
1079 ass_x.col_offset = ass_x.end_col_offset = -1
1080 f = compile(tree, "?", "exec").co_consts[0]
1081
1082 expect = '\n'.join([
1083 '1:0-1:0 RESUME 0',
1084 '',
1085 '2:5-2:6 LOAD_SMALL_INT 1',
1086 '2:?-2:? STORE_FAST 0 (x)',
1087 '2:?-2:? LOAD_CONST 1 (None)',
1088 '2:?-2:? RETURN_VALUE',
1089 '',
1090 ])
1091 self.do_disassembly_test(f, expect, show_positions=True)
1092
1093 def test_dis_with_no_positions(self):
1094 def f():
1095 pass
1096
1097 f.__code__ = f.__code__.replace(co_linetable=b'')
1098 expect = '\n'.join([
1099 ' RESUME 0',
1100 ' LOAD_CONST 0 (None)',
1101 ' RETURN_VALUE',
1102 '',
1103 ])
1104 self.do_disassembly_test(f, expect, show_positions=True)
1105
1106 def test_bug_708901(self):
1107 self.do_disassembly_test(bug708901, dis_bug708901)
1108
1109 def test_bug_1333982(self):
1110 # This one is checking bytecodes generated for an `assert` statement,
1111 # so fails if the tests are run with -O. Skip this test then.
1112 if not __debug__:
1113 self.skipTest('need asserts, run without -O')
1114
1115 self.do_disassembly_test(bug1333982, dis_bug1333982)
1116
1117 def test_bug_42562(self):
1118 self.do_disassembly_test(bug42562, dis_bug42562)
1119
1120 def test_bug_45757(self):
1121 # Extended arg followed by NOP
1122 self.do_disassembly_test(code_bug_45757, dis_bug_45757)
1123
1124 def test_bug_46724(self):
1125 # Test that negative operargs are handled properly
1126 self.do_disassembly_test(bug46724, dis_bug46724)
1127
1128 def test_kw_names(self):
1129 # Test that value is displayed for keyword argument names:
1130 self.do_disassembly_test(wrap_func_w_kwargs, dis_kw_names)
1131
1132 def test_intrinsic_1(self):
1133 # Test that argrepr is displayed for CALL_INTRINSIC_1
1134 self.do_disassembly_test("from math import *", dis_intrinsic_1_2)
1135 self.do_disassembly_test("+a", dis_intrinsic_1_5)
1136 self.do_disassembly_test("(*a,)", dis_intrinsic_1_6)
1137
1138 def test_intrinsic_2(self):
1139 self.assertIn("CALL_INTRINSIC_2 1 (INTRINSIC_PREP_RERAISE_STAR)",
1140 self.get_disassembly("try: pass\nexcept* Exception: x"))
1141
1142 def test_big_linenos(self):
1143 def func(count):
1144 namespace = {}
1145 func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"])
1146 exec(func, namespace)
1147 return namespace['foo']
1148
1149 # Test all small ranges
1150 for i in range(1, 300):
1151 expected = _BIG_LINENO_FORMAT % (i + 2)
1152 self.do_disassembly_test(func(i), expected)
1153
1154 # Test some larger ranges too
1155 for i in range(300, 1000, 10):
1156 expected = _BIG_LINENO_FORMAT % (i + 2)
1157 self.do_disassembly_test(func(i), expected)
1158
1159 for i in range(1000, 5000, 10):
1160 expected = _BIG_LINENO_FORMAT2 % (i + 2)
1161 self.do_disassembly_test(func(i), expected)
1162
1163 from test import dis_module
1164 self.do_disassembly_test(dis_module, dis_module_expected_results)
1165
1166 def test_disassemble_str(self):
1167 self.do_disassembly_test(expr_str, dis_expr_str)
1168 self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str)
1169 self.do_disassembly_test(annot_stmt_str, dis_annot_stmt_str)
1170 self.do_disassembly_test(fn_with_annotate_str, dis_fn_with_annotate_str)
1171 self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str)
1172
1173 def test_disassemble_bytes(self):
1174 self.do_disassembly_test(_f.__code__.co_code, dis_f_co_code)
1175
1176 def test_disassemble_class(self):
1177 self.do_disassembly_test(_C, dis_c)
1178
1179 def test_disassemble_instance_method(self):
1180 self.do_disassembly_test(_C(1).__init__, dis_c_instance_method)
1181
1182 def test_disassemble_instance_method_bytes(self):
1183 method_bytecode = _C(1).__init__.__code__.co_code
1184 self.do_disassembly_test(method_bytecode, dis_c_instance_method_bytes)
1185
1186 def test_disassemble_static_method(self):
1187 self.do_disassembly_test(_C.sm, dis_c_static_method)
1188
1189 def test_disassemble_class_method(self):
1190 self.do_disassembly_test(_C.cm, dis_c_class_method)
1191
1192 def test_disassemble_generator(self):
1193 gen_func_disas = self.get_disassembly(_g) # Generator function
1194 gen_disas = self.get_disassembly(_g(1)) # Generator iterator
1195 self.assertEqual(gen_disas, gen_func_disas)
1196
1197 def test_disassemble_async_generator(self):
1198 agen_func_disas = self.get_disassembly(_ag) # Async generator function
1199 agen_disas = self.get_disassembly(_ag(1)) # Async generator iterator
1200 self.assertEqual(agen_disas, agen_func_disas)
1201
1202 def test_disassemble_coroutine(self):
1203 coro_func_disas = self.get_disassembly(_co) # Coroutine function
1204 coro = _co(1) # Coroutine object
1205 coro.close() # Avoid a RuntimeWarning (never awaited)
1206 coro_disas = self.get_disassembly(coro)
1207 self.assertEqual(coro_disas, coro_func_disas)
1208
1209 def test_disassemble_fstring(self):
1210 self.do_disassembly_test(_fstring, dis_fstring)
1211
1212 def test_disassemble_with(self):
1213 self.do_disassembly_test(_with, dis_with)
1214
1215 def test_disassemble_asyncwith(self):
1216 self.do_disassembly_test(_asyncwith, dis_asyncwith)
1217
1218 def test_disassemble_try_finally(self):
1219 self.do_disassembly_test(_tryfinally, dis_tryfinally)
1220 self.do_disassembly_test(_tryfinallyconst, dis_tryfinallyconst)
1221
1222 def test_dis_none(self):
1223 try:
1224 del sys.last_exc
1225 except AttributeError:
1226 pass
1227 try:
1228 del sys.last_traceback
1229 except AttributeError:
1230 pass
1231 self.assertRaises(RuntimeError, dis.dis, None)
1232
1233 def test_dis_traceback(self):
1234 self.maxDiff = None
1235 try:
1236 del sys.last_traceback
1237 except AttributeError:
1238 pass
1239
1240 try:
1241 1/0
1242 except Exception as e:
1243 tb = e.__traceback__
1244 sys.last_exc = e
1245
1246 tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti)
1247 self.do_disassembly_test(None, tb_dis)
1248
1249 def test_dis_object(self):
1250 self.assertRaises(TypeError, dis.dis, object())
1251
1252 def test_disassemble_recursive(self):
1253 def check(expected, **kwargs):
1254 dis = self.get_disassembly(_h, **kwargs)
1255 dis = self.strip_addresses(dis)
1256 self.assertEqual(dis, expected)
1257
1258 check(dis_nested_0, depth=0)
1259 check(dis_nested_1, depth=1)
1260 check(dis_nested_2, depth=2)
1261 check(dis_nested_2, depth=3)
1262 check(dis_nested_2, depth=None)
1263 check(dis_nested_2)
1264
1265 def test__try_compile_no_context_exc_on_error(self):
1266 # see gh-102114
1267 try:
1268 dis._try_compile(")", "")
1269 except Exception as e:
1270 self.assertIsNone(e.__context__)
1271
1272 def test_async_for_presentation(self):
1273
1274 async def afunc():
1275 async for letter in async_iter1:
1276 l2
1277 l3
1278
1279 disassembly = self.get_disassembly(afunc)
1280 for line in disassembly.split("\n"):
1281 if "END_ASYNC_FOR" in line:
1282 break
1283 else:
1284 self.fail("No END_ASYNC_FOR in disassembly of async for")
1285 self.assertNotIn("to", line)
1286 self.assertIn("from", line)
1287
1288
1289 @staticmethod
1290 def code_quicken(f):
1291 _testinternalcapi = import_helper.import_module("_testinternalcapi")
1292 for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD):
1293 f()
1294
1295 @cpython_only
1296 @requires_specialization
1297 def test_super_instructions(self):
1298 self.code_quicken(lambda: load_test(0, 0))
1299 got = self.get_disassembly(load_test, adaptive=True)
1300 self.do_disassembly_compare(got, dis_load_test_quickened_code)
1301
1302 @cpython_only
1303 @requires_specialization
1304 def test_load_attr_specialize(self):
1305 load_attr_quicken = """\
1306 0 RESUME_CHECK 0
1307
1308 1 LOAD_CONST_IMMORTAL 0 ('a')
1309 LOAD_ATTR_SLOT 0 (__class__)
1310 RETURN_VALUE
1311 """
1312 co = compile("'a'.__class__", "", "eval")
1313 self.code_quicken(lambda: exec(co, {}, {}))
1314 got = self.get_disassembly(co, adaptive=True)
1315 self.do_disassembly_compare(got, load_attr_quicken)
1316
1317 @cpython_only
1318 @requires_specialization
1319 def test_call_specialize(self):
1320 call_quicken = """\
1321 0 RESUME_CHECK 0
1322
1323 1 LOAD_NAME 0 (str)
1324 PUSH_NULL
1325 LOAD_SMALL_INT 1
1326 CALL_STR_1 1
1327 RETURN_VALUE
1328 """
1329 co = compile("str(1)", "", "eval")
1330 self.code_quicken(lambda: exec(co, {}, {}))
1331 got = self.get_disassembly(co, adaptive=True)
1332 self.do_disassembly_compare(got, call_quicken)
1333
1334 @cpython_only
1335 @requires_specialization
1336 def test_loop_quicken(self):
1337 # Loop can trigger a quicken where the loop is located
1338 self.code_quicken(loop_test)
1339 got = self.get_disassembly(loop_test, adaptive=True)
1340 jit = sys._jit.is_enabled()
1341 expected = dis_loop_test_quickened_code.format("JIT" if jit else "NO_JIT")
1342 self.do_disassembly_compare(got, expected)
1343
1344 @cpython_only
1345 @requires_specialization
1346 def test_loop_with_conditional_at_end_is_quickened(self):
1347 _testinternalcapi = import_helper.import_module("_testinternalcapi")
1348 def for_loop_true(x):
1349 for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD):
1350 if x:
1351 pass
1352
1353 for_loop_true(True)
1354 self.assertIn('FOR_ITER_RANGE',
1355 self.get_disassembly(for_loop_true, adaptive=True))
1356
1357 def for_loop_false(x):
1358 for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD):
1359 if x:
1360 pass
1361
1362 for_loop_false(False)
1363 self.assertIn('FOR_ITER_RANGE',
1364 self.get_disassembly(for_loop_false, adaptive=True))
1365
1366 def while_loop():
1367 i = 0
1368 while i < _testinternalcapi.SPECIALIZATION_THRESHOLD:
1369 i += 1
1370
1371 while_loop()
1372 self.assertIn('COMPARE_OP_INT',
1373 self.get_disassembly(while_loop, adaptive=True))
1374
1375 @cpython_only
1376 def test_extended_arg_quick(self):
1377 got = self.get_disassembly(extended_arg_quick)
1378 self.do_disassembly_compare(got, dis_extended_arg_quick_code)
1379
1380 def get_cached_values(self, quickened, adaptive):
1381 def f():
1382 l = []
1383 for i in range(42):
1384 l.append(i)
1385 if quickened:
1386 self.code_quicken(f)
1387 else:
1388 # "copy" the code to un-quicken it:
1389 reset_code(f)
1390 for instruction in _unroll_caches_as_Instructions(dis.get_instructions(
1391 f, show_caches=True, adaptive=adaptive
1392 ), show_caches=True):
1393 if instruction.opname == "CACHE":
1394 yield instruction.argrepr
1395
1396 @cpython_only
1397 def test_show_caches(self):
1398 for quickened in (False, True):
1399 for adaptive in (False, True):
1400 with self.subTest(f"{quickened=}, {adaptive=}"):
1401 if adaptive:
1402 pattern = r"^(\w+: \d+)?$"
1403 else:
1404 pattern = r"^(\w+: 0)?$"
1405 caches = list(self.get_cached_values(quickened, adaptive))
1406 for cache in caches:
1407 self.assertRegex(cache, pattern)
1408 total_caches = 21
1409 empty_caches = 7
1410 self.assertEqual(caches.count(""), empty_caches)
1411 self.assertEqual(len(caches), total_caches)
1412
1413 @cpython_only
1414 def test_show_currinstr_with_cache(self):
1415 """
1416 Make sure that with lasti pointing to CACHE, it still shows the current
1417 line correctly
1418 """
1419 def f():
1420 print(a)
1421 # The code above should generate a LOAD_GLOBAL which has CACHE instr after
1422 # However, this might change in the future. So we explicitly try to find
1423 # a CACHE entry in the instructions. If we can't do that, fail the test
1424
1425 for inst in _unroll_caches_as_Instructions(
1426 dis.get_instructions(f, show_caches=True), show_caches=True):
1427 if inst.opname == "CACHE":
1428 op_offset = inst.offset - 2
1429 cache_offset = inst.offset
1430 break
1431 else:
1432 opname = inst.opname
1433 else:
1434 self.fail("Can't find a CACHE entry in the function provided to do the test")
1435
1436 assem_op = self.get_disassembly(f.__code__, lasti=op_offset, wrapper=False)
1437 assem_cache = self.get_disassembly(f.__code__, lasti=cache_offset, wrapper=False)
1438
1439 # Make sure --> exists and points to the correct op
1440 self.assertRegex(assem_op, fr"--> {opname}")
1441 # Make sure when lasti points to cache, it shows the same disassembly
1442 self.assertEqual(assem_op, assem_cache)
1443
1444
1445 class DisWithFileTests(DisTests):
1446
1447 # Run the tests again, using the file arg instead of print
1448 def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs):
1449 output = io.StringIO()
1450 if wrapper:
1451 dis.dis(func, file=output, **kwargs)
1452 else:
1453 dis.disassemble(func, lasti, file=output, **kwargs)
1454 return output.getvalue()
1455
1456
1457 if dis.code_info.__doc__ is None:
1458 code_info_consts = "0: None"
1459 else:
1460 code_info_consts = "0: 'Formatted details of methods, functions, or code.'"
1461
1462 code_info_code_info = f"""\
1463 Name: code_info
1464 Filename: (.*)
1465 Argument count: 1
1466 Positional-only arguments: 0
1467 Kw-only arguments: 0
1468 Number of locals: 1
1469 Stack size: \\d+
1470 Flags: OPTIMIZED, NEWLOCALS, HAS_DOCSTRING
1471 Constants:
1472 {code_info_consts}
1473 Names:
1474 0: _format_code_info
1475 1: _get_code_object
1476 Variable names:
1477 0: x"""
1478
1479
1480 @staticmethod
1481 def tricky(a, b, /, x, y, z=True, *args, c, d, e=[], **kwds):
1482 def f(c=c):
1483 print(a, b, x, y, z, c, d, e, f)
1484 yield a, b, x, y, z, c, d, e, f
1485
1486 code_info_tricky = """\
1487 Name: tricky
1488 Filename: (.*)
1489 Argument count: 5
1490 Positional-only arguments: 2
1491 Kw-only arguments: 3
1492 Number of locals: 10
1493 Stack size: \\d+
1494 Flags: OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR
1495 Constants:
1496 0: <code object f at (.*), file "(.*)", line (.*)>
1497 1: None
1498 Variable names:
1499 0: a
1500 1: b
1501 2: x
1502 3: y
1503 4: z
1504 5: c
1505 6: d
1506 7: e
1507 8: args
1508 9: kwds
1509 Cell variables:
1510 0: [abedfxyz]
1511 1: [abedfxyz]
1512 2: [abedfxyz]
1513 3: [abedfxyz]
1514 4: [abedfxyz]
1515 5: [abedfxyz]
1516 6: [abedfxyz]
1517 7: [abedfxyz]"""
1518 # NOTE: the order of the cell variables above depends on dictionary order!
1519
1520 co_tricky_nested_f = tricky.__func__.__code__.co_consts[0]
1521
1522 code_info_tricky_nested_f = """\
1523 Filename: (.*)
1524 Argument count: 1
1525 Positional-only arguments: 0
1526 Kw-only arguments: 0
1527 Number of locals: 1
1528 Stack size: \\d+
1529 Flags: OPTIMIZED, NEWLOCALS, NESTED
1530 Constants:
1531 0: None
1532 Names:
1533 0: print
1534 Variable names:
1535 0: c
1536 Free variables:
1537 0: [abedfxyz]
1538 1: [abedfxyz]
1539 2: [abedfxyz]
1540 3: [abedfxyz]
1541 4: [abedfxyz]
1542 5: [abedfxyz]"""
1543
1544 code_info_expr_str = """\
1545 Name: <module>
1546 Filename: <disassembly>
1547 Argument count: 0
1548 Positional-only arguments: 0
1549 Kw-only arguments: 0
1550 Number of locals: 0
1551 Stack size: \\d+
1552 Flags: 0x0
1553 Constants:
1554 0: 1
1555 Names:
1556 0: x"""
1557
1558 code_info_simple_stmt_str = """\
1559 Name: <module>
1560 Filename: <disassembly>
1561 Argument count: 0
1562 Positional-only arguments: 0
1563 Kw-only arguments: 0
1564 Number of locals: 0
1565 Stack size: \\d+
1566 Flags: 0x0
1567 Constants:
1568 0: 1
1569 1: None
1570 Names:
1571 0: x"""
1572
1573 code_info_compound_stmt_str = """\
1574 Name: <module>
1575 Filename: <disassembly>
1576 Argument count: 0
1577 Positional-only arguments: 0
1578 Kw-only arguments: 0
1579 Number of locals: 0
1580 Stack size: \\d+
1581 Flags: 0x0
1582 Constants:
1583 0: 0
1584 Names:
1585 0: x"""
1586
1587
1588 async def async_def():
1589 await 1
1590 async for a in b: pass
1591 async with c as d: pass
1592
1593 code_info_async_def = """\
1594 Name: async_def
1595 Filename: (.*)
1596 Argument count: 0
1597 Positional-only arguments: 0
1598 Kw-only arguments: 0
1599 Number of locals: 2
1600 Stack size: \\d+
1601 Flags: OPTIMIZED, NEWLOCALS, COROUTINE
1602 Constants:
1603 0: 1
1604 1: None
1605 Names:
1606 0: b
1607 1: c
1608 Variable names:
1609 0: a
1610 1: d"""
1611
1612 class CodeInfoTests(unittest.TestCase):
1613 test_pairs = [
1614 (dis.code_info, code_info_code_info),
1615 (tricky, code_info_tricky),
1616 (co_tricky_nested_f, code_info_tricky_nested_f),
1617 (expr_str, code_info_expr_str),
1618 (simple_stmt_str, code_info_simple_stmt_str),
1619 (compound_stmt_str, code_info_compound_stmt_str),
1620 (async_def, code_info_async_def)
1621 ]
1622
1623 def test_code_info(self):
1624 self.maxDiff = 1000
1625 for x, expected in self.test_pairs:
1626 self.assertRegex(dis.code_info(x), expected)
1627
1628 def test_show_code(self):
1629 self.maxDiff = 1000
1630 for x, expected in self.test_pairs:
1631 with captured_stdout() as output:
1632 dis.show_code(x)
1633 self.assertRegex(output.getvalue(), expected+"\n")
1634 output = io.StringIO()
1635 dis.show_code(x, file=output)
1636 self.assertRegex(output.getvalue(), expected)
1637
1638 def test_code_info_object(self):
1639 self.assertRaises(TypeError, dis.code_info, object())
1640
1641 def test_pretty_flags_no_flags(self):
1642 self.assertEqual(dis.pretty_flags(0), '0x0')
1643
1644
1645 # Fodder for instruction introspection tests
1646 # Editing any of these may require recalculating the expected output
1647 def outer(a=1, b=2):
1648 def f(c=3, d=4):
1649 def inner(e=5, f=6):
1650 print(a, b, c, d, e, f)
1651 print(a, b, c, d)
1652 return inner
1653 print(a, b, '', 1, [], {}, "Hello world!")
1654 return f
1655
1656 def jumpy():
1657 # This won't actually run (but that's OK, we only disassemble it)
1658 for i in range(10):
1659 print(i)
1660 if i < 4:
1661 continue
1662 if i > 6:
1663 break
1664 else:
1665 print("I can haz else clause?")
1666 while i:
1667 print(i)
1668 i -= 1
1669 if i > 6:
1670 continue
1671 if i < 4:
1672 break
1673 else:
1674 print("Who let lolcatz into this test suite?")
1675 try:
1676 1 / 0
1677 except ZeroDivisionError:
1678 print("Here we go, here we go, here we go...")
1679 else:
1680 with i as dodgy:
1681 print("Never reach this")
1682 finally:
1683 print("OK, now we're done")
1684
1685 # End fodder for opinfo generation tests
1686 expected_outer_line = 1
1687 _line_offset = outer.__code__.co_firstlineno - 1
1688 code_object_f = outer.__code__.co_consts[1]
1689 expected_f_line = code_object_f.co_firstlineno - _line_offset
1690 code_object_inner = code_object_f.co_consts[1]
1691 expected_inner_line = code_object_inner.co_firstlineno - _line_offset
1692 expected_jumpy_line = 1
1693
1694 # The following lines are useful to regenerate the expected results after
1695 # either the fodder is modified or the bytecode generation changes
1696 # After regeneration, update the references to code_object_f and
1697 # code_object_inner before rerunning the tests
1698
1699 def _stringify_instruction(instr):
1700 # Since postions offsets change a lot for these test cases, ignore them.
1701 base = (
1702 f" make_inst(opname={instr.opname!r}, arg={instr.arg!r}, argval={instr.argval!r}, " +
1703 f"argrepr={instr.argrepr!r}, offset={instr.offset}, start_offset={instr.start_offset}, " +
1704 f"starts_line={instr.starts_line!r}, line_number={instr.line_number}"
1705 )
1706 if instr.label is not None:
1707 base += f", label={instr.label!r}"
1708 if instr.cache_info:
1709 base += f", cache_info={instr.cache_info!r}"
1710 return base + "),"
1711
1712 def _prepare_test_cases():
1713 ignore = io.StringIO()
1714 with contextlib.redirect_stdout(ignore):
1715 f = outer()
1716 inner = f()
1717 _instructions_outer = dis.get_instructions(outer, first_line=expected_outer_line)
1718 _instructions_f = dis.get_instructions(f, first_line=expected_f_line)
1719 _instructions_inner = dis.get_instructions(inner, first_line=expected_inner_line)
1720 _instructions_jumpy = dis.get_instructions(jumpy, first_line=expected_jumpy_line)
1721 result = "\n".join(
1722 [
1723 "expected_opinfo_outer = [",
1724 *map(_stringify_instruction, _instructions_outer),
1725 "]",
1726 "",
1727 "expected_opinfo_f = [",
1728 *map(_stringify_instruction, _instructions_f),
1729 "]",
1730 "",
1731 "expected_opinfo_inner = [",
1732 *map(_stringify_instruction, _instructions_inner),
1733 "]",
1734 "",
1735 "expected_opinfo_jumpy = [",
1736 *map(_stringify_instruction, _instructions_jumpy),
1737 "]",
1738 ]
1739 )
1740 result = result.replace(repr(repr(code_object_f)), "repr(code_object_f)")
1741 result = result.replace(repr(code_object_f), "code_object_f")
1742 result = result.replace(repr(repr(code_object_inner)), "repr(code_object_inner)")
1743 result = result.replace(repr(code_object_inner), "code_object_inner")
1744 print(result)
1745
1746 # from test.test_dis import _prepare_test_cases; _prepare_test_cases()
1747
1748 make_inst = dis.Instruction.make
1749
1750 expected_opinfo_outer = [
1751 make_inst(opname='MAKE_CELL', arg=0, argval='a', argrepr='a', offset=0, start_offset=0, starts_line=True, line_number=None),
1752 make_inst(opname='MAKE_CELL', arg=1, argval='b', argrepr='b', offset=2, start_offset=2, starts_line=False, line_number=None),
1753 make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=4, start_offset=4, starts_line=True, line_number=1),
1754 make_inst(opname='LOAD_CONST', arg=4, argval=(3, 4), argrepr='(3, 4)', offset=6, start_offset=6, starts_line=True, line_number=2),
1755 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='a', argrepr='a', offset=8, start_offset=8, starts_line=False, line_number=2),
1756 make_inst(opname='LOAD_FAST_BORROW', arg=1, argval='b', argrepr='b', offset=10, start_offset=10, starts_line=False, line_number=2),
1757 make_inst(opname='BUILD_TUPLE', arg=2, argval=2, argrepr='', offset=12, start_offset=12, starts_line=False, line_number=2),
1758 make_inst(opname='LOAD_CONST', arg=1, argval=code_object_f, argrepr=repr(code_object_f), offset=14, start_offset=14, starts_line=False, line_number=2),
1759 make_inst(opname='MAKE_FUNCTION', arg=None, argval=None, argrepr='', offset=16, start_offset=16, starts_line=False, line_number=2),
1760 make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=8, argval=8, argrepr='closure', offset=18, start_offset=18, starts_line=False, line_number=2),
1761 make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=1, argval=1, argrepr='defaults', offset=20, start_offset=20, starts_line=False, line_number=2),
1762 make_inst(opname='STORE_FAST', arg=2, argval='f', argrepr='f', offset=22, start_offset=22, starts_line=False, line_number=2),
1763 make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=24, start_offset=24, starts_line=True, line_number=7, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1764 make_inst(opname='LOAD_DEREF', arg=0, argval='a', argrepr='a', offset=34, start_offset=34, starts_line=False, line_number=7),
1765 make_inst(opname='LOAD_DEREF', arg=1, argval='b', argrepr='b', offset=36, start_offset=36, starts_line=False, line_number=7),
1766 make_inst(opname='LOAD_CONST', arg=2, argval='', argrepr="''", offset=38, start_offset=38, starts_line=False, line_number=7),
1767 make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=40, start_offset=40, starts_line=False, line_number=7),
1768 make_inst(opname='BUILD_LIST', arg=0, argval=0, argrepr='', offset=42, start_offset=42, starts_line=False, line_number=7),
1769 make_inst(opname='BUILD_MAP', arg=0, argval=0, argrepr='', offset=44, start_offset=44, starts_line=False, line_number=7),
1770 make_inst(opname='LOAD_CONST', arg=3, argval='Hello world!', argrepr="'Hello world!'", offset=46, start_offset=46, starts_line=False, line_number=7),
1771 make_inst(opname='CALL', arg=7, argval=7, argrepr='', offset=48, start_offset=48, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1772 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=56, start_offset=56, starts_line=False, line_number=7),
1773 make_inst(opname='LOAD_FAST_BORROW', arg=2, argval='f', argrepr='f', offset=58, start_offset=58, starts_line=True, line_number=8),
1774 make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=60, start_offset=60, starts_line=False, line_number=8),
1775 ]
1776
1777 expected_opinfo_f = [
1778 make_inst(opname='COPY_FREE_VARS', arg=2, argval=2, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=None),
1779 make_inst(opname='MAKE_CELL', arg=0, argval='c', argrepr='c', offset=2, start_offset=2, starts_line=False, line_number=None),
1780 make_inst(opname='MAKE_CELL', arg=1, argval='d', argrepr='d', offset=4, start_offset=4, starts_line=False, line_number=None),
1781 make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=6, start_offset=6, starts_line=True, line_number=2),
1782 make_inst(opname='LOAD_CONST', arg=2, argval=(5, 6), argrepr='(5, 6)', offset=8, start_offset=8, starts_line=True, line_number=3),
1783 make_inst(opname='LOAD_FAST_BORROW', arg=3, argval='a', argrepr='a', offset=10, start_offset=10, starts_line=False, line_number=3),
1784 make_inst(opname='LOAD_FAST_BORROW', arg=4, argval='b', argrepr='b', offset=12, start_offset=12, starts_line=False, line_number=3),
1785 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='c', argrepr='c', offset=14, start_offset=14, starts_line=False, line_number=3),
1786 make_inst(opname='LOAD_FAST_BORROW', arg=1, argval='d', argrepr='d', offset=16, start_offset=16, starts_line=False, line_number=3),
1787 make_inst(opname='BUILD_TUPLE', arg=4, argval=4, argrepr='', offset=18, start_offset=18, starts_line=False, line_number=3),
1788 make_inst(opname='LOAD_CONST', arg=1, argval=code_object_inner, argrepr=repr(code_object_inner), offset=20, start_offset=20, starts_line=False, line_number=3),
1789 make_inst(opname='MAKE_FUNCTION', arg=None, argval=None, argrepr='', offset=22, start_offset=22, starts_line=False, line_number=3),
1790 make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=8, argval=8, argrepr='closure', offset=24, start_offset=24, starts_line=False, line_number=3),
1791 make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=1, argval=1, argrepr='defaults', offset=26, start_offset=26, starts_line=False, line_number=3),
1792 make_inst(opname='STORE_FAST', arg=2, argval='inner', argrepr='inner', offset=28, start_offset=28, starts_line=False, line_number=3),
1793 make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=30, start_offset=30, starts_line=True, line_number=5, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1794 make_inst(opname='LOAD_DEREF', arg=3, argval='a', argrepr='a', offset=40, start_offset=40, starts_line=False, line_number=5),
1795 make_inst(opname='LOAD_DEREF', arg=4, argval='b', argrepr='b', offset=42, start_offset=42, starts_line=False, line_number=5),
1796 make_inst(opname='LOAD_DEREF', arg=0, argval='c', argrepr='c', offset=44, start_offset=44, starts_line=False, line_number=5),
1797 make_inst(opname='LOAD_DEREF', arg=1, argval='d', argrepr='d', offset=46, start_offset=46, starts_line=False, line_number=5),
1798 make_inst(opname='CALL', arg=4, argval=4, argrepr='', offset=48, start_offset=48, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1799 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=56, start_offset=56, starts_line=False, line_number=5),
1800 make_inst(opname='LOAD_FAST_BORROW', arg=2, argval='inner', argrepr='inner', offset=58, start_offset=58, starts_line=True, line_number=6),
1801 make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=60, start_offset=60, starts_line=False, line_number=6),
1802 ]
1803
1804 expected_opinfo_inner = [
1805 make_inst(opname='COPY_FREE_VARS', arg=4, argval=4, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=None),
1806 make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=2, start_offset=2, starts_line=True, line_number=3),
1807 make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=4, start_offset=4, starts_line=True, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1808 make_inst(opname='LOAD_DEREF', arg=2, argval='a', argrepr='a', offset=14, start_offset=14, starts_line=False, line_number=4),
1809 make_inst(opname='LOAD_DEREF', arg=3, argval='b', argrepr='b', offset=16, start_offset=16, starts_line=False, line_number=4),
1810 make_inst(opname='LOAD_DEREF', arg=4, argval='c', argrepr='c', offset=18, start_offset=18, starts_line=False, line_number=4),
1811 make_inst(opname='LOAD_DEREF', arg=5, argval='d', argrepr='d', offset=20, start_offset=20, starts_line=False, line_number=4),
1812 make_inst(opname='LOAD_FAST_BORROW_LOAD_FAST_BORROW', arg=1, argval=('e', 'f'), argrepr='e, f', offset=22, start_offset=22, starts_line=False, line_number=4),
1813 make_inst(opname='CALL', arg=6, argval=6, argrepr='', offset=24, start_offset=24, starts_line=False, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1814 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=32, start_offset=32, starts_line=False, line_number=4),
1815 make_inst(opname='LOAD_CONST', arg=0, argval=None, argrepr='None', offset=34, start_offset=34, starts_line=False, line_number=4),
1816 make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=36, start_offset=36, starts_line=False, line_number=4),
1817 ]
1818
1819 expected_opinfo_jumpy = [
1820 make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=1),
1821 make_inst(opname='LOAD_GLOBAL', arg=1, argval='range', argrepr='range + NULL', offset=2, start_offset=2, starts_line=True, line_number=3, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1822 make_inst(opname='LOAD_SMALL_INT', arg=10, argval=10, argrepr='', offset=12, start_offset=12, starts_line=False, line_number=3),
1823 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=14, start_offset=14, starts_line=False, line_number=3, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1824 make_inst(opname='GET_ITER', arg=None, argval=None, argrepr='', offset=22, start_offset=22, starts_line=False, line_number=3),
1825 make_inst(opname='FOR_ITER', arg=32, argval=92, argrepr='to L4', offset=24, start_offset=24, starts_line=False, line_number=3, label=1, cache_info=[('counter', 1, b'\x00\x00')]),
1826 make_inst(opname='STORE_FAST', arg=0, argval='i', argrepr='i', offset=28, start_offset=28, starts_line=False, line_number=3),
1827 make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=30, start_offset=30, starts_line=True, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1828 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=40, start_offset=40, starts_line=False, line_number=4),
1829 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=42, start_offset=42, starts_line=False, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1830 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=50, start_offset=50, starts_line=False, line_number=4),
1831 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=52, start_offset=52, starts_line=True, line_number=5),
1832 make_inst(opname='LOAD_SMALL_INT', arg=4, argval=4, argrepr='', offset=54, start_offset=54, starts_line=False, line_number=5),
1833 make_inst(opname='COMPARE_OP', arg=18, argval='<', argrepr='bool(<)', offset=56, start_offset=56, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00')]),
1834 make_inst(opname='POP_JUMP_IF_FALSE', arg=3, argval=70, argrepr='to L2', offset=60, start_offset=60, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00')]),
1835 make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=64, start_offset=64, starts_line=False, line_number=5),
1836 make_inst(opname='JUMP_BACKWARD', arg=23, argval=24, argrepr='to L1', offset=66, start_offset=66, starts_line=True, line_number=6, cache_info=[('counter', 1, b'\x00\x00')]),
1837 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=70, start_offset=70, starts_line=True, line_number=7, label=2),
1838 make_inst(opname='LOAD_SMALL_INT', arg=6, argval=6, argrepr='', offset=72, start_offset=72, starts_line=False, line_number=7),
1839 make_inst(opname='COMPARE_OP', arg=148, argval='>', argrepr='bool(>)', offset=74, start_offset=74, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]),
1840 make_inst(opname='POP_JUMP_IF_TRUE', arg=3, argval=88, argrepr='to L3', offset=78, start_offset=78, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]),
1841 make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=82, start_offset=82, starts_line=False, line_number=7),
1842 make_inst(opname='JUMP_BACKWARD', arg=32, argval=24, argrepr='to L1', offset=84, start_offset=84, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]),
1843 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=88, start_offset=88, starts_line=True, line_number=8, label=3),
1844 make_inst(opname='JUMP_FORWARD', arg=13, argval=118, argrepr='to L5', offset=90, start_offset=90, starts_line=False, line_number=8),
1845 make_inst(opname='END_FOR', arg=None, argval=None, argrepr='', offset=92, start_offset=92, starts_line=True, line_number=3, label=4),
1846 make_inst(opname='POP_ITER', arg=None, argval=None, argrepr='', offset=94, start_offset=94, starts_line=False, line_number=3),
1847 make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=96, start_offset=96, starts_line=True, line_number=10, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1848 make_inst(opname='LOAD_CONST', arg=1, argval='I can haz else clause?', argrepr="'I can haz else clause?'", offset=106, start_offset=106, starts_line=False, line_number=10),
1849 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=108, start_offset=108, starts_line=False, line_number=10, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1850 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=116, start_offset=116, starts_line=False, line_number=10),
1851 make_inst(opname='LOAD_FAST_CHECK', arg=0, argval='i', argrepr='i', offset=118, start_offset=118, starts_line=True, line_number=11, label=5),
1852 make_inst(opname='TO_BOOL', arg=None, argval=None, argrepr='', offset=120, start_offset=120, starts_line=False, line_number=11, cache_info=[('counter', 1, b'\x00\x00'), ('version', 2, b'\x00\x00\x00\x00')]),
1853 make_inst(opname='POP_JUMP_IF_FALSE', arg=40, argval=212, argrepr='to L8', offset=128, start_offset=128, starts_line=False, line_number=11, cache_info=[('counter', 1, b'\x00\x00')]),
1854 make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=132, start_offset=132, starts_line=False, line_number=11),
1855 make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=134, start_offset=134, starts_line=True, line_number=12, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1856 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=144, start_offset=144, starts_line=False, line_number=12),
1857 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=146, start_offset=146, starts_line=False, line_number=12, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1858 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=154, start_offset=154, starts_line=False, line_number=12),
1859 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=156, start_offset=156, starts_line=True, line_number=13),
1860 make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=158, start_offset=158, starts_line=False, line_number=13),
1861 make_inst(opname='BINARY_OP', arg=23, argval=23, argrepr='-=', offset=160, start_offset=160, starts_line=False, line_number=13, cache_info=[('counter', 1, b'\x00\x00'), ('descr', 4, b'\x00\x00\x00\x00\x00\x00\x00\x00')]),
1862 make_inst(opname='STORE_FAST', arg=0, argval='i', argrepr='i', offset=172, start_offset=172, starts_line=False, line_number=13),
1863 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=174, start_offset=174, starts_line=True, line_number=14),
1864 make_inst(opname='LOAD_SMALL_INT', arg=6, argval=6, argrepr='', offset=176, start_offset=176, starts_line=False, line_number=14),
1865 make_inst(opname='COMPARE_OP', arg=148, argval='>', argrepr='bool(>)', offset=178, start_offset=178, starts_line=False, line_number=14, cache_info=[('counter', 1, b'\x00\x00')]),
1866 make_inst(opname='POP_JUMP_IF_FALSE', arg=3, argval=192, argrepr='to L6', offset=182, start_offset=182, starts_line=False, line_number=14, cache_info=[('counter', 1, b'\x00\x00')]),
1867 make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=186, start_offset=186, starts_line=False, line_number=14),
1868 make_inst(opname='JUMP_BACKWARD', arg=37, argval=118, argrepr='to L5', offset=188, start_offset=188, starts_line=True, line_number=15, cache_info=[('counter', 1, b'\x00\x00')]),
1869 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=192, start_offset=192, starts_line=True, line_number=16, label=6),
1870 make_inst(opname='LOAD_SMALL_INT', arg=4, argval=4, argrepr='', offset=194, start_offset=194, starts_line=False, line_number=16),
1871 make_inst(opname='COMPARE_OP', arg=18, argval='<', argrepr='bool(<)', offset=196, start_offset=196, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]),
1872 make_inst(opname='POP_JUMP_IF_TRUE', arg=3, argval=210, argrepr='to L7', offset=200, start_offset=200, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]),
1873 make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=204, start_offset=204, starts_line=False, line_number=16),
1874 make_inst(opname='JUMP_BACKWARD', arg=46, argval=118, argrepr='to L5', offset=206, start_offset=206, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]),
1875 make_inst(opname='JUMP_FORWARD', arg=11, argval=234, argrepr='to L9', offset=210, start_offset=210, starts_line=True, line_number=17, label=7),
1876 make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=212, start_offset=212, starts_line=True, line_number=19, label=8, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1877 make_inst(opname='LOAD_CONST', arg=2, argval='Who let lolcatz into this test suite?', argrepr="'Who let lolcatz into this test suite?'", offset=222, start_offset=222, starts_line=False, line_number=19),
1878 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=224, start_offset=224, starts_line=False, line_number=19, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1879 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=232, start_offset=232, starts_line=False, line_number=19),
1880 make_inst(opname='NOP', arg=None, argval=None, argrepr='', offset=234, start_offset=234, starts_line=True, line_number=20, label=9),
1881 make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=236, start_offset=236, starts_line=True, line_number=21),
1882 make_inst(opname='LOAD_SMALL_INT', arg=0, argval=0, argrepr='', offset=238, start_offset=238, starts_line=False, line_number=21),
1883 make_inst(opname='BINARY_OP', arg=11, argval=11, argrepr='/', offset=240, start_offset=240, starts_line=False, line_number=21, cache_info=[('counter', 1, b'\x00\x00'), ('descr', 4, b'\x00\x00\x00\x00\x00\x00\x00\x00')]),
1884 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=252, start_offset=252, starts_line=False, line_number=21),
1885 make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=254, start_offset=254, starts_line=True, line_number=25),
1886 make_inst(opname='COPY', arg=1, argval=1, argrepr='', offset=256, start_offset=256, starts_line=False, line_number=25),
1887 make_inst(opname='LOAD_SPECIAL', arg=1, argval=1, argrepr='__exit__', offset=258, start_offset=258, starts_line=False, line_number=25),
1888 make_inst(opname='SWAP', arg=2, argval=2, argrepr='', offset=260, start_offset=260, starts_line=False, line_number=25),
1889 make_inst(opname='SWAP', arg=3, argval=3, argrepr='', offset=262, start_offset=262, starts_line=False, line_number=25),
1890 make_inst(opname='LOAD_SPECIAL', arg=0, argval=0, argrepr='__enter__', offset=264, start_offset=264, starts_line=False, line_number=25),
1891 make_inst(opname='CALL', arg=0, argval=0, argrepr='', offset=266, start_offset=266, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1892 make_inst(opname='STORE_FAST', arg=1, argval='dodgy', argrepr='dodgy', offset=274, start_offset=274, starts_line=False, line_number=25),
1893 make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=276, start_offset=276, starts_line=True, line_number=26, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1894 make_inst(opname='LOAD_CONST', arg=3, argval='Never reach this', argrepr="'Never reach this'", offset=286, start_offset=286, starts_line=False, line_number=26),
1895 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=288, start_offset=288, starts_line=False, line_number=26, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1896 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=296, start_offset=296, starts_line=False, line_number=26),
1897 make_inst(opname='LOAD_CONST', arg=4, argval=None, argrepr='None', offset=298, start_offset=298, starts_line=True, line_number=25),
1898 make_inst(opname='LOAD_CONST', arg=4, argval=None, argrepr='None', offset=300, start_offset=300, starts_line=False, line_number=25),
1899 make_inst(opname='LOAD_CONST', arg=4, argval=None, argrepr='None', offset=302, start_offset=302, starts_line=False, line_number=25),
1900 make_inst(opname='CALL', arg=3, argval=3, argrepr='', offset=304, start_offset=304, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1901 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=312, start_offset=312, starts_line=False, line_number=25),
1902 make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=314, start_offset=314, starts_line=True, line_number=28, label=10, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1903 make_inst(opname='LOAD_CONST', arg=6, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=324, start_offset=324, starts_line=False, line_number=28),
1904 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=326, start_offset=326, starts_line=False, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1905 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=334, start_offset=334, starts_line=False, line_number=28),
1906 make_inst(opname='LOAD_CONST', arg=4, argval=None, argrepr='None', offset=336, start_offset=336, starts_line=False, line_number=28),
1907 make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=338, start_offset=338, starts_line=False, line_number=28),
1908 make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=340, start_offset=340, starts_line=True, line_number=25),
1909 make_inst(opname='WITH_EXCEPT_START', arg=None, argval=None, argrepr='', offset=342, start_offset=342, starts_line=False, line_number=25),
1910 make_inst(opname='TO_BOOL', arg=None, argval=None, argrepr='', offset=344, start_offset=344, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('version', 2, b'\x00\x00\x00\x00')]),
1911 make_inst(opname='POP_JUMP_IF_TRUE', arg=2, argval=360, argrepr='to L11', offset=352, start_offset=352, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00')]),
1912 make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=356, start_offset=356, starts_line=False, line_number=25),
1913 make_inst(opname='RERAISE', arg=2, argval=2, argrepr='', offset=358, start_offset=358, starts_line=False, line_number=25),
1914 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=360, start_offset=360, starts_line=False, line_number=25, label=11),
1915 make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=362, start_offset=362, starts_line=False, line_number=25),
1916 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=364, start_offset=364, starts_line=False, line_number=25),
1917 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=366, start_offset=366, starts_line=False, line_number=25),
1918 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=368, start_offset=368, starts_line=False, line_number=25),
1919 make_inst(opname='JUMP_BACKWARD_NO_INTERRUPT', arg=29, argval=314, argrepr='to L10', offset=370, start_offset=370, starts_line=False, line_number=25),
1920 make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=372, start_offset=372, starts_line=True, line_number=None),
1921 make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=374, start_offset=374, starts_line=False, line_number=None),
1922 make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=376, start_offset=376, starts_line=False, line_number=None),
1923 make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=378, start_offset=378, starts_line=False, line_number=None),
1924 make_inst(opname='LOAD_GLOBAL', arg=4, argval='ZeroDivisionError', argrepr='ZeroDivisionError', offset=380, start_offset=380, starts_line=True, line_number=22, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1925 make_inst(opname='CHECK_EXC_MATCH', arg=None, argval=None, argrepr='', offset=390, start_offset=390, starts_line=False, line_number=22),
1926 make_inst(opname='POP_JUMP_IF_FALSE', arg=15, argval=426, argrepr='to L12', offset=392, start_offset=392, starts_line=False, line_number=22, cache_info=[('counter', 1, b'\x00\x00')]),
1927 make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=396, start_offset=396, starts_line=False, line_number=22),
1928 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=398, start_offset=398, starts_line=False, line_number=22),
1929 make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=400, start_offset=400, starts_line=True, line_number=23, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1930 make_inst(opname='LOAD_CONST', arg=5, argval='Here we go, here we go, here we go...', argrepr="'Here we go, here we go, here we go...'", offset=410, start_offset=410, starts_line=False, line_number=23),
1931 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=412, start_offset=412, starts_line=False, line_number=23, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1932 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=420, start_offset=420, starts_line=False, line_number=23),
1933 make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=422, start_offset=422, starts_line=False, line_number=23),
1934 make_inst(opname='JUMP_BACKWARD_NO_INTERRUPT', arg=56, argval=314, argrepr='to L10', offset=424, start_offset=424, starts_line=False, line_number=23),
1935 make_inst(opname='RERAISE', arg=0, argval=0, argrepr='', offset=426, start_offset=426, starts_line=True, line_number=22, label=12),
1936 make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=428, start_offset=428, starts_line=True, line_number=None),
1937 make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=430, start_offset=430, starts_line=False, line_number=None),
1938 make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=432, start_offset=432, starts_line=False, line_number=None),
1939 make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=434, start_offset=434, starts_line=False, line_number=None),
1940 make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=436, start_offset=436, starts_line=True, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]),
1941 make_inst(opname='LOAD_CONST', arg=6, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=446, start_offset=446, starts_line=False, line_number=28),
1942 make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=448, start_offset=448, starts_line=False, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]),
1943 make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=456, start_offset=456, starts_line=False, line_number=28),
1944 make_inst(opname='RERAISE', arg=0, argval=0, argrepr='', offset=458, start_offset=458, starts_line=False, line_number=28),
1945 make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=460, start_offset=460, starts_line=True, line_number=None),
1946 make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=462, start_offset=462, starts_line=False, line_number=None),
1947 make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=464, start_offset=464, starts_line=False, line_number=None),
1948 ]
1949
1950 # One last piece of inspect fodder to check the default line number handling
1951 def simple(): pass
1952 expected_opinfo_simple = [
1953 make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=simple.__code__.co_firstlineno),
1954 make_inst(opname='LOAD_CONST', arg=0, argval=None, argrepr='None', offset=2, start_offset=2, starts_line=False, line_number=simple.__code__.co_firstlineno),
1955 make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=4, start_offset=4, starts_line=False, line_number=simple.__code__.co_firstlineno),
1956 ]
1957
1958
1959 class InstructionTestCase(BytecodeTestCase):
1960
1961 def assertInstructionsEqual(self, instrs_1, instrs_2, /):
1962 instrs_1 = [instr_1._replace(positions=None, cache_info=None) for instr_1 in instrs_1]
1963 instrs_2 = [instr_2._replace(positions=None, cache_info=None) for instr_2 in instrs_2]
1964 self.assertEqual(instrs_1, instrs_2)
1965
1966 class InstructionTests(InstructionTestCase):
1967
1968 def __init__(self, *args):
1969 super().__init__(*args)
1970 self.maxDiff = None
1971
1972 def test_instruction_str(self):
1973 # smoke test for __str__
1974 instrs = dis.get_instructions(simple)
1975 for instr in instrs:
1976 str(instr)
1977
1978 def test_default_first_line(self):
1979 actual = dis.get_instructions(simple)
1980 self.assertInstructionsEqual(list(actual), expected_opinfo_simple)
1981
1982 def test_first_line_set_to_None(self):
1983 actual = dis.get_instructions(simple, first_line=None)
1984 self.assertInstructionsEqual(list(actual), expected_opinfo_simple)
1985
1986 def test_outer(self):
1987 actual = dis.get_instructions(outer, first_line=expected_outer_line)
1988 self.assertInstructionsEqual(list(actual), expected_opinfo_outer)
1989
1990 def test_nested(self):
1991 with captured_stdout():
1992 f = outer()
1993 actual = dis.get_instructions(f, first_line=expected_f_line)
1994 self.assertInstructionsEqual(list(actual), expected_opinfo_f)
1995
1996 def test_doubly_nested(self):
1997 with captured_stdout():
1998 inner = outer()()
1999 actual = dis.get_instructions(inner, first_line=expected_inner_line)
2000 self.assertInstructionsEqual(list(actual), expected_opinfo_inner)
2001
2002 def test_jumpy(self):
2003 actual = dis.get_instructions(jumpy, first_line=expected_jumpy_line)
2004 self.assertInstructionsEqual(list(actual), expected_opinfo_jumpy)
2005
2006 @requires_debug_ranges()
2007 def test_co_positions(self):
2008 code = compile('f(\n x, y, z\n)', '<test>', 'exec')
2009 positions = [
2010 instr.positions
2011 for instr in dis.get_instructions(code)
2012 ]
2013 expected = [
2014 (0, 1, 0, 0),
2015 (1, 1, 0, 1),
2016 (1, 1, 0, 1),
2017 (2, 2, 2, 3),
2018 (2, 2, 5, 6),
2019 (2, 2, 8, 9),
2020 (1, 3, 0, 1),
2021 (1, 3, 0, 1),
2022 (1, 3, 0, 1),
2023 (1, 3, 0, 1)
2024 ]
2025 self.assertEqual(positions, expected)
2026
2027 named_positions = [
2028 (pos.lineno, pos.end_lineno, pos.col_offset, pos.end_col_offset)
2029 for pos in positions
2030 ]
2031 self.assertEqual(named_positions, expected)
2032
2033 @requires_debug_ranges()
2034 def test_co_positions_missing_info(self):
2035 code = compile('x, y, z', '<test>', 'exec')
2036 code_without_location_table = code.replace(co_linetable=b'')
2037 actual = dis.get_instructions(code_without_location_table)
2038 for instruction in actual:
2039 with self.subTest(instruction=instruction):
2040 positions = instruction.positions
2041 self.assertEqual(len(positions), 4)
2042 if instruction.opname == "RESUME":
2043 continue
2044 self.assertIsNone(positions.lineno)
2045 self.assertIsNone(positions.end_lineno)
2046 self.assertIsNone(positions.col_offset)
2047 self.assertIsNone(positions.end_col_offset)
2048
2049 @requires_debug_ranges()
2050 def test_co_positions_with_lots_of_caches(self):
2051 def roots(a, b, c):
2052 d = b**2 - 4 * a * c
2053 yield (-b - cmath.sqrt(d)) / (2 * a)
2054 if d:
2055 yield (-b + cmath.sqrt(d)) / (2 * a)
2056 code = roots.__code__
2057 ops = code.co_code[::2]
2058 cache_opcode = opcode.opmap["CACHE"]
2059 caches = sum(op == cache_opcode for op in ops)
2060 non_caches = len(ops) - caches
2061 # Make sure we have "lots of caches". If not, roots should be changed:
2062 assert 1 / 3 <= caches / non_caches, "this test needs more caches!"
2063 for show_caches in (False, True):
2064 for adaptive in (False, True):
2065 with self.subTest(f"{adaptive=}, {show_caches=}"):
2066 co_positions = [
2067 positions
2068 for op, positions in zip(ops, code.co_positions(), strict=True)
2069 if show_caches or op != cache_opcode
2070 ]
2071 dis_positions = [
2072 None if instruction.positions is None else (
2073 instruction.positions.lineno,
2074 instruction.positions.end_lineno,
2075 instruction.positions.col_offset,
2076 instruction.positions.end_col_offset,
2077 )
2078 for instruction in _unroll_caches_as_Instructions(dis.get_instructions(
2079 code, adaptive=adaptive, show_caches=show_caches
2080 ), show_caches=show_caches)
2081 ]
2082 self.assertEqual(co_positions, dis_positions)
2083
2084 def test_oparg_alias(self):
2085 instruction = make_inst(opname="NOP", arg=None, argval=None,
2086 argrepr='', offset=10, start_offset=10, starts_line=True, line_number=1, label=None,
2087 positions=None)
2088 self.assertEqual(instruction.arg, instruction.oparg)
2089
2090 def test_show_caches_with_label(self):
2091 def f(x, y, z):
2092 if x:
2093 res = y
2094 else:
2095 res = z
2096 return res
2097
2098 output = io.StringIO()
2099 dis.dis(f.__code__, file=output, show_caches=True)
2100 self.assertIn("L1:", output.getvalue())
2101
2102 def test_is_op_format(self):
2103 output = io.StringIO()
2104 dis.dis("a is b", file=output, show_caches=True)
2105 self.assertIn("IS_OP 0 (is)", output.getvalue())
2106
2107 output = io.StringIO()
2108 dis.dis("a is not b", file=output, show_caches=True)
2109 self.assertIn("IS_OP 1 (is not)", output.getvalue())
2110
2111 def test_contains_op_format(self):
2112 output = io.StringIO()
2113 dis.dis("a in b", file=output, show_caches=True)
2114 self.assertIn("CONTAINS_OP 0 (in)", output.getvalue())
2115
2116 output = io.StringIO()
2117 dis.dis("a not in b", file=output, show_caches=True)
2118 self.assertIn("CONTAINS_OP 1 (not in)", output.getvalue())
2119
2120 def test_baseopname_and_baseopcode(self):
2121 # Standard instructions
2122 for name in dis.opmap:
2123 instruction = make_inst(opname=name, arg=None, argval=None, argrepr='', offset=0,
2124 start_offset=0, starts_line=True, line_number=1, label=None, positions=None)
2125 baseopname = instruction.baseopname
2126 baseopcode = instruction.baseopcode
2127 self.assertIsNotNone(baseopname)
2128 self.assertIsNotNone(baseopcode)
2129 self.assertEqual(name, baseopname)
2130 self.assertEqual(instruction.opcode, baseopcode)
2131
2132 # Specialized instructions
2133 for name in opcode._specialized_opmap:
2134 instruction = make_inst(opname=name, arg=None, argval=None, argrepr='',
2135 offset=0, start_offset=0, starts_line=True, line_number=1, label=None, positions=None)
2136 baseopname = instruction.baseopname
2137 baseopcode = instruction.baseopcode
2138 self.assertIn(name, opcode._specializations[baseopname])
2139 self.assertEqual(opcode.opmap[baseopname], baseopcode)
2140
2141 def test_jump_target(self):
2142 # Non-jump instructions should return None
2143 instruction = make_inst(opname="NOP", arg=None, argval=None,
2144 argrepr='', offset=10, start_offset=10, starts_line=True, line_number=1, label=None,
2145 positions=None)
2146 self.assertIsNone(instruction.jump_target)
2147
2148 delta = 100
2149 instruction = make_inst(opname="JUMP_FORWARD", arg=delta, argval=delta,
2150 argrepr='', offset=10, start_offset=10, starts_line=True, line_number=1, label=None,
2151 positions=None)
2152 self.assertEqual(10 + 2 + 100*2, instruction.jump_target)
2153
2154 # Test negative deltas
2155 instruction = make_inst(opname="JUMP_BACKWARD", arg=delta, argval=delta,
2156 argrepr='', offset=200, start_offset=200, starts_line=True, line_number=1, label=None,
2157 positions=None)
2158 self.assertEqual(200 + 2 - 100*2 + 2*1, instruction.jump_target)
2159
2160 # Make sure cache entries are handled
2161 instruction = make_inst(opname="SEND", arg=delta, argval=delta,
2162 argrepr='', offset=10, start_offset=10, starts_line=True, line_number=1, label=None,
2163 positions=None)
2164 self.assertEqual(10 + 2 + 1*2 + 100*2, instruction.jump_target)
2165
2166 def test_argval_argrepr(self):
2167 def f(opcode, oparg, offset, *init_args):
2168 arg_resolver = dis.ArgResolver(*init_args)
2169 return arg_resolver.get_argval_argrepr(opcode, oparg, offset)
2170
2171 offset = 42
2172 co_consts = (0, 1, 2, 3)
2173 names = {1: 'a', 2: 'b'}
2174 varname_from_oparg = lambda i : names[i]
2175 labels_map = {24: 1}
2176 args = (offset, co_consts, names, varname_from_oparg, labels_map)
2177 self.assertEqual(f(opcode.opmap["POP_TOP"], None, *args), (None, ''))
2178 self.assertEqual(f(opcode.opmap["LOAD_CONST"], 1, *args), (1, '1'))
2179 self.assertEqual(f(opcode.opmap["LOAD_GLOBAL"], 2, *args), ('a', 'a'))
2180 self.assertEqual(f(opcode.opmap["JUMP_BACKWARD"], 11, *args), (24, 'to L1'))
2181 self.assertEqual(f(opcode.opmap["COMPARE_OP"], 3, *args), ('<', '<'))
2182 self.assertEqual(f(opcode.opmap["SET_FUNCTION_ATTRIBUTE"], 2, *args), (2, 'kwdefaults'))
2183 self.assertEqual(f(opcode.opmap["BINARY_OP"], 3, *args), (3, '<<'))
2184 self.assertEqual(f(opcode.opmap["CALL_INTRINSIC_1"], 2, *args), (2, 'INTRINSIC_IMPORT_STAR'))
2185
2186 def test_custom_arg_resolver(self):
2187 class MyArgResolver(dis.ArgResolver):
2188 def offset_from_jump_arg(self, op, arg, offset):
2189 return arg + 1
2190
2191 def get_label_for_offset(self, offset):
2192 return 2 * offset
2193
2194 def f(opcode, oparg, offset, *init_args):
2195 arg_resolver = MyArgResolver(*init_args)
2196 return arg_resolver.get_argval_argrepr(opcode, oparg, offset)
2197 offset = 42
2198 self.assertEqual(f(opcode.opmap["JUMP_BACKWARD"], 1, offset), (2, 'to L4'))
2199 self.assertEqual(f(opcode.opmap["SETUP_FINALLY"], 2, offset), (3, 'to L6'))
2200
2201
2202 def get_instructions(self, code):
2203 return dis._get_instructions_bytes(code)
2204
2205 def test_start_offset(self):
2206 # When no extended args are present,
2207 # start_offset should be equal to offset
2208
2209 instructions = list(dis.Bytecode(_f))
2210 for instruction in instructions:
2211 self.assertEqual(instruction.offset, instruction.start_offset)
2212
2213 def last_item(iterable):
2214 return functools.reduce(lambda a, b : b, iterable)
2215
2216 code = bytes([
2217 opcode.opmap["LOAD_FAST"], 0x00,
2218 opcode.opmap["EXTENDED_ARG"], 0x01,
2219 opcode.opmap["POP_JUMP_IF_TRUE"], 0xFF,
2220 ])
2221 labels_map = dis._make_labels_map(code)
2222 jump = last_item(self.get_instructions(code))
2223 self.assertEqual(4, jump.offset)
2224 self.assertEqual(2, jump.start_offset)
2225
2226 code = bytes([
2227 opcode.opmap["LOAD_FAST"], 0x00,
2228 opcode.opmap["EXTENDED_ARG"], 0x01,
2229 opcode.opmap["EXTENDED_ARG"], 0x01,
2230 opcode.opmap["EXTENDED_ARG"], 0x01,
2231 opcode.opmap["POP_JUMP_IF_TRUE"], 0xFF,
2232 opcode.opmap["CACHE"], 0x00,
2233 ])
2234 jump = last_item(self.get_instructions(code))
2235 self.assertEqual(8, jump.offset)
2236 self.assertEqual(2, jump.start_offset)
2237
2238 code = bytes([
2239 opcode.opmap["LOAD_FAST"], 0x00,
2240 opcode.opmap["EXTENDED_ARG"], 0x01,
2241 opcode.opmap["POP_JUMP_IF_TRUE"], 0xFF,
2242 opcode.opmap["CACHE"], 0x00,
2243 opcode.opmap["EXTENDED_ARG"], 0x01,
2244 opcode.opmap["EXTENDED_ARG"], 0x01,
2245 opcode.opmap["EXTENDED_ARG"], 0x01,
2246 opcode.opmap["POP_JUMP_IF_TRUE"], 0xFF,
2247 opcode.opmap["CACHE"], 0x00,
2248 ])
2249 instructions = list(self.get_instructions(code))
2250 # 1st jump
2251 self.assertEqual(4, instructions[2].offset)
2252 self.assertEqual(2, instructions[2].start_offset)
2253 # 2nd jump
2254 self.assertEqual(14, instructions[6].offset)
2255 self.assertEqual(8, instructions[6].start_offset)
2256
2257 def test_cache_offset_and_end_offset(self):
2258 code = bytes([
2259 opcode.opmap["LOAD_GLOBAL"], 0x01,
2260 opcode.opmap["CACHE"], 0x00,
2261 opcode.opmap["CACHE"], 0x00,
2262 opcode.opmap["CACHE"], 0x00,
2263 opcode.opmap["CACHE"], 0x00,
2264 opcode.opmap["LOAD_FAST"], 0x00,
2265 opcode.opmap["CALL"], 0x01,
2266 opcode.opmap["CACHE"], 0x00,
2267 opcode.opmap["CACHE"], 0x00,
2268 opcode.opmap["CACHE"], 0x00
2269 ])
2270 instructions = list(self.get_instructions(code))
2271 self.assertEqual(2, instructions[0].cache_offset)
2272 self.assertEqual(10, instructions[0].end_offset)
2273 self.assertEqual(12, instructions[1].cache_offset)
2274 self.assertEqual(12, instructions[1].end_offset)
2275 self.assertEqual(14, instructions[2].cache_offset)
2276 self.assertEqual(20, instructions[2].end_offset)
2277
2278 # end_offset of the previous instruction should be equal to the
2279 # start_offset of the following instruction
2280 instructions = list(dis.Bytecode(self.test_cache_offset_and_end_offset))
2281 for prev, curr in zip(instructions, instructions[1:]):
2282 self.assertEqual(prev.end_offset, curr.start_offset)
2283
2284
2285 # get_instructions has its own tests above, so can rely on it to validate
2286 # the object oriented API
2287 class BytecodeTests(InstructionTestCase, DisTestBase):
2288
2289 def test_instantiation(self):
2290 # Test with function, method, code string and code object
2291 for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
2292 with self.subTest(obj=obj):
2293 b = dis.Bytecode(obj)
2294 self.assertIsInstance(b.codeobj, types.CodeType)
2295
2296 self.assertRaises(TypeError, dis.Bytecode, object())
2297
2298 def test_iteration(self):
2299 for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
2300 with self.subTest(obj=obj):
2301 via_object = list(dis.Bytecode(obj))
2302 via_generator = list(dis.get_instructions(obj))
2303 self.assertInstructionsEqual(via_object, via_generator)
2304
2305 def test_explicit_first_line(self):
2306 actual = dis.Bytecode(outer, first_line=expected_outer_line)
2307 self.assertInstructionsEqual(list(actual), expected_opinfo_outer)
2308
2309 def test_source_line_in_disassembly(self):
2310 # Use the line in the source code
2311 actual = dis.Bytecode(simple).dis()
2312 actual = actual.strip().partition(" ")[0] # extract the line no
2313 expected = str(simple.__code__.co_firstlineno)
2314 self.assertEqual(actual, expected)
2315 # Use an explicit first line number
2316 actual = dis.Bytecode(simple, first_line=350).dis()
2317 actual = actual.strip().partition(" ")[0] # extract the line no
2318 self.assertEqual(actual, "350")
2319
2320 def test_info(self):
2321 self.maxDiff = 1000
2322 for x, expected in CodeInfoTests.test_pairs:
2323 b = dis.Bytecode(x)
2324 self.assertRegex(b.info(), expected)
2325
2326 def test_disassembled(self):
2327 actual = dis.Bytecode(_f).dis()
2328 self.do_disassembly_compare(actual, dis_f)
2329
2330 def test_from_traceback(self):
2331 tb = get_tb()
2332 b = dis.Bytecode.from_traceback(tb)
2333 while tb.tb_next: tb = tb.tb_next
2334
2335 self.assertEqual(b.current_offset, tb.tb_lasti)
2336
2337 def test_from_traceback_dis(self):
2338 self.maxDiff = None
2339 tb = get_tb()
2340 b = dis.Bytecode.from_traceback(tb)
2341 self.assertEqual(b.dis(), dis_traceback)
2342
2343 @requires_debug_ranges()
2344 def test_bytecode_co_positions(self):
2345 bytecode = dis.Bytecode("a=1")
2346 for instr, positions in zip(bytecode, bytecode.codeobj.co_positions()):
2347 assert instr.positions == positions
2348
2349 class TestBytecodeTestCase(BytecodeTestCase):
2350 def test_assert_not_in_with_op_not_in_bytecode(self):
2351 code = compile("a = 1", "<string>", "exec")
2352 self.assertInBytecode(code, "LOAD_SMALL_INT", 1)
2353 self.assertNotInBytecode(code, "LOAD_NAME")
2354 self.assertNotInBytecode(code, "LOAD_NAME", "a")
2355
2356 def test_assert_not_in_with_arg_not_in_bytecode(self):
2357 code = compile("a = 1", "<string>", "exec")
2358 self.assertInBytecode(code, "LOAD_SMALL_INT")
2359 self.assertInBytecode(code, "LOAD_SMALL_INT", 1)
2360 self.assertNotInBytecode(code, "LOAD_CONST", 2)
2361
2362 def test_assert_not_in_with_arg_in_bytecode(self):
2363 code = compile("a = 1", "<string>", "exec")
2364 with self.assertRaises(AssertionError):
2365 self.assertNotInBytecode(code, "LOAD_SMALL_INT", 1)
2366
2367 class TestFinderMethods(unittest.TestCase):
2368 def test__find_imports(self):
2369 cases = [
2370 ("import a.b.c", ('a.b.c', 0, None)),
2371 ("from a.b import c", ('a.b', 0, ('c',))),
2372 ("from a.b import c as d", ('a.b', 0, ('c',))),
2373 ("from a.b import *", ('a.b', 0, ('*',))),
2374 ("from ...a.b import c as d", ('a.b', 3, ('c',))),
2375 ("from ..a.b import c as d, e as f", ('a.b', 2, ('c', 'e'))),
2376 ("from ..a.b import *", ('a.b', 2, ('*',))),
2377 ]
2378 for src, expected in cases:
2379 with self.subTest(src=src):
2380 code = compile(src, "<string>", "exec")
2381 res = tuple(dis._find_imports(code))
2382 self.assertEqual(len(res), 1)
2383 self.assertEqual(res[0], expected)
2384
2385 def test__find_store_names(self):
2386 cases = [
2387 ("x+y", ()),
2388 ("x=y=1", ('x', 'y')),
2389 ("x+=y", ('x',)),
2390 ("global x\nx=y=1", ('x', 'y')),
2391 ("global x\nz=x", ('z',)),
2392 ]
2393 for src, expected in cases:
2394 with self.subTest(src=src):
2395 code = compile(src, "<string>", "exec")
2396 res = tuple(dis._find_store_names(code))
2397 self.assertEqual(res, expected)
2398
2399 def test_findlabels(self):
2400 labels = dis.findlabels(jumpy.__code__.co_code)
2401 jumps = [
2402 instr.offset
2403 for instr in expected_opinfo_jumpy
2404 if instr.is_jump_target
2405 ]
2406
2407 self.assertEqual(sorted(labels), sorted(jumps))
2408
2409 def test_findlinestarts(self):
2410 def func():
2411 pass
2412
2413 code = func.__code__
2414 offsets = [linestart[0] for linestart in dis.findlinestarts(code)]
2415 self.assertEqual(offsets, [0, 2])
2416
2417
2418 class TestDisTraceback(DisTestBase):
2419 def setUp(self) -> None:
2420 try: # We need to clean up existing tracebacks
2421 del sys.last_exc
2422 except AttributeError:
2423 pass
2424 try: # We need to clean up existing tracebacks
2425 del sys.last_traceback
2426 except AttributeError:
2427 pass
2428 return super().setUp()
2429
2430 def get_disassembly(self, tb):
2431 output = io.StringIO()
2432 with contextlib.redirect_stdout(output):
2433 dis.distb(tb)
2434 return output.getvalue()
2435
2436 def test_distb_empty(self):
2437 with self.assertRaises(RuntimeError):
2438 dis.distb()
2439
2440 def test_distb_last_traceback(self):
2441 self.maxDiff = None
2442 # We need to have an existing last traceback in `sys`:
2443 tb = get_tb()
2444 sys.last_traceback = tb
2445
2446 self.do_disassembly_compare(self.get_disassembly(None), dis_traceback)
2447
2448 def test_distb_explicit_arg(self):
2449 self.maxDiff = None
2450 tb = get_tb()
2451
2452 self.do_disassembly_compare(self.get_disassembly(tb), dis_traceback)
2453
2454
2455 class TestDisTracebackWithFile(TestDisTraceback):
2456 # Run the `distb` tests again, using the file arg instead of print
2457 def get_disassembly(self, tb):
2458 output = io.StringIO()
2459 with contextlib.redirect_stdout(output):
2460 dis.distb(tb, file=output)
2461 return output.getvalue()
2462
2463 def _unroll_caches_as_Instructions(instrs, show_caches=False):
2464 # Cache entries are no longer reported by dis as fake instructions,
2465 # but some tests assume that do. We should rewrite the tests to assume
2466 # the new API, but it will be clearer to keep the tests working as
2467 # before and do that in a separate PR.
2468
2469 for instr in instrs:
2470 yield instr
2471 if not show_caches:
2472 continue
2473
2474 offset = instr.offset
2475 for name, size, data in (instr.cache_info or ()):
2476 for i in range(size):
2477 offset += 2
2478 # Only show the fancy argrepr for a CACHE instruction when it's
2479 # the first entry for a particular cache value:
2480 if i == 0:
2481 argrepr = f"{name}: {int.from_bytes(data, sys.byteorder)}"
2482 else:
2483 argrepr = ""
2484
2485 yield make_inst("CACHE", 0, None, argrepr, offset, offset,
2486 False, None, None, instr.positions)
2487
2488
2489 class TestDisCLI(unittest.TestCase):
2490
2491 def setUp(self):
2492 self.filename = tempfile.mktemp()
2493 self.addCleanup(os_helper.unlink, self.filename)
2494
2495 @staticmethod
2496 def text_normalize(string):
2497 """Dedent *string* and strip it from its surrounding whitespaces.
2498
2499 This method is used by the other utility functions so that any
2500 string to write or to match against can be freely indented.
2501 """
2502 return textwrap.dedent(string).strip()
2503
2504 def set_source(self, content):
2505 with open(self.filename, 'w') as fp:
2506 fp.write(self.text_normalize(content))
2507
2508 def invoke_dis(self, *flags):
2509 output = io.StringIO()
2510 with contextlib.redirect_stdout(output):
2511 dis.main(args=[*flags, self.filename])
2512 return self.text_normalize(output.getvalue())
2513
2514 def check_output(self, source, expect, *flags):
2515 with self.subTest(source=source, flags=flags):
2516 self.set_source(source)
2517 res = self.invoke_dis(*flags)
2518 expect = self.text_normalize(expect)
2519 self.assertListEqual(res.splitlines(), expect.splitlines())
2520
2521 def test_invocation(self):
2522 # test various combinations of parameters
2523 base_flags = [
2524 ('-C', '--show-caches'),
2525 ('-O', '--show-offsets'),
2526 ('-P', '--show-positions'),
2527 ('-S', '--specialized'),
2528 ]
2529
2530 self.set_source('''
2531 def f():
2532 print(x)
2533 return None
2534 ''')
2535
2536 for r in range(1, len(base_flags) + 1):
2537 for choices in itertools.combinations(base_flags, r=r):
2538 for args in itertools.product(*choices):
2539 with self.subTest(args=args[1:]):
2540 _ = self.invoke_dis(*args)
2541
2542 with self.assertRaises(SystemExit):
2543 # suppress argparse error message
2544 with contextlib.redirect_stderr(io.StringIO()):
2545 _ = self.invoke_dis('--unknown')
2546
2547 def test_show_cache(self):
2548 # test 'python -m dis -C/--show-caches'
2549 source = 'print()'
2550 expect = '''
2551 0 RESUME 0
2552
2553 1 LOAD_NAME 0 (print)
2554 PUSH_NULL
2555 CALL 0
2556 CACHE 0 (counter: 0)
2557 CACHE 0 (func_version: 0)
2558 CACHE 0
2559 POP_TOP
2560 LOAD_CONST 0 (None)
2561 RETURN_VALUE
2562 '''
2563 for flag in ['-C', '--show-caches']:
2564 self.check_output(source, expect, flag)
2565
2566 def test_show_offsets(self):
2567 # test 'python -m dis -O/--show-offsets'
2568 source = 'pass'
2569 expect = '''
2570 0 0 RESUME 0
2571
2572 1 2 LOAD_CONST 0 (None)
2573 4 RETURN_VALUE
2574 '''
2575 for flag in ['-O', '--show-offsets']:
2576 self.check_output(source, expect, flag)
2577
2578 def test_show_positions(self):
2579 # test 'python -m dis -P/--show-positions'
2580 source = 'pass'
2581 expect = '''
2582 0:0-1:0 RESUME 0
2583
2584 1:0-1:4 LOAD_CONST 0 (None)
2585 1:0-1:4 RETURN_VALUE
2586 '''
2587 for flag in ['-P', '--show-positions']:
2588 self.check_output(source, expect, flag)
2589
2590 def test_specialized_code(self):
2591 # test 'python -m dis -S/--specialized'
2592 source = 'pass'
2593 expect = '''
2594 0 RESUME 0
2595
2596 1 LOAD_CONST 0 (None)
2597 RETURN_VALUE
2598 '''
2599 for flag in ['-S', '--specialized']:
2600 self.check_output(source, expect, flag)
2601
2602
2603 if __name__ == "__main__":
2604 unittest.main()