<s> import struct <EOL> from . . import ir <EOL> from . . jvmops import * <EOL> def _calcMinimumPositions ( instrs ) : <EOL> posd = { } <EOL> pos = <NUM_LIT:0> <EOL> for ins in instrs : <EOL> posd [ ins ] = pos <EOL> if isinstance ( ins , ir . LazyJumpBase ) : <EOL> pos += ins . min <EOL> elif isinstance ( ins , ir . Switch ) : <EOL> pad = ( - pos - <NUM_LIT:1> ) % <NUM_LIT:4> <EOL> pos += pad + ins . nopad_size <EOL> else : <EOL> pos += len ( ins . bytecode ) <EOL> return posd , pos <EOL> def optimizeJumps ( irdata ) : <EOL> instrs = irdata . flat_instructions <EOL> jump_instrs = [ ins for ins in instrs if isinstance ( ins , ir . LazyJumpBase ) ] <EOL> while <NUM_LIT:1> : <EOL> done = True <EOL> posd , _ = _calcMinimumPositions ( instrs ) <EOL> for ins in jump_instrs : <EOL> if ins . min < ins . max and ins . widenIfNecessary ( irdata . labels , posd ) : <EOL> done = False <EOL> if done : <EOL> break <EOL> for ins in jump_instrs : <EOL> assert ( ins . min <= ins . max ) <EOL> ins . max = ins . min <EOL> def createBytecode ( irdata ) : <EOL> instrs = irdata . flat_instructions <EOL> posd , end_pos = _calcMinimumPositions ( instrs ) <EOL> bytecode = bytearray ( ) <EOL> for ins in instrs : <EOL> if isinstance ( ins , ( ir . LazyJumpBase , ir . Switch ) ) : <EOL> ins . calcBytecode ( posd , irdata . labels ) <EOL> bytecode += ins . bytecode <EOL> assert ( len ( bytecode ) == end_pos ) <EOL> prev_instr_map = dict ( zip ( instrs [ <NUM_LIT:1> : ] , instrs ) ) <EOL> packed_excepts = [ ] <EOL> for s , e , h , c in irdata . excepts : <EOL> s = prev_instr_map . get ( s , s ) <EOL> s_off = posd [ s ] <EOL> e_off = posd [ e ] <EOL> h_off = posd [ h ] <EOL> assert ( s_off <= e_off ) <EOL> if s_off < e_off : <EOL> packed_excepts . append ( struct . pack ( '<STR_LIT>' , s_off , e_off , h_off , c ) ) <EOL> else : <EOL> print ( '<STR_LIT>' ) <EOL> assert ( <NUM_LIT:0> ) <EOL> return bytes ( bytecode ) , packed_excepts </s>
