[Python-Dev] Switch statement (original) (raw)

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 jumpdict is NULL: jumpdict = {FIRSTCASE : JUMPTARGET1, SECONDCASE : JUMPTARGET2, THIRDCASE : JUMPTARGET3} jumptocase(value, jumpdict) ELSECLAUSE jumptoend()

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