summaryrefslogtreecommitdiff
path: root/python/helpers/coverage/bytecode.py
blob: ab522d6c1c6cd22eb55d53bfff3ec10843400e79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""Bytecode manipulation for coverage.py"""

import opcode, sys, types

class ByteCode(object):
    """A single bytecode."""
    def __init__(self):
        self.offset = -1
        self.op = -1
        self.arg = -1
        self.next_offset = -1
        self.jump_to = -1


class ByteCodes(object):
    """Iterator over byte codes in `code`.

    Returns `ByteCode` objects.

    """
    def __init__(self, code):
        self.code = code
        self.offset = 0

    if sys.version_info >= (3, 0):
        def __getitem__(self, i):
            return self.code[i]
    else:
        def __getitem__(self, i):
            return ord(self.code[i])

    def __iter__(self):
        return self

    def __next__(self):
        if self.offset >= len(self.code):
            raise StopIteration

        bc = ByteCode()
        bc.op = self[self.offset]
        bc.offset = self.offset

        next_offset = self.offset+1
        if bc.op >= opcode.HAVE_ARGUMENT:
            bc.arg = self[self.offset+1] + 256*self[self.offset+2]
            next_offset += 2

            label = -1
            if bc.op in opcode.hasjrel:
                label = next_offset + bc.arg
            elif bc.op in opcode.hasjabs:
                label = bc.arg
            bc.jump_to = label

        bc.next_offset = self.offset = next_offset
        return bc

    next = __next__     # Py2k uses an old-style non-dunder name.


class CodeObjects(object):
    """Iterate over all the code objects in `code`."""
    def __init__(self, code):
        self.stack = [code]

    def __iter__(self):
        return self

    def __next__(self):
        if self.stack:
            # We're going to return the code object on the stack, but first
            # push its children for later returning.
            code = self.stack.pop()
            for c in code.co_consts:
                if isinstance(c, types.CodeType):
                    self.stack.append(c)
            return code

        raise StopIteration

    next = __next__