[Python-Dev] Switch statement
Phillip J. Eby
pje at telecommunity.com
Mon Jun 19 16:29:49 CEST 2006
At 12:10 AM 6/20/2006 +1000, Nick Coghlan wrote:
>Caching on first use would be the easiest to explain I think. Something like:
>
> if jump_dict is NULL:
> jump_dict = {FIRST_CASE : JUMP_TARGET_1,
> SECOND_CASE : JUMP_TARGET_2,
> THIRD_CASE : JUMP_TARGET_3}
> jump_to_case(value, jump_dict)
> ELSE_CLAUSE
> jump_to_end()
Sadly, it's not *quite* that simple, due to the fact that co_lnotab must be
increase in line numbers as bytecode offsets increase. It would actually
look more like:
LOAD_DEREF jumpdictN
JUMP_IF_FALSE initfirstcase
do_switch:
...
initfirstcase:
DUP_TOP
# compute case value
LOAD_CONST firstcaseoffset
ROT_THREE
STORE_SUBSCR
JUMP_FORWARD initsecondcase
firstcaseoffset:
first case goes here
...
initsecondcase:
DUP_TOP
# compute case value
LOAD_CONST secondcaseoffset
ROT_THREE
STORE_SUBSCR
JUMP_FORWARD initthirdcase
secondcaseoffset:
second case goes here
...
...
initlastcase:
DUP_TOP
# compute case value
LOAD_CONST lastcaseoffset
ROT_THREE
STORE_SUBSCR
JUMP_ABSOLUTE doswitch
lastcaseoffset:
last case goes here
The above shenanigans are necessary because the line numbers of the code
for computing the case expressions have to be interleaved with the line
numbers for the code for the case suites.
Of course, we could always change how co_lnotab works, which might be a
good idea anyway. As our compilation techniques become more sophisticated,
it starts to get less and less likely that we will always want bytecode and
source code to be in exactly the same sequence within a given code object.
More information about the Python-Dev
mailing list