codewalk.py (was RE: PEP 329 and bytecode hacking)

Robert Brewer fumanchu at amor.org
Fri Apr 23 15:27:12 EDT 2004


New, vastly improved version 0.3 at:
http://www.aminus.org/rbre/python/index.html which includes:

Visitor
Rewriter
JumpCodeAdjuster
Localizer (like Raymond's)
EarlyBinder
LambdaDecompiler


Phillip J. Eby wrote:
> For more sophisticated bytecode modifications, you'll want to 
> keep track of things like source line number, the nth
> instruction and its operand if any (so you can scan
> *backwards*), the list of locations of a given opcode, etc.

I don't mind the function-call overhead, really, and much prefer to
stick with the visitor style. The biggest change in the new version is
that the original bytecode is left unchanged--a copy is built and
mutated instead, so line numbers, etc. are still available as one
rewrites. You can also call walk() multiple times now and get the same
result.

You could subclass codewalk.Visitor to get a list of locations with
something like:

class Locator(codewalk.Visitor):
    def locations(self, *opcodes):
        # Allow named or numbered instructions.
        opcodes = codewalk.numeric_opcodes(opcodes)
        
        self.watch = dict([(key, []) for key in opcodes])
        self.walk()
        return self.watch
    
    def visit_instruction(self, op, lo=None, hi=None):
        if op in self.watch:
            self.watch[op].append(self.cursor)


print Locator(func).locations(100, 'LOAD_DEREF', 124)


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list