compiler construction - How to track the index of variables in an interpreter -
i'm creating interpreter (a bytecode interpreter, compiler) , i've found problem can't solve. need store variables somewhere. storing them in dictionary , looking them @ runtime way slow, i'd store them in registers , use indexes instead of name.
so @ compile time give every variable index, , create array of registers. that's fine monolithic scoped languages. language i'm creating interpreter has nested scopes (and function calls). approach have set of global registers, , stack of register lists function calls. virtual machine have like:
register globalregisters[number_of_globals]; stack<register[]> callstack;
but there's thing. language allows functions inside functions. example:
var x = 1; function foo() { y = 2; function bar() { z = 3; y = y - 1; } }
function bar() refers variable belongs foo(). means virtual machine have @ register list under top 1 on stack. if bar() recursive? if number of recursions defined user input? virtual machine wouldn't know how many stack elements have go under find set of registers containing value of y.
what effective solution problem? first time i'm dealing registers, calculations happen on value stack.
the usual way represent closures create struct contains both function pointer environment. simplest way represent environment pointer stack frame of outer function. inner function dereference pointer (with offset of given variable of course) when accessing variables of outer function.
however there's problem have consider: if foo
returns bar
, bar
called after foo
returned? in case pointer foo
's stack frame invalid stack frame no longer exist @ point. if want allow scenario (instead of making illegal return functions), need solution.
one common solution represent local variables pointers heap-allocated values , storing copies of pointers in function's struct.
another solution restrict closures, variables of outer function can accessed inner function if they're never re-assigned. that's closures in java 8 do. struct contain copies of variables instead of pointers.
Comments
Post a Comment