Skip to content

Instantly share code, notes, and snippets.

@oleganza
Forked from michaelklishin/gist:25453
Created November 16, 2008 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oleganza/25529 to your computer and use it in GitHub Desktop.
Save oleganza/25529 to your computer and use it in GitHub Desktop.
Generates a byte code for the "if" expression.
To understand how it works consider the
following Scheme code:
(if (> 3 8) 10 14)
The expression results in the following byte code:
array('i', [9, 0, 9, 1, 5, 6, 1, 2, 17, 14, 9, 2, 16, 16, 9, 3])
and `disasm` outputs the following:
literals:
0: 3
1: 8
2: 14
3: 10
instructions:
--------------------------------------------------
0000 push_literal literal=0
0002 push_literal literal=1
0004 push_local idx: 6, name: >
0006 call argc=2
0008 goto_if_not_false ip=0x000E
000A push_literal literal=2
000C goto ip=0x0010
000E push_literal literal=3
0010 ...
"If" expression in this example has the condition expression,
"then" clause and "else" clause. It is turned into two
jump instructions and three
instructions (or sequence instructions in more complex
cases), one for the condition expression,
one for the "then" clause and one for the "else" clause.
In the example above condition expression is (> 3 8) which
results into the following instructions:
0000 push_literal literal=0
0002 push_literal literal=1
0004 push_local idx: 6, name: >
0006 call argc=2
Then goto_if_not_false instruction is used to jump to the "then"
clause if the value on the top of the stack (the result of evaluating
of
0008 goto_if_not_false ip=0x000E
jumps to the instruction at 0x000E if the value on the top of the stack
is not false.
0x000E is the value of the "then" clause that pushes 10 on top
of the stack in this example:
000E push_literal literal=3
10 comes from the 3rd literal in the literals frame.
if the jump at 0008 does not happen, instruction at
000A is executed:
000A push_literal literal=2
it pushes 14 (2nd slot in literals frame) onto the stack.
14 is the value of "else" clause in this example. Then
to jump over "then" clause we use goto instruction.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment