[PEAK] Using BytecodeAssembler

Phillip J. Eby pje at telecommunity.com
Mon Feb 18 19:38:17 EST 2008


At 06:24 PM 2/18/2008 -0600, Aaron Lebo wrote:
>Man, you sure have created some great libraries PJE. I am thoroughly 
>enjoying using them.
>
>I've been using BytecodeAssembler lately. I'm finding the manual is 
>pretty solid but I am unclear on how to do a few things.
>1. Say I am implementing an interpreter. Am I going to want to have 
>a single peak.util.assembler.Code instance for an entire file and 
>continue to add to it, or should there be multiple ones?

That's up to you.  Note that each function will require its own Code.


>Also how does Suite play into this?

Suite is just a way of concatenating AST nodes together into a single 
node.  It has no other purpose.


>2. What steps do I need to take to create a .pyc file out of a 
>collection of bytecodes?

See the stdlib "py_compile" module, specifically its "compile()" 
function, for an example, replacing the call to __builtin__.compile() 
with your own bytecode generation.


>3. How are individual Python literals represented by bytecode? I 
>tried c = Code(); c(1); exec c.code(), but found that was an invalid opcode,

That's not why you got the error.  You got the error because the 
interpreter tried to run off the end of your code.  It loaded the 
constant 1 on the stack, and then encountered the end of the code 
string (a NUL byte), which is an invalid opcode.


>  and I actually  to add c.RETURN_VALUE() to get it to work 
> correctly. Is it necessary that c.RETURN_VALUE() is called for each literal?

No - it's just required that your bytecode not run off the end of the 
string.  Python normally adds the equivalent of a Return_(None) to 
the end of every bytecode sequence it generates.  BytecodeAssembler 
assumes you will do this yourself if you need to.




More information about the PEAK mailing list