I heard that some languages go from interpreted to compiled by ‘unrolling the interpreter loop’.
Let’s say I have the following pseudo-c-code interpreter for an ast tree.
int interpret(node) { switch(node) { case PLUS: return interpret(child(0))+interpret(child(1)); case MINUS: return interpret(child(0))-interpret(child(1)); } }
How do I unroll this loop to create a compiled program?
I see you all downvoting this like I don’t know what I am talking about, but here is a quote from Wikipedia that states exactly what I am describing.
‘Factor was originally only interpreted, but is now fully compiled (the non-optimizing compiler basically unrolls the interpreter loop’
‘Unrolling a loop’ normally means replacing a repetition with a sequence of actions. The loop:
would unroll into the equivalent:
It appears to me that whoever was being quoted by Wikipedia was using the phrase in a somewhat metaphorical sense. So, in that sense…
Your sample would normally be invoked inside a interpreter that is walking a tree of AST nodes, which might look something like this:
and the
interpretfunction would have additional options:If you walk the AST with that
interpetfunction (actually performing the operations), you’re interpreting. But if the function records the actions to be performed, rather than executing them, you’re compiling. In pseudocode (actually, pseudocode twice, as I’m assuming a hypothetical stack machine as the compilation target):Invoking
compileon that AST (ignoring any pseudocode typos 😉 would spit out something like:FWIW, I’d tend to think of that as unrolling the AST, rather than unrolling the interpreter, but won’t criticize somebody else’s metaphor without reading it in context.