Interesting things about the Lua interpreter (2020)
thesephist.com
thesephist.com
This is a common source of confusion, because the name "register machine" makes people think about CPU registers. However, the registers in a register VM are merely slots in the traditional runtime stack. The difference between a stack and register machine has to do with how the bytecode instructions are encoded. In a stack machine, most instructions implicitly pop arguments from and push their results to the top of the stack. The instructions are byte-sized, encoding just the operation name. For example, to add 10+10
LOADK 10
DUP
ADD
Meanwhile, in a register machine the instructions can read and write to any slot in the stack. Instructions are larger, because in addition to the operation name they also encode the indexes of the input slots and the index of the output slot. But it's worth it because you need less instructions in total and do less stack shuffling. LOADK 1 10
ADD 1 1 2So how does having a larger "microarchitectural" register file help?
Regiater renaming is used to eliminate false data dependencies arising from the reuse of registers by successive instructions that do not have any real data dependencies between them.
This allows independent instructions to be executed in parallel even if seems that you'd have to wait until a regiater is freed up.
I do believe that an un-bloated JavaScript language from when it was just invented would be simpler than Lua (as both were designed as "scripting" languages, not as main ones), but history didn't go that route :)
But... Lua is WEIRD! Weird nomenclature, weird string concatenation operand, 1-based arrays, too clever "tables" and "metatables" stuff.
One fun thing we did with co-routines was build literate-style scripting for our designers to define AI routines. They could write them in a linear/semi linear way with yield(<number of frames to wait to re-execute>) that allowed them to script all sorts of interesting behaviors without extensive programming knowledge.
We also ran the whole thing inside a 400kb pre-allocated block, it's an incredible powerful, embeddable language.
Out of curiosity: what Lua interpreter did you pick for your .net project?
It sounds like the stack is perhaps a Stack<Frame pointer¹>, where each Frame contains the locals for that stack frame; then a coroutine just needs to keep a pointer to the stack frame it is closing over. (And then, Frame does too, recursively, incase there is more than one scope being closed over.)
This would be extremely similar to … most any other language … and makes me wonder why Lua gives them such a unique name. It has been hard to really comprehend the Lua spec, when I've tried to understand that facet of it.
(I'd also argue that Lua isn't as simple as it is made out to be: primitives behave wildly different from objects, there's the 1-based indexing, multiple-return is pretty much unique to Lua (vs. returning a tuple, which other languages such as Python, Rust, and sort-of JS, go for; I think that's conceptually simpler).)
¹and note "pointer" here might really be "GC ref", to permit these to be GC'd as necessary, as closures can keep stuff alive far longer than normal.
No, the stack isn't a list of frames where each frame is a separate heap allocated list of slots for values. You're right that that's a very common (but not super fast) implementation technique.
The Lua stack is a single contiguous array of value slots that is used by all call frames. In fact, call frames use overlapping stack windows so that function call arguments don't need to be moved during a call.
That makes implementing closures particularly tricky since when a function returns, its region of the stack is immediately reused by later code.
Upvalues address that by moving just the local variables that are closed over off that contiguous stack array and into the heap. And they do that only when the function where the variable is declared returns so that during that functionn's lifetime, it can be accessed directly from the stack. Also, the compiler is able to manage all this just with a single pass compilation.
It's really clever.
Multiple returns are from Common Lisp (I don't know if the history goes back further though), and they aren't tuples. They're the return-position analogue of what are default arguments in argument-position; like default args allow callers to ignore arguments they don't care about, multiple returns allow callers to ignore the return values they don't care about. You can add a secondary return value to a function without breaking existing callers, just like you can add a new default arg.
I’m pretty sure I saw multiple returns used in pseudo-code on a class handout the semester before I started working on CLU. The class was “Structure and Interpretation of Computer Programs” that would lead to the writing of SICP.
> From CLU we took multiple assignment and multiple returns from function calls. We regarded multiple returns as a simpler alternative to reference parameters used in Pascal and Modula and to in-out parameters used in Ada; we also wanted to avoid explicit pointers (used in C).
Lisp Machine Lisp is claimed to be the first Lisp to have that feature (end 70s), from where Common Lisp got it.
Edit: And yeah I don't think it's anything unique to Lua, it's an implementation detail of closures and lexical scope generally. It's a non-stack wrapper for closed-over variables, the end of the introduction to chapter 25 explains:
> For locals that aren’t used in closures, we’ll keep them just as they are on the stack. When a local is captured by a closure, we’ll adopt another solution that lifts them onto the heap where they can live as long as needed.
I sort of thought about mentioning something like that; that's in what I categorize as an optimization. (A good one, since the common case is that there probably isn't a closure at all in the scope, and the entire scope can thus be moved to the stack, kept out of heap, and not GC'd, reducing GC pressure.)
^ I mean internal stack structures, not a public stack, which is fully dynamic and may be cleared without affecting anything, e.g. in lua_CFunction. There’s nothing you can refer to on the stack, the same way you don’t want to refer to a temporary technical `push` in Assembly. Consider this:
function f()
local arr = []
for i = 0, 100000000 do
table.insert(arr, function ()
return i
end)
end
end
If `i` was created on the stack on every iteration, it would quickly overflow it, because you can’t just erase previous i, since it was closed.(For those unaware: `for i …` “creates” a new variable/upvalue at each iteration. Every arr[?]() returns a different value in this example.)
(A corrected version of your counter-example:
function f()
local arr = {}
for i = 0, 5 do
table.insert(arr, function ()
return i
end)
end
return arr
end
I've also changed the constant to make it reasonable to run, without creating an enormous table.)That's good counter-example, and does run counter to my intuition. (The behavior I describe, e.g., in Python, is different; the closures in Python all close over the same variable.) One might be able to boil this down to instead using "scope" where I was saying "stack frame". (The difference being that for loops in Lua create scopes, vs. Python, where they do not. IMO Lua's is the better of the two options.)
To combine the optimization in the sibling thread (that I was attempting to avoid for simplicity's sake), then the implementation could be a stack of scope-ishes, consisting of the unclosed variables only, and then optionally some structure under GC, containing the closed-over variables (none, if nothing is closed over). The scopes on the stack would need to know of the (potential) GC object holding the closed over variables; a (normal) use of `i` here would have to look up the same `i` as what the closure hold, and as you note, cannot live on the stack.
… this is where, again, I think a diagram would help. I don't know that terms like "upvalue" and "activation record" help build understanding of Lua to new practitioners, and IMO, do more to obscure it. (This isn't your fault, ofc.; these are the terms Lua itself uses for these concepts.)
The pdf they based the blog post off of even says the incremental GC is upcoming in 5.1, and you can read through https://www.lua.org/source/5.0/lgc.c.html yourself and see that, unlike the 5.1 version, it only has a single mark list and doesn't use the tri-color scheme.
It's still a really insightful and approachable paper that's worth reading, and it does still help understand the constraints and approach of lua. But the current "old" version of the language is 5.2 released in 2011, and there have been a couple major versions after that as well.
So some of it may not actually be applicable to using lua now, depending on what your "now" looks like.
Lua is basically done as a language.
Instead there are like 5 hacky ways to do it: http://lua-users.org/wiki/StringInterpolation
I've written so much FFI code for Lua it's ridiculous. Rust mlua has been a total game-changer for me.
- register based VM with 32 bit instruction words holding 6 bit opcodes.
- closures that start on the stack and are moved to the heap.
- single pass compiler with no SSA, Lisp straight to code - but with additional optimization, informed by control and data flow analysis, done on the VM assembly code.
If you want all the gritty details, a chapter of Crafting Interpreters walks through a complete implementation of Lua's approach to closures:
They aren't the same thing but they are closely related concepts and similar solutions to the same potential problem.