Blame Lib/dis.py

rpm-build 2bd099
"""Disassembler of Python byte code into mnemonics."""
rpm-build 2bd099
rpm-build 2bd099
import sys
rpm-build 2bd099
import types
rpm-build 2bd099
import collections
rpm-build 2bd099
import io
rpm-build 2bd099
rpm-build 2bd099
from opcode import *
rpm-build 2bd099
from opcode import __all__ as _opcodes_all
rpm-build 2bd099
rpm-build 2bd099
__all__ = ["code_info", "dis", "disassemble", "distb", "disco",
rpm-build 2bd099
           "findlinestarts", "findlabels", "show_code",
rpm-build 2bd099
           "get_instructions", "Instruction", "Bytecode"] + _opcodes_all
rpm-build 2bd099
del _opcodes_all
rpm-build 2bd099
rpm-build 2bd099
_have_code = (types.MethodType, types.FunctionType, types.CodeType,
rpm-build 2bd099
              classmethod, staticmethod, type)
rpm-build 2bd099
rpm-build 2bd099
FORMAT_VALUE = opmap['FORMAT_VALUE']
rpm-build 2bd099
rpm-build 2bd099
def _try_compile(source, name):
rpm-build 2bd099
    """Attempts to compile the given source, first as an expression and
rpm-build 2bd099
       then as a statement if the first approach fails.
rpm-build 2bd099
rpm-build 2bd099
       Utility function to accept strings in functions that otherwise
rpm-build 2bd099
       expect code objects
rpm-build 2bd099
    """
rpm-build 2bd099
    try:
rpm-build 2bd099
        c = compile(source, name, 'eval')
rpm-build 2bd099
    except SyntaxError:
rpm-build 2bd099
        c = compile(source, name, 'exec')
rpm-build 2bd099
    return c
rpm-build 2bd099
rpm-build 2bd099
def dis(x=None, *, file=None):
rpm-build 2bd099
    """Disassemble classes, methods, functions, generators, or code.
rpm-build 2bd099
rpm-build 2bd099
    With no argument, disassemble the last traceback.
rpm-build 2bd099
rpm-build 2bd099
    """
rpm-build 2bd099
    if x is None:
rpm-build 2bd099
        distb(file=file)
rpm-build 2bd099
        return
rpm-build 2bd099
    if hasattr(x, '__func__'):  # Method
rpm-build 2bd099
        x = x.__func__
rpm-build 2bd099
    if hasattr(x, '__code__'):  # Function
rpm-build 2bd099
        x = x.__code__
rpm-build 2bd099
    if hasattr(x, 'gi_code'):  # Generator
rpm-build 2bd099
        x = x.gi_code
rpm-build 2bd099
    if hasattr(x, '__dict__'):  # Class or module
rpm-build 2bd099
        items = sorted(x.__dict__.items())
rpm-build 2bd099
        for name, x1 in items:
rpm-build 2bd099
            if isinstance(x1, _have_code):
rpm-build 2bd099
                print("Disassembly of %s:" % name, file=file)
rpm-build 2bd099
                try:
rpm-build 2bd099
                    dis(x1, file=file)
rpm-build 2bd099
                except TypeError as msg:
rpm-build 2bd099
                    print("Sorry:", msg, file=file)
rpm-build 2bd099
                print(file=file)
rpm-build 2bd099
    elif hasattr(x, 'co_code'): # Code object
rpm-build 2bd099
        disassemble(x, file=file)
rpm-build 2bd099
    elif isinstance(x, (bytes, bytearray)): # Raw bytecode
rpm-build 2bd099
        _disassemble_bytes(x, file=file)
rpm-build 2bd099
    elif isinstance(x, str):    # Source code
rpm-build 2bd099
        _disassemble_str(x, file=file)
rpm-build 2bd099
    else:
rpm-build 2bd099
        raise TypeError("don't know how to disassemble %s objects" %
rpm-build 2bd099
                        type(x).__name__)
rpm-build 2bd099
rpm-build 2bd099
def distb(tb=None, *, file=None):
rpm-build 2bd099
    """Disassemble a traceback (default: last traceback)."""
rpm-build 2bd099
    if tb is None:
rpm-build 2bd099
        try:
