How lotabout/write-a-c-interpreter works
Project Type and Purpose
• This is a compiler/interpreter project (“xc.c”) that interprets C code by compiling it into an internal bytecode and running it on a simple virtual machine.
• It comes with a tutorial implementation (“xc‐tutor.c”) and multilingual documentation that walks through each stage: skeleton, virtual machine, lexer, parsing, variables, functions, statements, expressions.
File Structure
• Top-level files:
• xc.c ← the full interpreter’s source
• xc-tutor.c ← step-by-step tutorial build of the interpreter
• hello.c ← sample C program used for testing
• tutorial/ ← Markdown guides in multiple languages
• There are no external dependencies or build scripts beyond a simple gcc invocation.
• The codebase implements a linear pipeline (scanning → parsing → code‐gen → VM) in a single C program.
README for Additional Insights
• Confirms a self‐interpreting design (the interpreter can compile and run itself).
• Inspired by the “c4” project, but rewritten for clarity.
• Usage: compile xc.c, then feed it one or more .c inputs to produce and execute bytecode, optionally emitting an s-expression view.
a. Main Components
1. Driver / CLI Module
2. Scanner (Lexer)
3. Parser (Recursive-descent, produces AST)
4. Semantic Analyzer / Symbol Table
5. Code Generator (AST → Bytecode)
6. Virtual Machine (Bytecode Interpreter)
7. Runtime Data Structures (stack, heap, call frames)
8. Input Source Files & Output (console, s-expr dump)
b. Relationships and Interactions
Source File → Driver → Scanner → Parser → Semantic Analyzer → Code Generator → VM → Program Output
• The Driver may loop to re-invoke downstream stages (to recompile xc.c itself).
• The VM invokes runtime data structures (stack, global memory).
c. Architectural Patterns / Design Principles
• Pipeline architecture (each stage hands off to the next).
• Recursive-descent parser for simplicity and clarity.
• Stack-based virtual machine model.
• Single executable amalgamating compiler and runtime.
d. Technologies and Libraries
• C99 (gcc) for implementation.
• No third-party libraries; everything is hand-rolled for didactic clarity.