You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
refactor: abstract stack pushing/popping in compiler 'GenerateTargetTraversal' #218
A good refactor would be to abstract stack pushing/popping in compiler 'GenerateTargetTraversal.ts'
from June 2023 discussion:
I agree it's confusing. It might be good to abstract away the stack pushing/popping at some point actually, since it's been the cause of a few bugs in the past 😅
This whole piece of code is very very bad and I would hopefully not write it the same way if I were to do it again lmao. But hopefully this gives some insight into what is actually happening here and what you need to change. By the end of your execution you need to end up with '(value)' on top of the stack, and the rest of the stack being unaffected.
So to recap: this.stack keeps track of what the stack looks like if the compiled bytecode were to be executed up until then. this.pushToStack() pushes to this stack, and this.popFromStack() pops from it.
In the example above, we start with this stack:
1:
When we execute this.emit(hexToBin('a914')), this pushes a value to the stack, so we also call this.pushToStack('(value)') to account for that.
1:
2:
Then we call this.visit(node.parameters[0]), the end result of this "visit" will be a new value on the stack (this is pushed in the call to this.visit().
1: node.parameters[0]
2:
3:
Then we execute this.emit(Op.OP_CAT), this concats the top 2 stack elements together. Because I am lazy I don't call this.popFromStack() here. So we need to remember to call pop 1x later on.
1: + node.parameters[0]
2:
Then we execute this.emit(hexToBin('87')), pushing a value to the stack. We don't call pushToStack, which cancels out last time we didn't call pop.
1:
2: + node.parameters[0]
3:
Then we execute this.emit(Op.OP_CAT), concatenating again. We don't call pop, so we need to remember to call pop 1x later on.
1: + node.parameters[0] +
2:
Then we call this.popFromStack(2) (equivalent to 2x this.popFromStack()) and later outside the big if-statement we call this.pushToStack('(value)'). The first pop is to compensate for the one we skipped earlier, the second pop+push is to replace whatever was on top of the stack with '(value)'.
I think by now GenerateTargetTraversal is over 1000 lines, so the entire file needs some good refactoring. The specific refactor mentioned in this issue should definitely be in there, but it needs to be a broader refactor.
Had a look at how this could be approached. Proposal below, nothing implemented yet.
The problem
Every visitor does two things by hand that have to agree: this.emit(...) (the bytecode) and pushToStack / popFromStack (the model of the stack). The file currently has 118 emit calls and 71 manual stack-bookkeeping calls. In a few places they are deliberately out of sync and reconciled afterwards, as in the walkthrough above: visitInstantiation skips pops and a push and reconciles with popFromStack(2) plus a later push, and the runtime-size path of emitNullDataChunk emits 19 opcodes and reconciles with a single popFromStack().
Proposed approach
Derive the stack effect from the opcode. A table says OP_CAT pops 2 and pushes 1, a data push pushes 1, OP_NIP removes slot 1, and so on, and emit() applies it. Most opcodes we emit are plain "pops n, pushes m".
Named helpers for what cannot be derived.OP_ROLL / OP_PICK depend on the index, and function calls / inlined bodies are opaque but have a known signature.
Move it into its own class. A ScriptEmitter owns output, locationData, stack and sourceTags, and with them the instruction pointer that requires, consoleLogs and inlineRanges key off. The traversal then only describes what each node compiles to, which is also a first step in the broader split of this file.
What it could look like
// derived effect: no manual bookkeepingthis.emit(Op.OP_CAT,end(node));// opaque bytecode with a declared effect (builtins, OP_INVOKE, inlined bodies)this.emitCall(symbol.bytecode,end(node),{pops: node.parameters.length,pushes: returnValueCount});// named stack operations replace the `<index> OP_ROLL OP_DROP` + removeFromStack idiomthis.pick(name,start(node));this.roll(name,start(node));this.drop(index,end(node));this.replace(name,end(node));// slots and names that no opcode createsthis.seedInput(node.name);// parameters and the function selectorthis.nameTop(node.name);// variable definition: name the '(value)' on topthis.anonymise(name);// unscoped reassignment: the old slot becomes '(value)'// scopes and tags as wrappers instead of start/end index arithmeticthis.scoped(node.ifBlock,()=>this.visit(node.ifBlock));// drops what the block addedthis.tagged(SourceTagKind.LOOP_CONDITION,()=>{ ... });
start(node) / end(node) replace the { location, positionHint } literals, of which there are about 70 (28 of them exactly { location: node.location, positionHint: PositionHint.END }).
P2PKH, P2SH20 and P2SH32 then only differ in prefix and suffix bytes, so the three branches can become one { prefix, suffix } lookup. Simple visitors shrink the same way:
The model cannot drift from the bytecode. A skipped pop is no longer possible for ordinary opcodes, which removes the class of bug this issue is about.
Internal errors instead of bad bytecode. With an exact model we can assert that both arms of an OP_IF end at the same depth, that a loop body is net zero, and that a function ends with the expected stack. Today those mistakes compile silently.
Visitors read as the opcodes they emit. The three copies of <index> OP_ROLL OP_DROP + removeFromStack collapse into drop(), and the hand-rolled source-tag index calculations into tagged().
Somewhat fewer lines in the traversal, not in total. Rough estimate: the traversal shrinks by 150-200 lines, and the emitter plus effect table add about as many.
Catches
removeFinalVerifyFromFunction. It pops an already-emitted op from output and either re-emits it or patches the previous op's location. With auto-tracking that would undo or double-apply a stack effect (and the op can be OP_ENDIF / OP_UNTIL), so it needs an explicit unemit() or a different shape, e.g. deciding before the final OP_VERIFY is emitted.
Branches. Arms are not always net zero: in the function selector in visitContract, each arm runs a whole function body and cleans the stack down to one item, which is why the stack is copied and restored by hand today. The emitter would snapshot at OP_IF, restore at OP_ELSE and assert equal depth at OP_ENDIF.
Named slots.emitReplace moves a new value into a named slot through a swap/altstack sequence. Simulated literally the name would be lost, so it stays an opaque helper with a declared effect.
Altstack.OP_TOALTSTACK / OP_FROMALTSTACK are used in visitTupleAssignment, emitReplace and the loop condition. "Pop 1 / push 1" is enough as long as values are named after they come back, otherwise the emitter needs to model the altstack too.
finalStackUsage.visitIdentifier records the IP between the index push and OP_ROLL, so roll() has to expose it.
Table entries that are easy to get wrong.OP_CHECKMULTISIG is variable arity and needs an explicit effect, OP_CHECKLOCKTIMEVERIFY / OP_CHECKSEQUENCEVERIFY do not pop, OP_SPLIT is 2 → 2.
Suggested order
start() / end() location helpers and the drop / pick / roll helpers. Mechanical, output should stay byte-identical.
The effect table and auto-tracking emit, deleting the manual push/pop calls visitor by visitor. The existing fixture tests should catch any bytecode change.
Extract ScriptEmitter into its own file, and move global-function definition and debug-info merging out of the traversal as part of the broader split.
Activity
rkalis commentedon Jul 28, 2026
I think by now GenerateTargetTraversal is over 1000 lines, so the entire file needs some good refactoring. The specific refactor mentioned in this issue should definitely be in there, but it needs to be a broader refactor.
mr-zwets commentedon Nov 29, 2026
Had a look at how this could be approached. Proposal below, nothing implemented yet.
The problem
Every visitor does two things by hand that have to agree:
this.emit(...)(the bytecode) andpushToStack/popFromStack(the model of the stack). The file currently has 118emitcalls and 71 manual stack-bookkeeping calls. In a few places they are deliberately out of sync and reconciled afterwards, as in the walkthrough above:visitInstantiationskips pops and a push and reconciles withpopFromStack(2)plus a later push, and the runtime-size path ofemitNullDataChunkemits 19 opcodes and reconciles with a singlepopFromStack().Proposed approach
OP_CATpops 2 and pushes 1, a data push pushes 1,OP_NIPremoves slot 1, and so on, andemit()applies it. Most opcodes we emit are plain "pops n, pushes m".OP_ROLL/OP_PICKdepend on the index, and function calls / inlined bodies are opaque but have a known signature.ScriptEmitterownsoutput,locationData,stackandsourceTags, and with them the instruction pointer thatrequires,consoleLogsandinlineRangeskey off. The traversal then only describes what each node compiles to, which is also a first step in the broader split of this file.What it could look like
start(node)/end(node)replace the{ location, positionHint }literals, of which there are about 70 (28 of them exactly{ location: node.location, positionHint: PositionHint.END }).The P2SH20 case from the walkthrough, today:
With the effect derived (same bytecode, same location data, same resulting stack):
P2PKH, P2SH20 and P2SH32 then only differ in prefix and suffix bytes, so the three branches can become one
{ prefix, suffix }lookup. Simple visitors shrink the same way:Benefits
OP_IFend at the same depth, that a loop body is net zero, and that a function ends with the expected stack. Today those mistakes compile silently.<index> OP_ROLL OP_DROP+removeFromStackcollapse intodrop(), and the hand-rolled source-tag index calculations intotagged().Catches
removeFinalVerifyFromFunction. It pops an already-emitted op fromoutputand either re-emits it or patches the previous op's location. With auto-tracking that would undo or double-apply a stack effect (and the op can beOP_ENDIF/OP_UNTIL), so it needs an explicitunemit()or a different shape, e.g. deciding before the finalOP_VERIFYis emitted.visitContract, each arm runs a whole function body and cleans the stack down to one item, which is why the stack is copied and restored by hand today. The emitter would snapshot atOP_IF, restore atOP_ELSEand assert equal depth atOP_ENDIF.emitReplacemoves a new value into a named slot through a swap/altstack sequence. Simulated literally the name would be lost, so it stays an opaque helper with a declared effect.OP_TOALTSTACK/OP_FROMALTSTACKare used invisitTupleAssignment,emitReplaceand the loop condition. "Pop 1 / push 1" is enough as long as values are named after they come back, otherwise the emitter needs to model the altstack too.finalStackUsage.visitIdentifierrecords the IP between the index push andOP_ROLL, soroll()has to expose it.OP_CHECKMULTISIGis variable arity and needs an explicit effect,OP_CHECKLOCKTIMEVERIFY/OP_CHECKSEQUENCEVERIFYdo not pop,OP_SPLITis 2 → 2.Suggested order
start()/end()location helpers and thedrop/pick/rollhelpers. Mechanical, output should stay byte-identical.emit, deleting the manual push/pop calls visitor by visitor. The existing fixture tests should catch any bytecode change.ScriptEmitterinto its own file, and move global-function definition and debug-info merging out of the traversal as part of the broader split.