rpm-build 2bd099
            tb = sys.last_traceback
rpm-build 2bd099
        except AttributeError:
rpm-build 2bd099
            raise RuntimeError("no last traceback to disassemble")
rpm-build 2bd099
        while tb.tb_next: tb = tb.tb_next
rpm-build 2bd099
    disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file)
rpm-build 2bd099
rpm-build 2bd099
# The inspect module interrogates this dictionary to build its
rpm-build 2bd099
# list of CO_* constants. It is also used by pretty_flags to
rpm-build 2bd099
# turn the co_flags field into a human readable list.
rpm-build 2bd099
COMPILER_FLAG_NAMES = {
rpm-build 2bd099
     1: "OPTIMIZED",
rpm-build 2bd099
     2: "NEWLOCALS",
rpm-build 2bd099
     4: "VARARGS",
rpm-build 2bd099
     8: "VARKEYWORDS",
rpm-build 2bd099
    16: "NESTED",
rpm-build 2bd099
    32: "GENERATOR",
rpm-build 2bd099
    64: "NOFREE",
rpm-build 2bd099
   128: "COROUTINE",
rpm-build 2bd099
   256: "ITERABLE_COROUTINE",
rpm-build 2bd099
   512: "ASYNC_GENERATOR",
rpm-build 2bd099
}
rpm-build 2bd099
rpm-build 2bd099
def pretty_flags(flags):
rpm-build 2bd099
    """Return pretty representation of code flags."""
rpm-build 2bd099
    names = []
rpm-build 2bd099
    for i in range(32):
rpm-build 2bd099
        flag = 1<
rpm-build 2bd099
        if flags & flag:
rpm-build 2bd099
            names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
rpm-build 2bd099
            flags ^= flag
rpm-build 2bd099
            if not flags:
rpm-build 2bd099
                break
rpm-build 2bd099
    else:
rpm-build 2bd099
        names.append(hex(flags))
rpm-build 2bd099
    return ", ".join(names)
rpm-build 2bd099
rpm-build 2bd099
def _get_code_object(x):
rpm-build 2bd099
    """Helper to handle methods, functions, generators, strings and raw code objects"""
rpm-build 2bd099
    if hasattr(x, '__func__'): # Method
rpm-build 2bd099
        x = x.__func__
rpm-build 2bd099
    if hasattr(x, '__code__'): # Function
rpm-build 2bd099
        x = x.__code__
rpm-build 2bd099
    if hasattr(x, 'gi_code'):  # Generator
rpm-build 2bd099
        x = x.gi_code
rpm-build 2bd099
    if isinstance(x, str):     # Source code
rpm-build 2bd099
        x = _try_compile(x, "<disassembly>")
rpm-build 2bd099
    if hasattr(x, 'co_code'):  # Code object
rpm-build 2bd099
        return x
rpm-build 2bd099
    raise TypeError("don't know how to disassemble %s objects" %
rpm-build 2bd099
                    type(x).__name__)
rpm-build 2bd099
rpm-build 2bd099
def code_info(x):
rpm-build 2bd099
    """Formatted details of methods, functions, or code."""
rpm-build 2bd099
    return _format_code_info(_get_code_object(x))
rpm-build 2bd099
rpm-build 2bd099
def _format_code_info(co):
rpm-build 2bd099
    lines = []
rpm-build 2bd099
    lines.append("Name:              %s" % co.co_name)
rpm-build 2bd099
    lines.append("Filename:          %s" % co.co_filename)
rpm-build 2bd099
    lines.append("Argument count:    %s" % co.co_argcount)
rpm-build 2bd099
    lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
rpm-build 2bd099
    lines.append("Number of locals:  %s" % co.co_nlocals)
rpm-build 2bd099
    lines.append("Stack size:        %s" % co.co_stacksize)
rpm-build 2bd099
    lines.append("Flags:             %s" % pretty_flags(co.co_flags))
rpm-build 2bd099
    if co.co_consts:
rpm-build 2bd099
        lines.append("Constants:")
rpm-build 2bd099
        for i_c in enumerate(co.co_consts):
rpm-build 2bd099
            lines.append("%4d: %r" % i_c)
rpm-build 2bd099
    if co.co_names:
