originally inspired by Jamie Kyle's The Super Tiny Compiler written in JavaScript
Welcome to The Tiny Lua Compiler!
This is an ultra-simplified example of all the major pieces of a modern compiler written in easy to read Lua code.
- Zero dependencies: This compiler is written in pure Lua and has no dependencies.
- Educational: Reading through the guided code will help you learn about how most compilers work from end to end.
- Self-compiling: This compiler can compile itself!
That's fair, most people don't really have to think about compilers in their day jobs. However, compilers are all around you, tons of the tools you use are based on concepts borrowed from compilers.
Lua is a simple programming language that is easy to learn and use. It doesn't have complex syntax or a lot of features, which makes it a great language to make a compiler for.
Yes, they are. But that's our fault (the people who write compilers), we've taken something that is reasonably straightforward and made it so scary that most think of it as this totally unapproachable thing that only the nerdiest of the nerds are able to understand.
Awesome! Head on over to the the-tiny-lua-compiler.lua file.
Currently, the compiler only supports Lua 5.1. Here's an example of how you can use it:
local tlc = require("the-tiny-lua-compiler")
local inputCode = [[
for index = 1, 10 do
print(index)
end
print("Hello, World!")
]]
local tokens = tlc.Tokenizer.new(inputCode):tokenize()
local abstractSyntaxTree = tlc.Parser.new(tokens):parse()
local prototype = tlc.CodeGenerator.new(abstractSyntaxTree):generate()
local bytecode = tlc.Compiler.new(prototype):compile()
local compiledFunction = loadstring(bytecode)
-- Run the compiled function
compiledFunction()
Run with lua tests/test.lua