Overengineered Calculator: Zig and QBE
5 hours ago
- Crafting Interpreters and Writing An Interpreter In Go teach tokenization, parsing, and interpretation but do not cover native code generation.
- QBE is a compact compiler backend providing 70% of the performance of industrial compilers in 10% of the code, ideal for learning code generation.
- The project uses a simple grammar for arithmetic expressions to define precedence and tokenization rules.
- The tokenizer is a state machine implemented in Zig, producing tokens like numbers, operators, and parentheses.
- The parser builds an AST with binary and unary operations based on grammar rules like Sum, Product, and Unary.
- The interpreter evaluates the AST directly by recursively computing values for binary and unary operations.
- The emitter generates QBE intermediate language in static single-assignment form, mapping operations to QBE instructions.
- The compiler stages include generating QBE SSA code, using QBE to produce assembly, and then compiling with Zig to create an executable.
- QBE optimizes by constant folding when possible, but division prevents full optimization, producing explicit assembly instructions.
- The project requires QBE and Zig packages to build and run, with source code available for further development.