rpm-build 2bd099
        lines.append("Names:")
rpm-build 2bd099
        for i_n in enumerate(co.co_names):
rpm-build 2bd099
            lines.append("%4d: %s" % i_n)
rpm-build 2bd099
    if co.co_varnames:
rpm-build 2bd099
        lines.append("Variable names:")
rpm-build 2bd099
        for i_n in enumerate(co.co_varnames):
rpm-build 2bd099
            lines.append("%4d: %s" % i_n)
rpm-build 2bd099
    if co.co_freevars:
rpm-build 2bd099
        lines.append("Free variables:")
rpm-build 2bd099
        for i_n in enumerate(co.co_freevars):
rpm-build 2bd099
            lines.append("%4d: %s" % i_n)
rpm-build 2bd099
    if co.co_cellvars:
rpm-build 2bd099
        lines.append("Cell variables:")
rpm-build 2bd099
        for i_n in enumerate(co.co_cellvars):
rpm-build 2bd099
            lines.append("%4d: %s" % i_n)
rpm-build 2bd099
    return "\n".join(lines)
rpm-build 2bd099
rpm-build 2bd099
def show_code(co, *, file=None):
rpm-build 2bd099
    """Print details of methods, functions, or code to *file*.
rpm-build 2bd099
rpm-build 2bd099
    If *file* is not provided, the output is printed on stdout.
rpm-build 2bd099
    """
rpm-build 2bd099
    print(code_info(co), file=file)
rpm-build 2bd099
rpm-build 2bd099
_Instruction = collections.namedtuple("_Instruction",
rpm-build 2bd099
     "opname opcode arg argval argrepr offset starts_line is_jump_target")
rpm-build 2bd099
rpm-build 2bd099
_Instruction.opname.__doc__ = "Human readable name for operation"
rpm-build 2bd099
_Instruction.opcode.__doc__ = "Numeric code for operation"
rpm-build 2bd099
_Instruction.arg.__doc__ = "Numeric argument to operation (if any), otherwise None"
rpm-build 2bd099
_Instruction.argval.__doc__ = "Resolved arg value (if known), otherwise same as arg"
rpm-build 2bd099
_Instruction.argrepr.__doc__ = "Human readable description of operation argument"
rpm-build 2bd099
_Instruction.offset.__doc__ = "Start index of operation within bytecode sequence"
rpm-build 2bd099
_Instruction.starts_line.__doc__ = "Line started by this opcode (if any), otherwise None"
rpm-build 2bd099
_Instruction.is_jump_target.__doc__ = "True if other code jumps to here, otherwise False"
rpm-build 2bd099
rpm-build 2bd099
class Instruction(_Instruction):
rpm-build 2bd099
    """Details for a bytecode operation
rpm-build 2bd099
rpm-build 2bd099
       Defined fields:
rpm-build 2bd099
         opname - human readable name for operation
rpm-build 2bd099
         opcode - numeric code for operation
rpm-build 2bd099
         arg - numeric argument to operation (if any), otherwise None
rpm-build 2bd099
         argval - resolved arg value (if known), otherwise same as arg
rpm-build 2bd099
         argrepr - human readable description of operation argument
rpm-build 2bd099
         offset - start index of operation within bytecode sequence
rpm-build 2bd099
         starts_line - line started by this opcode (if any), otherwise None
rpm-build 2bd099
         is_jump_target - True if other code jumps to here, otherwise False
rpm-build 2bd099
    """
rpm-build 2bd099
rpm-build 2bd099
    def _disassemble(self, lineno_width=3, mark_as_current=False):
rpm-build 2bd099
        """Format instruction details for inclusion in disassembly output
rpm-build 2bd099
rpm-build 2bd099
        *lineno_width* sets the width of the line number field (0 omits it)
rpm-build 2bd099
        *mark_as_current* inserts a '-->' marker arrow as part of the line
rpm-build 2bd099
        """
rpm-build 2bd099
        fields = []
rpm-build 2bd099
        # Column: Source code line number
rpm-build 2bd099
        if lineno_width:
rpm-build 2bd099
            if self.starts_line is not None:
rpm-build 2bd099
                lineno_fmt = "%%%dd" % lineno_width
