bytecode icon indicating copy to clipboard operation
bytecode copied to clipboard

Add ConcreteBytecode.{instr_at_code_offset, index_at_code_offset}

Open eric-wieser opened this issue 7 years ago • 5 comments

As discussed in #9.

Suggestions welcome for better method names

eric-wieser avatar Nov 25 '16 10:11 eric-wieser

Re: naming:

  • index_at_code_offset(offset)?
  • get_instr_index(offset)
  • index(value=None, code_offset=None), which overloads collections.Sequence.index

eric-wieser avatar Nov 25 '16 10:11 eric-wieser

Hum, I expect new user requests in the future for new methods using byte offset rather than index in the list of instructions.

I suggest to experiment a different design: add a method to get a read-only view of a ConcreteBytecode object which only works with offset. Something like:

view = code.offset_view()  # concrete bytecode using Python 3.6 wordcode
second_instr = view[2]  # get the ConcreteInstr at offset 2
for instr in view[10:]: print(instr)  # get instructions since the offset 10

Your frame.f_lasti usecase becomes obvious with such view.

It's a view, so the view is modified if the code is modified.

vstinner avatar Nov 25 '16 13:11 vstinner

That's a neat idea. How would offset_view() work with SetLineno though?

Also, without directly exposing the index, I'm still stuck trying to index a Bytecode object based on the offset in the code it was loaded from (#9)

I should probably point out that issue I'm trying to workaround is that the following can fail due to absolute jump targets:

  • Bytecode.from_code(code[i_raw:])
  • ConcreteBytecode.from_code(code)[i_concrete:].to_bytecode()

So the abstraction needs to happen before the slicing, Bytecode.from_code(code)[i_abstracted:]

eric-wieser avatar Nov 25 '16 13:11 eric-wieser

Sorry, but I still don't understand your use case :-( And I think that it's important to understand it to design the "right" API.

Can you give an example of the final expected output? Do you want to display bytecode as text? Abstract or concrete bytecode?

vstinner avatar Nov 25 '16 14:11 vstinner

I want to obtain abstract bytecode corresponding to the code executed between two frame.f_lastis (if possible - obviously if there are jumps leaving this segment, then erroring is fine)

eric-wieser avatar Nov 25 '16 14:11 eric-wieser