Instrument Stack Language Jumps
Problem statement
Transform a stack-language program so each original unconditional JUMP target has this three-instruction diagnostic block immediately before it: PUSH jump@i, PRINT, POP, where i is that jump's original zero-based index.
Return the transformed instruction list. These diagnostic instructions print the original jump index and restore the original stack before the jump executes.
Rewrite the target of every original JUMP and JUMP_IF_EMPTY. A target naming an original instruction must point to the beginning of that instruction's transformed block, including its diagnostic prefix when it is an unconditional jump. The original end target instructions.length must become the transformed program length.
Instrument only unconditional JUMP instructions. Preserve every other instruction exactly, except for rewriting conditional-jump targets. Do not instrument the inserted instructions or execute the program.
Function
instrumentJumps(instructions: String[]) → String[]Examples
Example 1
instructions = ["PUSH x","JUMP 3","PUSH skip","PRINT"]return = ["PUSH x","PUSH jump@1","PRINT","POP","JUMP 6","PUSH skip","PRINT"]The original index 3 moves to index 6 after the three diagnostics inserted before the jump at index 1.
Example 2
instructions = ["JUMP_IF_EMPTY 2","JUMP 3","JUMP 3"]return = ["JUMP_IF_EMPTY 5","PUSH jump@1","PRINT","POP","JUMP 9","PUSH jump@2","PRINT","POP","JUMP 9"]The conditional jump now targets index 5, the diagnostic entry for the original jump at index 2. Both unconditional jumps now target the new end index 9.
Example 3
instructions = ["PUSH JUMP 0","PRINT"]return = ["PUSH JUMP 0","PRINT"]Text inside a pushed value is data, so neither instruction is instrumented.
Constraints
- For this exercise, assume
0 <= instructions.length <= 1000. - Each original instruction is
PUSH value,POP,PRINT,TRUNCATE k,JUMP target, orJUMP_IF_EMPTY target. - A pushed value has at most
50printable ASCII characters excluding line breaks. Preserve its spaces;PUSHmay have an empty value. - Opcodes are uppercase. Operand instructions have one separating space. Numeric operands use unsigned decimal notation without leading zeros except
0. - Jump targets are valid original indices or the original end index. Backward and self-jumps are allowed because this function only transforms instructions.