rpm-build 2bd099
                fields.append(lineno_fmt % self.starts_line)
rpm-build 2bd099
            else:
rpm-build 2bd099
                fields.append(' ' * lineno_width)
rpm-build 2bd099
        # Column: Current instruction indicator
rpm-build 2bd099
        if mark_as_current:
rpm-build 2bd099
            fields.append('-->')
rpm-build 2bd099
        else:
rpm-build 2bd099
            fields.append('   ')
rpm-build 2bd099
        # Column: Jump target marker
rpm-build 2bd099
        if self.is_jump_target:
rpm-build 2bd099
            fields.append('>>')
rpm-build 2bd099
        else:
rpm-build 2bd099
            fields.append('  ')
rpm-build 2bd099
        # Column: Instruction offset from start of code sequence
rpm-build 2bd099
        fields.append(repr(self.offset).rjust(4))
rpm-build 2bd099
        # Column: Opcode name
rpm-build 2bd099
        fields.append(self.opname.ljust(20))
rpm-build 2bd099
        # Column: Opcode argument
rpm-build 2bd099
        if self.arg is not None:
rpm-build 2bd099
            fields.append(repr(self.arg).rjust(5))
rpm-build 2bd099
            # Column: Opcode argument details
rpm-build 2bd099
            if self.argrepr:
rpm-build 2bd099
                fields.append('(' + self.argrepr + ')')
rpm-build 2bd099
        return ' '.join(fields).rstrip()
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
def get_instructions(x, *, first_line=None):
rpm-build 2bd099
    """Iterator for the opcodes in methods, functions or code
rpm-build 2bd099
rpm-build 2bd099
    Generates a series of Instruction named tuples giving the details of
rpm-build 2bd099
    each operations in the supplied code.
rpm-build 2bd099
rpm-build 2bd099
    If *first_line* is not None, it indicates the line number that should
rpm-build 2bd099
    be reported for the first source line in the disassembled code.
rpm-build 2bd099
    Otherwise, the source line information (if any) is taken directly from
rpm-build 2bd099
    the disassembled code object.
rpm-build 2bd099
    """
rpm-build 2bd099
    co = _get_code_object(x)
rpm-build 2bd099
    cell_names = co.co_cellvars + co.co_freevars
rpm-build 2bd099
    linestarts = dict(findlinestarts(co))
rpm-build 2bd099
    if first_line is not None:
rpm-build 2bd099
        line_offset = first_line - co.co_firstlineno
rpm-build 2bd099
    else:
rpm-build 2bd099
        line_offset = 0
rpm-build 2bd099
    return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names,
rpm-build 2bd099
                                   co.co_consts, cell_names, linestarts,
rpm-build 2bd099
                                   line_offset)
rpm-build 2bd099
rpm-build 2bd099
def _get_const_info(const_index, const_list):
rpm-build 2bd099
    """Helper to get optional details about const references
rpm-build 2bd099
rpm-build 2bd099
       Returns the dereferenced constant and its repr if the constant
rpm-build 2bd099
       list is defined.
rpm-build 2bd099
       Otherwise returns the constant index and its repr().
rpm-build 2bd099
    """
rpm-build 2bd099
    argval = const_index
rpm-build 2bd099
    if const_list is not None:
rpm-build 2bd099
        argval = const_list[const_index]
rpm-build 2bd099
    return argval, repr(argval)
rpm-build 2bd099
rpm-build 2bd099
def _get_name_info(name_index, name_list):
rpm-build 2bd099
    """Helper to get optional details about named references
rpm-build 2bd099
rpm-build 2bd099
       Returns the dereferenced name as both value and repr if the name
rpm-build 2bd099
       list is defined.
rpm-build 2bd099
       Otherwise returns the name index and its repr().
rpm-build 2bd099
    """
rpm-build 2bd099
    argval = name_index
rpm-build 2bd099
    if name_list is not None:
rpm-build 2bd099
        argval = name_list[name_index]
rpm-build 2bd099
        argrepr = argval
rpm-build 2bd099
    else:
rpm-build 2bd099
        argrepr = repr(argval)
rpm-build 2bd099
    return argval, argrepr
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
rpm-build 2bd099
                      cells=None, linestarts=None, line_offset=0):
