rbartlensky / Lua-interpreter

A Lua interpreter in Rust
5 stars 2 forks source link

Extend code to allow compilation of chunks. #14

Closed rbartlensky closed 5 years ago

rbartlensky commented 5 years ago

The compile considers the module to be a function, making it easier to add upvalues. The compiler produces a CompiledFunc for each function that it encounters. These are translated into Functions, which are easier to understand from the VMs point of of view.

ltratt commented 5 years ago

Are chunks a Lua concept?

rbartlensky commented 5 years ago

Yes they are. (https://www.lua.org/manual/5.3/manual.html#3.3.2)

ltratt commented 5 years ago

It's not obvious to me that function == chunk. In fact, the link seems to suggest it absolutely isn't a chunk.

rbartlensky commented 5 years ago

It might not be super obvious in this PR, but in the following ones you will be able to tell that. When I compile functions, I create a new chunk, link it to the current one, compile its instructions, and then return to the parent to finish compiling it. I am splitting my work on functions into smaller PRs so that they are easier to review. (at the moment I have around 800 lines for simple function calls i.e. no parameters, no return values, etc.)

rbartlensky commented 5 years ago

Ah I see now why it might not be obvious. Lua refers to 'modules' as chunks, and functions are functions.

rbartlensky commented 5 years ago

In my case, I am also referring to functions as chunks because it makes the implementation much easier to write and to understand. If I introduce a Function struct then I will end up with a structure that is very similar to the Chunk one.

rbartlensky commented 5 years ago

Actually I think it makes more sense to rename Chunk to Function. Seems like the implementation of Lua does this as well (It considers even the module as a function).

rbartlensky commented 5 years ago

So it seems like in Lua chunks are just blocks of instructions (just like it says in the docs), but in the actual implementation a chunk is basically modeled as a closure/function. Hopefully this makes more sense now. (Sorry for the confusion!)

I guess it is ready for review now.

ltratt commented 5 years ago

Chunks are, I think, just anonymous functions. It makes much more sense to model them that way than making everything be chunks.

rbartlensky commented 5 years ago

Using a disassembler on a program which creates an anonymous function reveals that even for these Lua just creates a function and a closure.

rbartlensky commented 5 years ago

Now I have two different structures, one which is use by the compiler and one which is used by the VM. I am still using indices to reference functions, because I modify the state of CompiledFuncs, thus I can't really use Rcs. I also addressed your other comments. I guess this is ready for another review.

ltratt commented 5 years ago

Please squash.

rbartlensky commented 5 years ago

Squashed!