Snakes On A Moon
Snakes on a moon is a Lua virtual machine implementation written in Python that uses the RPython translation toolchain from the PyPy project to create a fast interpreter with a JIT compiler. Lua is a simple but powerful scripting language suitable to be embedded in large application written in static languages like C and C++, but can also be used as a standalone language. The Lua interpreting process can be seen as two distinct phases: the first parses the lua code and generates a compiled bytecode, and the second runs it on a virtual machine. Snakes on a moon only implements the second part. It consists of a virtual machine written in RPython that parses Lua bytecode and runs it on its own interpreter. This code can then be translated to a fast interpreter in C with a JIT compiler and compiled to a native executable, and will be much faster than running the interpreter on CPython and hopefully outperform the standard Lua implementation.
To interpret a Lua script, run
python interpreter.py luac-file,
luac-file is a file generated by the
luac command from a lua
source file. The parser can also be used stand-alone by running
python parser.py luac-file to test if the luac file parses, and if
successful it will print out the header data.
The parser is now able to be translated with RPython, so by using the
rpython tool from the PyPy
project (located in rpython/bin/)
with parser.py, it will create a native version of the parser called
parser-c that should work the same.
parser.py: Defines the class
LuaBytecodethat reads a string of lua bytecode generated by the
luactool (which is part of the lua distribution), and creates an object containing the all of the data from the bytecode organized and able to be used by the interpreter.
interpreter.py: Defines the
Interpreterclass, which is in charge of executing the Lua program and contains the main execution loop.
luatypes.py: Contains Python representations for some of the various types in the Lua language, such as LuaTable.
library.py: Defines the Lua standard library, documented here.
test/: Contains various sample lua programs from the lua distribution used to test the implementation.
Credits & Acknowledgements
Snakes On A Moon is authored by Brian Leibig. The project was inspired by a blog post and the goal is to implement a nontrivial yet still simple language similar to the tutorial to explore how PyPy works and how well it would work for languages other than Python.
The Lua ChunkSpy tool and the associated guide to the bytecode format by Kein-Hong Man, esq. are very useful for understanding the format and semantics of Lua bytecode. Read the guide for detailed information on how a Lua virtual machine works and what each opcode does.