rpm-build 2bd099
    """Iterate over the instructions in a bytecode string.
rpm-build 2bd099
rpm-build 2bd099
    Generates a sequence of Instruction namedtuples giving the details of each
rpm-build 2bd099
    opcode.  Additional information about the code's runtime environment
rpm-build 2bd099
    (e.g. variable names, constants) can be specified using optional
rpm-build 2bd099
    arguments.
rpm-build 2bd099
rpm-build 2bd099
    """
rpm-build 2bd099
    labels = findlabels(code)
rpm-build 2bd099
    starts_line = None
rpm-build 2bd099
    for offset, op, arg in _unpack_opargs(code):
rpm-build 2bd099
        if linestarts is not None:
rpm-build 2bd099
            starts_line = linestarts.get(offset, None)
rpm-build 2bd099
            if starts_line is not None:
rpm-build 2bd099
                starts_line += line_offset
rpm-build 2bd099
        is_jump_target = offset in labels
rpm-build 2bd099
        argval = None
rpm-build 2bd099
        argrepr = ''
rpm-build 2bd099
        if arg is not None:
rpm-build 2bd099
            #  Set argval to the dereferenced value of the argument when
rpm-build 2bd099
            #  available, and argrepr to the string representation of argval.
rpm-build 2bd099
            #    _disassemble_bytes needs the string repr of the
rpm-build 2bd099
            #    raw name index for LOAD_GLOBAL, LOAD_CONST, etc.
rpm-build 2bd099
            argval = arg
rpm-build 2bd099
            if op in hasconst:
rpm-build 2bd099
                argval, argrepr = _get_const_info(arg, constants)
rpm-build 2bd099
            elif op in hasname:
rpm-build 2bd099
                argval, argrepr = _get_name_info(arg, names)
rpm-build 2bd099
            elif op in hasjrel:
rpm-build 2bd099
                argval = offset + 2 + arg
rpm-build 2bd099
                argrepr = "to " + repr(argval)
rpm-build 2bd099
            elif op in haslocal:
rpm-build 2bd099
                argval, argrepr = _get_name_info(arg, varnames)
rpm-build 2bd099
            elif op in hascompare:
rpm-build 2bd099
                argval = cmp_op[arg]
rpm-build 2bd099
                argrepr = argval
rpm-build 2bd099
            elif op in hasfree:
rpm-build 2bd099
                argval, argrepr = _get_name_info(arg, cells)
rpm-build 2bd099
            elif op == FORMAT_VALUE:
rpm-build 2bd099
                argval = ((None, str, repr, ascii)[arg & 0x3], bool(arg & 0x4))
rpm-build 2bd099
                argrepr = ('', 'str', 'repr', 'ascii')[arg & 0x3]
rpm-build 2bd099
                if argval[1]:
rpm-build 2bd099
                    if argrepr:
rpm-build 2bd099
                        argrepr += ', '
rpm-build 2bd099
                    argrepr += 'with format'
rpm-build 2bd099
        yield Instruction(opname[op], op,
rpm-build 2bd099
                          arg, argval, argrepr,
rpm-build 2bd099
                          offset, starts_line, is_jump_target)
rpm-build 2bd099
rpm-build 2bd099
def disassemble(co, lasti=-1, *, file=None):
rpm-build 2bd099
    """Disassemble a code object."""
rpm-build 2bd099
    cell_names = co.co_cellvars + co.co_freevars
rpm-build 2bd099
    linestarts = dict(findlinestarts(co))
rpm-build 2bd099
    _disassemble_bytes(co.co_code, lasti, co.co_varnames, co.co_names,
rpm-build 2bd099
                       co.co_consts, cell_names, linestarts, file=file)
rpm-build 2bd099
rpm-build 2bd099
def _disassemble_bytes(code, lasti=-1, varnames=None, names=None,
rpm-build 2bd099
                       constants=None, cells=None, linestarts=None,
rpm-build 2bd099
                       *, file=None, line_offset=0):
rpm-build 2bd099
    # Omit the line number column entirely if we have no line number info
rpm-build 2bd099
    show_lineno = linestarts is not None
rpm-build 2bd099
    # TODO?: Adjust width upwards if max(linestarts.values()) >= 1000?
