Back in November, I had a silly idea: "what if I made my own programming language?"
I mean after all, all the OG programmers used to make their own compilers back in the day, so how hard could it be, right?
Turns out, it's both easier and harder than you'd think. The basic concepts are straightforward, but the devil is in the details. This is the story of how I built Fent, a simple compiled language that targets x86_64 assembly.
Features
But before diving in the implementation itself, we need to think about the features we want.
The list isn't complete but here are the basics:
- Support for binary operations such as +, -, *, /, ...
- Support for integers (and floating numbers if you feel brave), booleans and strings
- Support for variables declaration and usage
- If statements
- Functions declaration and usage with support for recursion
- While loops
Preview
We want our program to look roughly like this
var x = 4;
var str = "Hi";
var b = x+3;
while(b>0){
b = b-1;
}
if(b == 0){
print("Oh!");
}
return b;
Roadmap
The compilation pipeline is conceptually straightforward. For simplicity, we'll build a barebone compiler that targets x86_64 assembly instead of directly generating machine code. This means we can leverage existing tools (NASM for assembling, ld for linking) and focus on the interesting parts: lexing, parsing, and code generation.
Here's the complete pipeline:
Source Code
↓
[Lexer] → Tokens
↓
[Parser] → Abstract Syntax Tree (AST)
↓
[Code Generator] → x86_64 Assembly
↓
[NASM] → Object File
↓
[Linker] → Executable
I will go more in depth later on what Lexer and Parser are and then we will take a deep dive in the wonderful world of assembly conversion
Lexer
The first step is to roughly parse the source code and map the words to actual tokens that we will define
We will need a bunch of tokens for the features we want
As an example we would want
Definition
enum class TokenKind {
// Delimiters
LBrace,
RBrace,
Lpar,
Rpar,
Semicolon,
Comma,
// Literals and identifiers
Identifier,
Number,
String,
True,
False,
// Keywords
If,
Else,
While,
Return,
Var,
Define,
// Operators
Plus,
Minus,
Multiply,
Divide,
Modulo,
Equals,
EqualEqual,
Less,
Greater,
Not,
And,
Or,
// Control
EndOfFile,
Unknown
};
to take advantage of some built in C++ operations (especially on strings) we will define a struct
using LiteralValue = std::variant<std::monostate, int, bool, std::string>;
struct Token {
Position pos;
TokenKind kind;
std::string lexeme;
LiteralValue literal;
};
Implementation
The lexer's implementation is actually pretty straightforward. We'll use a single-pass linear scan, processing the source character by character. This approach is simple and efficient enough for most programming languages.
For simplicity, we won't implement sophisticated error recovery. If the lexer encounters something
it doesn't understand, it just emits an Unknown token and moves on. A production compiler would
want better error handling, but this keeps things clean for learning purposes.
The lexer itself maintains two pieces of state:
- a cursor (
pos) pointing into the source string - a line counter for diagnostics (that I ended up not implementing fully)
the main loop roughly looks like this
while (!isAtEnd(pos, source)) {
char c = peek(pos, source);
if (isspace(c)) {
if (c == '\n') line++;
pos++;
continue;
}
// Dispatch based on character category
}
This is the backbone of the lexer. Each iteration inspects the current character and decides how to interpret it. Whitespaces are completely ignored (except for newlines)
Single character tokens
Most punctuation and operators in the language are single characters so they can be processed immediatly
case '+':
tok.kind = TokenKind::Plus;
tok.lexeme = "+";
pos++;
tokens.push_back(tok);
continue;
The pattern is the exact same for parentheses, braces, commas etc
"Lookahead" for multi character operators
Some tokens require a minimal lookahead, as an example the "=" operator can be both "=" and "=="
But once again the approach is pretty straightforward
case '=':
if (peekNext(pos, source) == '=') {
tok.kind = TokenKind::EqualEqual;
tok.lexeme = "==";
pos += 2;
} else {
tok.kind = TokenKind::Equals;
tok.lexeme = "=";
pos++;
}
tokens.push_back(tok);
continue;
Numbers
Apart from the single character tokens the numbers may be one of the simplest to handle
We will simply declare a source variable pointing at the first digit (furthest left) of a number that we see and while the character next to it is a digit we increment pos
while (isdigit(peek(pos, source))) {
pos++;
}
Although this approach is extremely simple it makes decimal points not being handled
Strings
String literals will start with a double quote and they will be scanned until a matching closing quote is found. Escape sequences are handled inline:
if (c == '\\') {
pos++;
switch (peek(pos, source)) {
case 'n': processed += '\n'; break;
case 't': processed += '\t'; break;
case '"': processed += '"'; break;
}
pos++;
}
This design choice ensures that by the time the parser sees a string token, it already contains the actual value not the
escaped source representation.
If the lexer reaches the EOF without finding a closing quote we will just emit a Unknown token
Identifiers and keywords
Identifiers and keywords both share the same scanning logic. The lexer consumes alphanumeric characters, then decides what the token actually represents
tok.lexeme = source.substr(start, pos - start);
tok.kind = matchKeyword(tok.lexeme);
Keywords like if, while and return are resolved using a lookup table.Everything else defaults to
an identifier. Boolean literals are handled here as well and immediately assigned their literal values.
This allows us to keep the keyword handling explicit and avoids hardcoding language rules all over the lexer
End of input and unknown tokens
We have two remaining cases to handle. If we've reached the end of the file, we emit an EndOfFile
token. If we encounter a character we don't recognize, we emit an Unknown token. Both are trivial
to implement but important for making the lexer robust.
Parser
The parser's job is to take the flat stream of tokens from the lexer and build a structured representation of the program: the Abstract Syntax Tree (AST). While the lexer only cares about individual tokens, the parser understands the grammar of the language.
What is an AST?
An Abstract Syntax Tree is a hierarchical tree structure that represents the syntactic structure of the source code. Each node in the tree represents a construct in the language (expressions, statements, declarations, etc.).
For example, the expression x + 3 * 4 would be represented as:
graph TD
A[BinaryExpr: +]
A --> B[Identifier: x]
A --> C[BinaryExpr: *]
C --> D[Literal: 3]
C --> E[Literal: 4]
Notice how the tree respects operator precedence: multiplication binds tighter than addition, so 3 * 4 is a child node that gets evaluated first.
AST Node Definitions
Before diving into parsing, we need to define the data structures that represent our AST. We will use C++ classes with inheritance to model expressions and statements.
Expression Nodes
Expressions produce values. Our language supports several kinds:
class Expr {
public:
virtual ~Expr() = default;
};
// 42, true, "hello"
class LiteralExpr : public Expr {
public:
std::variant<int, bool, std::string> value;
};
// variable name
class IdentifierExpr : public Expr {
public:
std::string name;
};
// x + y, a * b
class BinaryExpr : public Expr {
public:
std::string op; // "+", "-", "*", "/", "==", "<", ">"
ExprPtr left;
ExprPtr right;
};
// -x, !condition
class UnaryExpr : public Expr {
public:
std::string op; // "-", "!"
ExprPtr operand;
};
// foo(a, b, c)
class CallExpr : public Expr {
public:
std::string function;
std::vector<ExprPtr> arguments;
};
Statement Nodes
Statements perform actions but don't produce values. They form the backbone of program control flow:
class Stmt {
public:
virtual ~Stmt() = default;
};
// var x = 10;
class VarDeclStmt : public Stmt {
public:
std::string name;
ExprPtr initializer;
bool isConst;
};
// x = 42;
class AssignStmt : public Stmt {
public:
std::string name;
ExprPtr value;
};
// if (condition) thenBranch else elseBranch
class IfStmt : public Stmt {
public:
ExprPtr condition;
StmtPtr thenBranch;
StmtPtr elseBranch; // can be nullptr
};
// while (condition) body
class WhileStmt : public Stmt {
public:
ExprPtr condition;
StmtPtr body;
};
// return expr;
class ReturnStmt : public Stmt {
public:
ExprPtr value; // can be nullptr for void return
};
// define foo(a, b) { body }
class FunctionDef : public Stmt {
public:
std::string name;
std::vector<FunctionParam> parameters;
StmtPtr body;
};
Parser Implementation
The parser maintains two simple pieces of state:
- A reference to the token stream
- A
currentindex pointing to the token being examined
class Parser {
private:
const std::vector<Token> &tokens;
size_t current = 0;
bool isAtEnd() const { return peek().kind == TokenKind::EndOfFile; }
const Token &peek() const { return tokens[current]; }
const Token &advance() {
if (!isAtEnd()) current++;
return previous();
}
The parser is organized as a recursive descent parser, where each grammar rule becomes a function. The structure naturally follows the precedence hierarchy of the language.
Parsing Flow
Here's how the parser processes a token stream into an AST:
graph TD
A[Token Stream] --> B[parse]
B --> C[parseStatement]
C --> D{Token Type?}
D -->|var| E[parseVarDecl]
D -->|if| F[parseIfStmt]
D -->|while| G[parseWhileStmt]
D -->|return| H[parseReturnStmt]
D -->|define| I[parseFunctionDef]
D -->|identifier| J[parseAssignment/ExprStmt]
E --> K[parseExpression]
F --> K
G --> K
H --> K
J --> K
K --> L[parseEquality]
L --> M[parseComparison]
M --> N[parseTerm]
N --> O[parseFactor]
O --> P[parseUnary]
P --> Q[parsePrimary]
Q --> R[AST Node]
Recursive Descent for Expressions
Expression parsing respects operator precedence by organizing parse functions in a hierarchy. Each level calls the next higher precedence level:
ExprPtr parseExpression() { return parseEquality(); }
// == operator (lowest precedence)
ExprPtr parseEquality() {
ExprPtr expr = parseComparison();
while (match(TokenKind::EqualEqual)) {
std::string op = previous().lexeme;
ExprPtr right = parseComparison();
expr = std::make_unique<BinaryExpr>(op, std::move(expr), std::move(right));
}
return expr;
}
// < > operators
ExprPtr parseComparison() {
ExprPtr expr = parseTerm();
while (check(TokenKind::Less) || check(TokenKind::Greater)) {
advance();
std::string op = previous().lexeme;
ExprPtr right = parseTerm();
expr = std::make_unique<BinaryExpr>(op, std::move(expr), std::move(right));
}
return expr;
}
// + - operators
ExprPtr parseTerm() {
ExprPtr expr = parseFactor();
while (check(TokenKind::Plus) || check(TokenKind::Minus)) {
advance();
std::string op = previous().lexeme;
ExprPtr right = parseFactor();
expr = std::make_unique<BinaryExpr>(op, std::move(expr), std::move(right));
}
return expr;
}
// * / % operators (highest precedence)
ExprPtr parseFactor() {
ExprPtr expr = parseUnary();
while (check(TokenKind::Multiply) || check(TokenKind::Divide) ||
check(TokenKind::Modulo)) {
advance();
std::string op = previous().lexeme;
ExprPtr right = parseUnary();
expr = std::make_unique<BinaryExpr>(op, std::move(expr), std::move(right));
}
return expr;
}
This hierarchy ensures that 2 + 3 * 4 is parsed as 2 + (3 * 4) rather than (2 + 3) * 4, because parseTerm calls parseFactor, which has higher precedence.
Primary Expressions
At the bottom of the precedence hierarchy, we handle the most basic expressions:
ExprPtr parsePrimary() {
// Literals
if (match(TokenKind::Number)) {
int value = std::get<int>(previous().literal);
return std::make_unique<LiteralExpr>(value);
}
if (match(TokenKind::String)) {
std::string value = std::get<std::string>(previous().literal);
return std::make_unique<LiteralExpr>(value);
}
if (match(TokenKind::True)) {
return std::make_unique<LiteralExpr>(true);
}
if (match(TokenKind::False)) {
return std::make_unique<LiteralExpr>(false);
}
// Identifier or function call
if (match(TokenKind::Identifier)) {
std::string name = previous().lexeme;
// Check for function call
if (match(TokenKind::Lpar)) {
std::vector<ExprPtr> args;
if (!check(TokenKind::Rpar)) {
do {
args.push_back(parseExpression());
} while (match(TokenKind::Comma));
}
expect(TokenKind::Rpar, "Expected ')' after arguments");
return std::make_unique<CallExpr>(name, std::move(args));
}
return std::make_unique<IdentifierExpr>(name);
}
// Parenthesized expression
if (match(TokenKind::Lpar)) {
ExprPtr expr = parseExpression();
expect(TokenKind::Rpar, "Expected ')' after expression");
return expr;
}
throw std::runtime_error("Expected expression");
}
Statement Parsing
Statements are simpler than expressions since they don't have precedence rules. Each statement type has its own parsing function:
StmtPtr parseStatement() {
if (match(TokenKind::Define))
return parseFunctionDef();
if (match(TokenKind::Var))
return parseVarDecl();
if (match(TokenKind::If))
return parseIfStmt();
if (match(TokenKind::While))
return parseWhileStmt();
if (match(TokenKind::Return))
return parseReturnStmt();
if (match(TokenKind::LBrace))
return parseBlockStmt();
// Assignment or expression statement
if (check(TokenKind::Identifier)) {
size_t saved = current;
advance();
if (match(TokenKind::Equals)) {
std::string name = tokens[saved].lexeme;
ExprPtr value = parseExpression();
expect(TokenKind::Semicolon, "Expected ';' after assignment");
return std::make_unique<AssignStmt>(name, std::move(value));
}
current = saved; // backtrack
}
return parseExprStmt();
}
Parsing Control Flow
Control flow statements require careful handling of their structure:
// if (condition) statement [else statement]
StmtPtr parseIfStmt() {
expect(TokenKind::Lpar, "Expected '(' after 'if'");
ExprPtr condition = parseExpression();
expect(TokenKind::Rpar, "Expected ')' after if condition");
StmtPtr thenBranch = parseStatement();
StmtPtr elseBranch = nullptr;
if (match(TokenKind::Else)) {
elseBranch = parseStatement();
}
return std::make_unique<IfStmt>(std::move(condition),
std::move(thenBranch),
std::move(elseBranch));
}
// while (condition) statement
StmtPtr parseWhileStmt() {
expect(TokenKind::Lpar, "Expected '(' after 'while'");
ExprPtr condition = parseExpression();
expect(TokenKind::Rpar, "Expected ')' after while condition");
StmtPtr body = parseStatement();
return std::make_unique<WhileStmt>(std::move(condition), std::move(body));
}
Function Definitions
Function parsing is slightly more complex because we need to handle parameter lists:
// define foo(var a, var b) { body }
StmtPtr parseFunctionDef() {
expect(TokenKind::Identifier, "Expected function name");
std::string name = previous().lexeme;
expect(TokenKind::Lpar, "Expected '(' after function name");
std::vector<FunctionParam> parameters;
if (!check(TokenKind::Rpar)) {
do {
bool isMutable = false;
if (match(TokenKind::Var)) {
isMutable = true;
}
expect(TokenKind::Identifier, "Expected parameter name");
std::string paramName = previous().lexeme;
parameters.emplace_back(paramName, !isMutable);
} while (match(TokenKind::Comma));
}
expect(TokenKind::Rpar, "Expected ')' after parameters");
expect(TokenKind::LBrace, "Expected '{' before function body");
StmtPtr body = parseBlockStmt();
return std::make_unique<FunctionDef>(name, std::move(parameters),
std::move(body));
}
Complete Example
Let's trace how this code gets parsed:
var x = 3 + 4 * 2;
if (x > 10) {
return x;
}
graph TD
A[Program] --> B[VarDeclStmt: x]
A --> C[IfStmt]
B --> D[BinaryExpr: +]
D --> E[Literal: 3]
D --> F[BinaryExpr: *]
F --> G[Literal: 4]
F --> H[Literal: 2]
C --> I[BinaryExpr: >]
I --> J[Identifier: x]
I --> K[Literal: 10]
C --> L[BlockStmt]
L --> M[ReturnStmt]
M --> N[Identifier: x]
The parser correctly builds a tree where:
- The variable declaration contains a binary expression with proper precedence
- The if statement has a condition expression and a body
- The block statement contains a return statement
Error Handling
The parser uses a simple expect function to ensure tokens match expectations:
void expect(TokenKind kind, const std::string &message) {
if (check(kind)) {
advance();
return;
}
throw std::runtime_error(message + " at line " +
std::to_string(peek().pos.line));
}
If a token doesn't match, we throw an error with the line number. This could be improved with better error recovery, but for a first implementation it keeps things simple and provides useful diagnostic information.
Why Recursive Descent?
Recursive descent parsers have several advantages:
- They directly mirror the grammar structure
- They're easy to understand and debug
- They handle operator precedence naturally through function call hierarchy
- They're efficient enough for most use cases
The main limitation is that they can't handle left-recursive grammars directly, but our grammar doesn't require left recursion.
Assembly Generation
Now comes the most interesting part: converting our AST into actual x86_64 assembly code that can be executed by the CPU. This is where the rubber meets the road - all our careful parsing work pays off as we translate high-level language concepts into the low-level operations the processor understands.
Why x86_64 Assembly?
x86_64 (also called AMD64 or Intel 64) is the 64-bit version of the x86 instruction set architecture. It's what most modern desktop and server CPUs use. While it's more complex than other architectures like ARM or RISC-V, it's:
- Ubiquitous on desktop/server systems
- Well-documented
- Supported by excellent tools (NASM, GDB)
- Powerful enough to teach important compiler concepts
Assembly Generation Overview
The code generator walks the AST and emits assembly instructions. It needs to handle several concerns:
- Data management - Tracking variables, strings, and functions in separate tables
- Stack frame layout - Storing local variables and managing function calls
- Control flow - Translating if/while statements into jumps
- Function calling - Custom stack-based calling convention
- Expression evaluation - Computing arithmetic and logical operations
Here's the overall flow:
graph TD
A[AST] --> B[Code Generator]
B --> C[Variable Table]
B --> D[Data Table]
B --> E[Function Table]
C --> F[Generate Assembly]
D --> F
E --> F
F --> G[.text section]
F --> H[.data section]
G --> I[NASM Assembler]
H --> I
I --> J[Object File]
J --> K[Linker]
K --> L[Executable]
Core Data Structures
The code generator uses three key tables to track program state:
Variable Table
Tracks all variables in the current scope with their stack offsets:
typedef struct {
u16 rbp_offset; // Offset from RBP
u16 size; // Size in bytes (8 for 64-bit)
string name; // Variable name
void *value; // Runtime value pointer
VarType type; // INT, BOOL, or STRING
string string_label; // Label for string data
bool is_param; // True if function parameter
} Variable;
Parameters live above RBP (at [rbp + offset]) while local variables live below RBP (at [rbp - offset]). The is_param flag determines which addressing mode to use.
Data Table
Manages all string literals in the program:
struct StringData {
string label; // Unique label (e.g., "str_0")
string value; // Actual string content
size_t length; // Length of string
bool is_computed; // True if from concatenation
};
struct Data_table {
vector<StringData> strings;
u32 string_counter = 0;
string add_string(const string &value, bool is_computed = false) {
string label = "str_" + to_string(string_counter++);
strings.emplace_back(label, value, is_computed);
return label;
}
};
Strings are stored in the .data section and referenced by label. This allows compile-time string concatenation!
Function Table
Keeps track of all user-defined functions:
struct FunctionInfo {
string name;
string label; // Assembly label
vector<CodegenFunctionParam> parameters;
VarType return_type;
};
Register Usage Strategy
The code generator uses a simple register allocation strategy:
- RAX - Primary accumulator for all expression results
- RBX - Temporary storage for binary operation left operand
- RCX - Used for division and string length calculations
- RDX - Used for division remainder and syscalls
- RSI/RDI - Syscall arguments (stdout, string pointers, etc.)
- RSP - Stack pointer
- RBP - Base pointer for accessing local variables
The approach is stack-based: evaluate expressions, push results, pop into registers for operations.
Stack Frame Layout
Each function (including _start) establishes a stack frame:
Higher addresses
+------------------+
| Argument 3 | [rbp + 32] (3rd arg)
| Argument 2 | [rbp + 24] (2nd arg)
| Argument 1 | [rbp + 16] (1st arg)
+------------------+
| Return address | [rbp + 8] <-- pushed by CALL
+------------------+
| Saved RBP | [rbp + 0] <-- RBP points here
+------------------+
| Local var 1 | [rbp - 8]
| Local var 2 | [rbp - 16]
| Local var 3 | [rbp - 24]
| ... |
+------------------+ <-- RSP points here
Lower addresses
Function parameters are pushed onto the stack right-to-left before the call. When call executes, it pushes the return address (8 bytes). Then the function prologue executes push rbp (saving the caller's frame pointer at the new stack top) and mov rbp, rsp (establishing the new frame pointer). This means:
- Saved RBP is at
[rbp + 0](where RBP points) - Return address is at
[rbp + 8](pushed by CALL before the prologue) - First parameter is at
[rbp + 16], second at[rbp + 24], etc. (pushed by caller before CALL)
Generating Expressions
Literal Expressions
Literals load values directly into RAX:
void handle_value(string &out, LiteralExpr *v, /* ... */) {
if (holds_alternative<int>(v->value)) {
out += " mov rax, " + to_string(get<int>(v->value)) + "\n";
} else if (holds_alternative<bool>(v->value)) {
bool val = get<bool>(v->value);
out += " mov rax, " + string(val ? "1" : "0") + "\n";
} else if (holds_alternative<string>(v->value)) {
// Add string to data table
string label = data_table.add_string(get<string>(v->value), false);
// Load address of string into rax
out += " lea rax, [rel " + label + "]\n";
}
}
For var x = 42;:
mov rax, 42
mov [rbp - 8], rax
For string literals, we use LEA (load effective address) with RIP-relative addressing to get the address of the string data.
Identifier Expressions (Variable Access)
Variables are loaded from their stack location:
if (var.is_param) {
out += " mov rax, [rbp + " + std::to_string(var.rbp_offset) + "]\n";
} else {
out += " mov rax, [rbp - " + std::to_string(var.rbp_offset) + "]\n";
}
Notice the different signs: parameters use + (above RBP), locals use - (below RBP).
Binary Expressions
Binary operations follow a consistent pattern:
void handle_bin_expr(string &out, BinaryExpr *b, /* ... */) {
// Evaluate left expression
handle_expr(out, b->left.get(), /* ... */);
out += " push rax\n"; // Save left value
// Evaluate right expression
handle_expr(out, b->right.get(), /* ... */);
// Pop left value into rbx
out += " pop rbx\n";
// Perform operation (left in RBX, right in RAX)
if (b->op == "+") {
out += " add rax, rbx\n";
} else if (b->op == "-") {
out += " sub rbx, rax\n";
out += " mov rax, rbx\n"; // Result back to RAX
} else if (b->op == "*") {
out += " imul rax, rbx\n";
} else if (b->op == "/") {
out += " mov rdx, 0\n"; // Clear RDX for division
out += " mov rcx, rax\n"; // Divisor to RCX
out += " mov rax, rbx\n"; // Dividend to RAX
out += " idiv rcx\n"; // Signed divide, quotient in RAX
}
}
For x + 3 * 4:
; Evaluate 3
mov rax, 3
push rax
; Evaluate 4
mov rax, 4
; Multiply: 3 * 4
pop rbx
imul rax, rbx ; RAX = 12
push rax
; Load x
mov rax, [rbp - 8]
; Add x + 12
pop rbx
add rax, rbx
String Concatenation
One cool feature is compile-time string concatenation. If both operands are known at compile time, they're concatenated immediately:
if (b->op == "+" && (left_type == VarType::STRING || right_type == VarType::STRING)) {
// Try to get string values at compile time
if (left_is_known && right_is_known) {
string concatenated = left_str_val + right_str_val;
string label = data_table.add_string(concatenated, true);
out += " lea rax, [rel " + label + "]\n";
return;
}
// Runtime concatenation not implemented yet
out += " ; ERROR: Runtime string concatenation not yet implemented\n";
out += " xor rax, rax\n";
}
So "Hello" + " " + "World" becomes a single string literal in the data section!
Comparison Operations
Comparisons use the cmp instruction with conditional set:
else if (b->op == "==") {
out += " cmp rbx, rax\n";
out += " sete al\n"; // Set AL to 1 if equal
out += " movzx rax, al\n"; // Zero-extend to full register
} else if (b->op == "<") {
out += " cmp rbx, rax\n";
out += " setl al\n"; // Set if less than (signed)
out += " movzx rax, al\n";
} else if (b->op == ">") {
out += " cmp rbx, rax\n";
out += " setg al\n"; // Set if greater than (signed)
out += " movzx rax, al\n";
}
Unary Expressions
Unary operators are applied after evaluating the operand:
void handle_un_expr(string &out, UnaryExpr *u, /* ... */) {
// Evaluate operand (result in RAX)
handle_expr(out, u->operand.get(), /* ... */);
if (u->op == "-") {
out += " neg rax\n"; // Two's complement negation
} else if (u->op == "!") {
out += " test rax, rax\n"; // Test if zero
out += " sete al\n"; // Set AL if zero
out += " movzx rax, al\n"; // Extend to full register
}
}
Function Calls
There are two types of function calls: built-ins and user-defined functions.
Built-in print function:
if (call->function == "print") {
// Evaluate argument (string pointer in RAX)
handle_expr(out, call->arguments[0].get(), /* ... */);
out += " mov rsi, rax\n"; // String pointer in RSI
// Calculate string length using repne scasb which is basically the assembly version of strlen
out += " mov rdi, rax\n"; // Copy pointer
out += " xor rcx, rcx\n"; // Counter = 0
out += " dec rcx\n"; // RCX = -1 (0xFFFFFFFFFFFFFFFF) which is basically the max length to scan
out += " xor al, al\n"; // Search for \0
out += " repne scasb\n"; // Scan until we find \0
out += " not rcx\n"; // Invert RCX
out += " dec rcx\n"; // Subtract 1
out += " mov rdx, rcx\n"; // Length in RDX
// write(1, rsi, rdx) syscall
out += " mov rax, 1\n"; // sys_write
out += " mov rdi, 1\n"; // stdout
out += " syscall\n";
}
This uses the repne scasb instruction to find the null terminator, which is a clever way to get the string length!
User-defined functions:
// Push arguments right-to-left
for (auto it = call->arguments.rbegin(); it != call->arguments.rend(); ++it) {
handle_expr(out, it->get(), /* ... */);
out += " push rax\n";
}
// Call the function
out += " call " + func_info->label + "\n";
// Caller cleans up stack
if (!call->arguments.empty()) {
out += " add rsp, " + to_string(call->arguments.size() * 8) + "\n";
}
This is a stack-based calling convention where all arguments are passed on the stack (not in registers like System V ABI).
Generating Statements
Variable Declarations
Variables are allocated on the stack:
void handle_stmt(/* VarDeclStmt case */) {
// Evaluate initializer
handle_expr(out, var_decl->initializer.get(), /* ... */);
// Calculate offset based on number of existing local variables
int local_var_count = count_non_param_vars(var_table);
Variable var;
var.name = var_decl->name;
var.rbp_offset = (local_var_count + 1) * 8;
var.type = get_expr_type(var_decl->initializer.get(), var_table);
var.is_param = false;
var_table.table.push_back(var);
// Store to fixed offset
out += " mov [rbp - " + std::to_string(var.rbp_offset) + "], rax\n";
}
If Statements
If statements use test and conditional jumps:
void handle_stmt(/* IfStmt case */) {
string else_label = ctx.generate_label("else");
string end_label = ctx.generate_label("endif");
// Evaluate condition
handle_expr(out, if_stmt->condition.get(), /* ... */);
// Jump if zero (false)
out += " test rax, rax\n";
if (if_stmt->elseBranch) {
out += " jz " + else_label + "\n";
} else {
out += " jz " + end_label + "\n";
}
// Then branch
handle_stmt(out, if_stmt->thenBranch.get(), /* ... */);
if (if_stmt->elseBranch) {
out += " jmp " + end_label + "\n";
out += else_label + ":\n";
handle_stmt(out, if_stmt->elseBranch.get(), /* ... */);
}
out += end_label + ":\n";
}
While Loops
While loops use labels and conditional jumps:
void handle_stmt(/* WhileStmt case */) {
string loop_start = ctx.generate_label("while_start");
string loop_end = ctx.generate_label("while_end");
out += loop_start + ":\n";
// Evaluate condition
handle_expr(out, while_stmt->condition.get(), /* ... */);
// Test if false (0)
out += " test rax, rax\n";
out += " jz " + loop_end + "\n";
// Loop body
handle_stmt(out, while_stmt->body.get(), /* ... */);
// Jump back
out += " jmp " + loop_start + "\n";
out += loop_end + ":\n";
}
Return Statements
Return statements differ between functions and main:
void handle_stmt(/* ReturnStmt case */) {
if (return_stmt->value) {
handle_expr(out, return_stmt->value.get(), /* ... */);
} else {
out += " xor rax, rax\n"; // Return 0
}
if (ctx.in_function) {
// Return from function
out += " mov rsp, rbp\n";
out += " pop rbp\n";
out += " ret\n";
} else {
// Exit from main
out += " mov rdi, rax\n"; // Exit code
out += " mov rsp, rbp\n";
out += " pop rbp\n";
out += " mov rax, 60\n"; // sys_exit
out += " syscall\n";
}
}
Function Definitions
Functions get their own stack frames:
string generate_function(FunctionDef *func_def, /* ... */) {
string out;
string func_label = ctx.generate_function_label(func_def->name);
out += func_label + ":\n";
out += " push rbp\n";
out += " mov rbp, rsp\n";
// Count local variables to allocate stack space
int local_var_count = count_local_vars(func_def->body.get());
if (local_var_count > 0) {
out += " sub rsp, " + to_string(local_var_count * 8) + "\n";
}
// Add parameters to the variable table
// Parameters are at [rbp + 16], [rbp + 24], etc.
for (size_t i = 0; i < func_def->parameters.size(); i++) {
Variable param_var;
param_var.name = func_def->parameters[i].name;
param_var.rbp_offset = 16 + i * 8; // First param at [rbp + 16]
param_var.is_param = true;
local_var_table.table.push_back(param_var);
}
// Generate function body
ctx.in_function = true;
handle_stmt(out, func_def->body.get(), local_var_table, /* ... */);
ctx.in_function = false;
// Default epilogue
out += " xor rax, rax\n";
out += " mov rsp, rbp\n";
out += " pop rbp\n";
out += " ret\n\n";
return out;
}
For define add(var a, var b) { return a + b; }:
func_add:
push rbp
mov rbp, rsp
sub rsp, 0 ; No local variables
; a is at [rbp + 16], b is at [rbp + 24]
mov rax, [rbp + 16] ; Load a
push rax
mov rax, [rbp + 24] ; Load b
pop rbx
add rax, rbx ; a + b
mov rsp, rbp
pop rbp
ret
The Data Section
String literals are emitted in the .data section:
string generate_data_header(const Data_table &data_table) {
if (data_table.strings.empty()) {
return "";
}
string data = "\nsection .data\n";
for (const auto &str : data_table.strings) {
data += " " + str.label + ": db ";
// Handle empty strings
if (str.value.empty()) {
data += "0\n";
data += " " + str.label + "_len equ 0\n";
continue;
}
bool in_string = false;
bool first_part = true;
// Process each character
for (char c : str.value) {
bool is_special = false;
int byte_val = 0;
// Check for special characters
switch (c) {
case '\n': is_special = true; byte_val = 10; break;
case '\t': is_special = true; byte_val = 9; break;
case '\"': is_special = true; byte_val = 34; break;
default: break;
}
if (is_special) {
// Close current string if open
if (in_string) {
data += "\"";
in_string = false;
}
// Add separator if not first part
if (!first_part) {
data += ", ";
}
// Add the numeric byte value
data += to_string(byte_val);
first_part = false;
} else {
// Regular character
if (!in_string) {
if (!first_part) {
data += ", ";
}
data += "\"";
in_string = true;
first_part = false;
}
data += c;
}
}
// Close string if still open
if (in_string) {
data += "\"";
}
// Add null terminator
data += ", 0\n";
data += " " + str.label + "_len equ $ - " + str.label + " - 1\n";
}
return data;
}
This generates entries like:
section .data
str_0: db "Hello, World!", 10, 0
str_0_len equ $ - str_0 - 1
Notice how the string is output as a quoted string "Hello, World!", then the special character \n is output as its numeric byte value 10, followed by the null terminator 0.
Complete Program Structure
The final assembly is structured as:
string generate_asm_program(const Program &program, /* ... */) {
// First pass: generate function definitions
for (const auto &stmt : program.statements) {
if (auto* func_def = dynamic_cast<FunctionDef*>(stmt.get())) {
func_table.add_function(func_def->name, /* ... */);
functions_code += generate_function(func_def, /* ... */);
}
}
// Generate _start (main)
out += " push rbp\n";
out += " mov rbp, rsp\n";
// Allocate space for main's local variables
int local_var_count = count_local_vars(program);
if (local_var_count > 0) {
out += " sub rsp, " + to_string(local_var_count * 8) + "\n";
}
// Generate main code
for (const auto &stmt : program.statements) {
if (!dynamic_cast<FunctionDef*>(stmt.get())) {
handle_stmt(out, stmt.get(), /* ... */);
}
}
// Exit with last variable's value
out += " mov rdi, [rbp - " + to_string(last_var_offset) + "]\n";
out += " mov rsp, rbp\n";
out += " pop rbp\n";
out += " mov rax, 60\n";
out += " syscall\n";
return out + functions_code;
}
Putting It All Together
For this complete program:
var x = 5;
var y = 3;
if (x > y) {
x = x - y;
}
print("Done!\n");
return x;
The code generator produces:
global _start
section .text
_start:
push rbp
mov rbp, rsp
sub rsp, 16 ; Space for x and y
; var x = 5
mov rax, 5
mov [rbp - 8], rax
; var y = 3
mov rax, 3
mov [rbp - 16], rax
; if (x > y)
mov rax, [rbp - 8] ; Load x
push rax
mov rax, [rbp - 16] ; Load y
pop rbx
cmp rbx, rax
setg al
movzx rax, al
test rax, rax
jz endif_0
; x = x - y
mov rax, [rbp - 8] ; Load x
push rax
mov rax, [rbp - 16] ; Load y
pop rbx
sub rbx, rax ; x - y (result in rbx)
mov rax, rbx ; Move result to rax
mov [rbp - 8], rax ; Store back to x
endif_0:
; print("Done!\n")
lea rax, [rel str_0]
mov rsi, rax
mov rdi, rax
xor rcx, rcx
dec rcx
xor al, al
repne scasb
not rcx
dec rcx
mov rdx, rcx
mov rax, 1
mov rdi, 1
syscall
; return x
mov rax, [rbp - 8]
mov rdi, rax
mov rsp, rbp
pop rbp
mov rax, 60
syscall
section .data
str_0: db "Done!", 10, 0
str_0_len equ $ - str_0 - 1
Assembling and Linking
Once we have the assembly file, we use NASM and ld:
# Compile Fent source to assembly
./fentc source.fent -o output.asm
# Assemble to object file
nasm -f elf64 output.asm -o output.o
# Link to create executable
ld output.o -o program
# Run it
./program
echo $? # Print exit code
The complete pipeline:
graph LR
A[source.fent] -->|Lexer| B[Tokens]
B -->|Parser| C[AST]
C -->|CodeGen| D[output.asm]
D -->|NASM| E[output.o]
E -->|ld| F[executable]
F -->|./program| G[Exit Code]
Design Decisions and Trade-offs
A few interesting choices in this implementation:
- Stack-based calling convention - Simpler than System V ABI (which passes first 6 args in registers), but less efficient since all arguments go on the stack
- Compile-time string concatenation - Clever optimization that works for literals, but runtime concatenation not supported yet
- Separate data tables - Clean separation of concerns, makes tracking strings/functions easier
- RBP-relative addressing - Standard approach, allows dynamic stack allocation
- Single-pass generation - Functions must be defined before they're called (could add forward declarations)
Conclusion
Building a compiler from scratch turned out to be one of the most rewarding projects I've ever done.
The key insight is that compilation is just transformation: source code → tokens → AST → assembly → machine code. Each step is straightforward on its own the complexity comes from putting them all together correctly.
If you're interested in trying this yourself, I highly recommend it. Start small (just integer arithmetic), get that working, then gradually add features. You'll learn an incredible amount about how computers actually work.
What's next?
There's plenty of room for improvement in Fent:
- Runtime string concatenation
- Arrays and structs
- Proper type system with type checking
- Better error messages with line/column information
- Optimization passes (constant folding, dead code elimination, etc.)
- More operators (bitwise, logical AND/OR, etc.)
- For loops and break/continue
- Maybe not make every data type 8 bytes in size
But even in its current simple form, it's fully functional and can compile real programs. And that's pretty satisfying.
The full source code is available on github.
Resources