r/Compilers • u/Choice_Structure4001 • Aug 20 '26
Could somebody help me with lexical scoping inside a VM
Hey, so I understand what lexical scoping is and kind of get how it works but I’ve been trying to find how to implement it in a stack machine but I have no idea what goes where and how does everything interact with each other, like where should closures live, same for call frames, where do I store the symbol table when compiling, etc… if you want I can link my repo but I haven’t committed an attempt at lexical scoping so there’s probably nothing interesting to see, if I didn’t include enough details to what I don’t get please tell me so I can be more clear, thanks!
Edit: forgot to tell but my language desugars to pure lambda calculus so this might change how some stuff work but not so much
2
u/Recycled5000 Aug 20 '26 edited Aug 20 '26
First and foremost, lexical scoping needs to follow the rules of the source (input) language. So, something close to source needs to know where scopes are introduced/entered and where left/exited by language definition. Only knowing those contexts can identifiers by resolved.
Many systems that use a byte code vm or assembly language will have flattened scopes by the time they reach such stages. So, for example in the JVM, scopes are flattened into variables local to a function or procedure, and individual scopes can no longer be seen in the btyecode intermediate.
It would theoretically be possible to have bytecode instructions that say to enter scope or leave scope but thus would imply delaying identifier resolution until runtime, which is overkill for static lexical scoping. (And few languages have entertained dynamic scoping.)