rpm-build 2bd099
    lineno_width = 3 if show_lineno else 0
rpm-build 2bd099
    for instr in _get_instructions_bytes(code, varnames, names,
rpm-build 2bd099
                                         constants, cells, linestarts,
rpm-build 2bd099
                                         line_offset=line_offset):
rpm-build 2bd099
        new_source_line = (show_lineno and
rpm-build 2bd099
                           instr.starts_line is not None and
rpm-build 2bd099
                           instr.offset > 0)
rpm-build 2bd099
        if new_source_line:
rpm-build 2bd099
            print(file=file)
rpm-build 2bd099
        is_current_instr = instr.offset == lasti
rpm-build 2bd099
        print(instr._disassemble(lineno_width, is_current_instr), file=file)
rpm-build 2bd099
rpm-build 2bd099
def _disassemble_str(source, *, file=None):
rpm-build 2bd099
    """Compile the source string, then disassemble the code object."""
rpm-build 2bd099
    disassemble(_try_compile(source, '<dis>'), file=file)
rpm-build 2bd099
rpm-build 2bd099
disco = disassemble                     # XXX For backwards compatibility
rpm-build 2bd099
rpm-build 2bd099
def _unpack_opargs(code):
rpm-build 2bd099
    extended_arg = 0
rpm-build 2bd099
    for i in range(0, len(code), 2):
rpm-build 2bd099
        op = code[i]
rpm-build 2bd099
        if op >= HAVE_ARGUMENT:
rpm-build 2bd099
            arg = code[i+1] | extended_arg
rpm-build 2bd099
            extended_arg = (arg << 8) if op == EXTENDED_ARG else 0
rpm-build 2bd099
        else:
rpm-build 2bd099
            arg = None
rpm-build 2bd099
        yield (i, op, arg)
rpm-build 2bd099
rpm-build 2bd099
def findlabels(code):
rpm-build 2bd099
    """Detect all offsets in a byte code which are jump targets.
rpm-build 2bd099
rpm-build 2bd099
    Return the list of offsets.
rpm-build 2bd099
rpm-build 2bd099
    """
rpm-build 2bd099
    labels = []
rpm-build 2bd099
    for offset, op, arg in _unpack_opargs(code):
rpm-build 2bd099
        if arg is not None:
rpm-build 2bd099
            if op in hasjrel:
rpm-build 2bd099
                label = offset + 2 + arg
rpm-build 2bd099
            elif op in hasjabs:
rpm-build 2bd099
                label = arg
rpm-build 2bd099
            else:
rpm-build 2bd099
                continue
rpm-build 2bd099
            if label not in labels:
rpm-build 2bd099
                labels.append(label)
rpm-build 2bd099
    return labels
rpm-build 2bd099
rpm-build 2bd099
def findlinestarts(code):
rpm-build 2bd099
    """Find the offsets in a byte code which are start of lines in the source.
rpm-build 2bd099
rpm-build 2bd099
    Generate pairs (offset, lineno) as described in Python/compile.c.
rpm-build 2bd099
rpm-build 2bd099
    """
rpm-build 2bd099
    byte_increments = code.co_lnotab[0::2]
rpm-build 2bd099
    line_increments = code.co_lnotab[1::2]
rpm-build 2bd099
rpm-build 2bd099
    lastlineno = None
rpm-build 2bd099
    lineno = code.co_firstlineno
rpm-build 2bd099
    addr = 0
rpm-build 2bd099
    for byte_incr, line_incr in zip(byte_increments, line_increments):
rpm-build 2bd099
        if byte_incr:
rpm-build 2bd099
            if lineno != lastlineno:
rpm-build 2bd099
                yield (addr, lineno)
rpm-build 2bd099
                lastlineno = lineno
rpm-build 2bd099
            addr += byte_incr
rpm-build 2bd099
        if line_incr >= 0x80:
rpm-build 2bd099
            # line_increments is an array of 8-bit signed integers
rpm-build 2bd099
            line_incr -= 0x100
rpm-build 2bd099
        lineno += line_incr
rpm-build 2bd099
    if lineno != lastlineno:
rpm-build 2bd099
        yield (addr, lineno)
rpm-build 2bd099
rpm-build 2bd099
class Bytecode:
rpm-build 2bd099
    """The bytecode operations of a piece of code
rpm-build 2bd099
rpm-build 2bd099
    Instantiate this with a function, method, string of code, or a code object
rpm-build 2bd099
    (as returned by compile()).
rpm-build 2bd099
rpm-build 2bd099
    Iterating over this yields the bytecode operations as Instruction instances.
rpm-build 2bd099
    """
rpm-build 2bd099
    def __init__(self, x, *, first_line=None, current_offset=None):
rpm-build 2bd099
        self.codeobj = co = _get_code_object(x)
rpm-build 2bd099
        if first_line is None:
rpm-build 2bd099
            self.first_line = co.co_firstlineno
rpm-build 2bd099
            self._line_offset = 0
rpm-build 2bd099
        else:
rpm-build 2bd099
            self.first_line = first_line
rpm-build 2bd099
            self._line_offset = first_line - co.co_firstlineno
rpm-build 2bd099
        self._cell_names = co.co_cellvars + co.co_freevars
rpm-build 2bd099
        self._linestarts = dict(findlinestarts(co))
rpm-build 2bd099
        self._original_object = x
rpm-build 2bd099
        self.current_offset = current_offset
rpm-build 2bd099
rpm-build 2bd099
    def __iter__(self):
rpm-build 2bd099
        co = self.codeobj
rpm-build 2bd099
        return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names,
rpm-build 2bd099
                                       co.co_consts, self._cell_names,
rpm-build 2bd099
                                       self._linestarts,
rpm-build 2bd099
                                       line_offset=self._line_offset)
rpm-build 2bd099
rpm-build 2bd099
    def __repr__(self):
rpm-build 2bd099
        return "{}({!r})".format(self.__class__.__name__,
rpm-build 2bd099
                                 self._original_object)
rpm-build 2bd099
rpm-build 2bd099
    @classmethod
rpm-build 2bd099
    def from_traceback(cls, tb):
rpm-build 2bd099
        """ Construct a Bytecode from the given traceback """
rpm-build 2bd099
        while tb.tb_next:
rpm-build 2bd099
            tb = tb.tb_next
rpm-build 2bd099
        return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)
rpm-build 2bd099
rpm-build 2bd099
    def info(self):
rpm-build 2bd099
        """Return formatted information about the code object."""
rpm-build 2bd099
        return _format_code_info(self.codeobj)
rpm-build 2bd099
rpm-build 2bd099
    def dis(self):
rpm-build 2bd099
        """Return a formatted view of the bytecode operations."""
rpm-build 2bd099
        co = self.codeobj
rpm-build 2bd099
        if self.current_offset is not None:
rpm-build 2bd099
            offset = self.current_offset
rpm-build 2bd099
        else:
rpm-build 2bd099
            offset = -1
rpm-build 2bd099
        with io.StringIO() as output:
rpm-build 2bd099
            _disassemble_bytes(co.co_code, varnames=co.co_varnames,
rpm-build 2bd099
                               names=co.co_names, constants=co.co_consts,
rpm-build 2bd099
                               cells=self._cell_names,
rpm-build 2bd099
                               linestarts=self._linestarts,
rpm-build 2bd099
                               line_offset=self._line_offset,
rpm-build 2bd099
                               file=output,
rpm-build 2bd099
                               lasti=offset)
rpm-build 2bd099
            return output.getvalue()
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
def _test():
rpm-build 2bd099
    """Simple test program to disassemble a file."""
rpm-build 2bd099
    import argparse
rpm-build 2bd099
rpm-build 2bd099
    parser = argparse.ArgumentParser()
rpm-build 2bd099
    parser.add_argument('infile', type=argparse.FileType(), nargs='?', default='-')
rpm-build 2bd099
    args = parser.parse_args()
rpm-build 2bd099
    with args.infile as infile:
rpm-build 2bd099
        source = infile.read()
rpm-build 2bd099
    code = compile(source, args.infile.name, "exec")
rpm-build 2bd099
    dis(code)
rpm-build 2bd099
rpm-build 2bd099
if __name__ == "__main__":
rpm-build 2bd099
    _test()