1. Home
  2. Explore
  3. Computer Science
  4. Crust Programming Language

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Crust Programming Language

Building a Minimal B Compiler in “Crust”

1. Project Overview

The project develops a small compiler for the B programming language, implemented in a deliberately unsafe dialect of Rust called Crust. The compiler translates a limited subset of B into x86-64 assembly, which is then assembled and linked into an executable.

The implementation proceeds incrementally:

  1. Create a minimal Crust executable.

  2. Interface with C libraries through foreign-function bindings.

  3. Read an entire B source file.

  4. Tokenize the source using a C lexer.

  5. Parse a very small subset of B.

  6. Track local variables and their stack offsets.

  7. Generate x86-64 assembly.

  8. Assemble and link the generated assembly.

  9. Extend the compiler to support multiple functions and function calls.

The central development strategy is to begin with one very small example and gradually add features:

A compiler can be developed by making one concrete program compile first, then progressively adding language features until the implementation approaches the complete language.

The resulting compiler is intentionally incomplete, but it demonstrates the essential structure of a compiler and the relationship between source code, tokens, intermediate decisions, assembly, object files, and executables.


2. The “Crust” Programming Model

2.1 Purpose of Crust

Crust is a recreational variant of Rust designed to make Rust more familiar to C developers by disabling or avoiding many of Rust’s safety-oriented abstractions.

The model emphasizes direct memory manipulation, explicit ABI compatibility, and easy interaction with C libraries. It is not intended for security-critical software.

2.2 Core Rules

The implementation follows four main conventions:

  • Every function is unsafe.

  • Pointers are used instead of references.

  • The standard library is not used.

  • C interoperability is provided through libc and manually declared foreign functions.

The language also uses Rust edition 2021 rather than newer editions because newer editions impose additional restrictions around unsafe operations and external blocks.

2.3 Pointers Rather Than References

Ordinary Rust references are avoided. Instead, functions receive:

  • Constant pointers for data they do not modify.

  • Mutable pointers for data they may modify.

  • Raw pointer operations for dereferencing and address manipulation.

For example, a C-style string is represented conceptually as a pointer to characters:

string≈pointer to char\text{string} \approx \text{pointer to } \text{char}string≈pointer to char

A mutable buffer is represented as a mutable pointer to character storage.

This approach removes borrow-checking constraints but also removes the protections that normally prevent:

  • Dangling pointers.

  • Out-of-bounds access.

  • Use-after-free errors.

  • Data races.

  • Invalid aliasing.

  • Incorrect lifetime management.

2.4 No Standard Library

Without Rust’s standard library, common facilities must be supplied manually or obtained from C libraries. The implementation therefore needs explicit support for:

  • Panic handling.

  • Memory operations.

  • C-compatible integer and character types.

  • String manipulation.

  • File reading.

  • Formatted output.

  • Dynamic arrays.

  • Lexer structures and functions.

This makes the program more verbose at the system boundary, but it also exposes the lower-level mechanisms normally hidden by Rust’s abstractions.

2.5 Panic Handling

A no_std-style executable still requires a panic handler. The compiler provides a minimal handler that aborts the program rather than attempting to unwind the stack.

This is appropriate for a small compiler because:

  • There is no standard runtime available to perform unwinding.

  • The program is not attempting to recover from internal failures.

  • Aborting is simpler than implementing a full panic runtime.


3. The B Programming Language

3.1 Historical Position

B was created by Ken Thompson before the development of C. C’s name reflects its position after B in the alphabet and, historically, in the evolution of these languages.

B can therefore be viewed as a predecessor or conceptual ancestor of C.

3.2 Status of B

Unlike languages such as COBOL, which remain in use because of large legacy codebases, B is effectively obsolete:

  • It is not used in ordinary modern software development.

  • It has no widely used official compiler.

  • Its language specification is difficult to verify.

  • Historical documentation is more important than current implementations.

The available documentation is primarily a user reference describing the language and providing example programs.

3.3 Machine-Word Type System

B has an extremely small type system. The implementation treats its variables as machine words rather than as values with distinct types such as integers, characters, floating-point numbers, or structures.

On an x86-64 target, the compiler chooses a 64-bit word representation:

B word=64-bit machine word\text{B word} = 64\text{-bit machine word}B word=64-bit machine word

This simplifies code generation because every local variable has the same size:

size of each local variable=8 bytes\text{size of each local variable} = 8\text{ bytes}size of each local variable=8 bytes

As a result, a compiler can calculate stack positions using only:

  • The variable’s index or offset.

  • The fixed word size.

  • The base pointer of the current function.

3.4 B Declarations and Storage Classes

B distinguishes several storage classes.

Automatic Storage

Automatic variables are allocated for each function invocation. They correspond closely to ordinary local variables stored in a function’s stack frame.

Their lifetime is:

  1. Allocation occurs when the function is entered or when the declaration is processed.

  2. The variable remains available during the function invocation.

  3. The storage is released when the function returns.

External Storage

External variables are allocated before program execution and can be accessed by multiple functions. An external declaration informs the compiler and linker that a name is defined elsewhere.

An external declaration functions similarly to a declaration of an externally defined symbol in C.

Internal Storage

Internal storage is associated with a function but persists across multiple invocations of that function. This resembles a function-local static variable in C.

The source material describes internal storage as:

  • Local to one function.

  • Available to all invocations of that function.

  • Persistent rather than newly allocated on each call.

3.5 External Declarations

An external declaration has the general purpose of informing the compiler that a named variable or function exists elsewhere.

For example, a B program may declare an external function for character output and later call it:

extern putchar;

The declaration must occur before the first use of the name, and the symbol must be defined externally during linking.

External declarations can also act as forward declarations. A name may be declared before its definition appears later in the source file.

3.6 The auto Keyword

The auto keyword identifies automatic storage. In B, this has a meaningful storage-management role.

In older versions of C, auto also referred to automatic stack allocation. In modern C and C, it is generally unnecessary for local variables because automatic storage is already the default. In modern C, auto has a different meaning: it requests type inference.

The original storage-related meaning is:

  • Allocate the variable in the current function’s stack frame.

  • Make it available during the function call.

  • Release the storage when the function exits.

3.7 Example B Program

A minimal B-style program can:

  1. Declare an external character-output function.

  2. Declare automatic variables.

  3. Assign integer values to those variables.

  4. Add or otherwise manipulate them.

  5. Pass a result to the external function.

A simplified example is conceptually:

extern putchar;

auto a, b;

a = 34;
b = 35;

putchar(a + b);

Because the program uses machine-word values, the expression result is also a machine word. When passed to putchar, it is interpreted as a character code.


4. Incremental Compiler Development

4.1 Start With One Concrete Program

The compiler is not designed from the beginning to support every B feature. Instead, implementation begins with one simple program and adds only the functionality needed to compile it.

The process is:

  1. Choose a minimal source example.

  2. Identify the syntax used by that example.

  3. Implement only enough parsing and code generation for that syntax.

  4. Test the generated program.

  5. Add another feature.

  6. Repeat.

This method reduces the amount of design that must be completed before obtaining a working result.

4.2 Why This Strategy Works

A compiler consists of many interacting components. Implementing the entire language specification at once would require solving all of the following simultaneously:

  • Lexical analysis.

  • Grammar design.

  • Name resolution.

  • Type or word-size handling.

  • Storage allocation.

  • Expression evaluation.

  • Calling conventions.

  • Assembly generation.

  • Linking.

  • Diagnostics.

A small example provides a concrete test for every layer. Once the pipeline works end to end, later changes can be validated against an already functioning system.

4.3 The Initial Target

The first successful target is a B program that:

  • Contains one function.

  • Declares one or more external symbols.

  • Declares automatic variables.

  • Assigns integer literals.

  • Reads a variable.

  • Calls an external function.

This target is deliberately narrow but exercises the entire path from source text to executable machine code.


5. Creating a Minimal Crust Executable

5.1 Required Components

A Crust executable without the standard library requires several elements:

  • A main entry point.

  • A no_std configuration.

  • A no_main configuration when supplying a custom entry strategy.

  • A panic handler.

  • C-compatible external declarations.

  • A build process that emits an object file.

  • A linker command that creates the final executable.

5.2 Object Files and Final Executables

The build process has two main stages.

Stage 1: Compile Source to an Object File

The Crust source is compiled into an object file rather than directly into an executable. The object file contains machine code and unresolved references.

Conceptually:

Crust source→object file\text{Crust source} \rightarrow \text{object file}Crust source→object file

Stage 2: Link Object Files

The object file is linked with required runtime and library objects:

object files+libraries→executable\text{object files} + \text{libraries} \rightarrow \text{executable}object files+libraries→executable

The object-file stage is important because external functions may not be defined in the Crust source itself.

5.3 Linking With the C Runtime

The compiler links with the C runtime to obtain functions such as:

  • putchar.

  • printf.

  • strcmp.

  • File utilities.

  • Other C library services.

Although the source language is B, using the C runtime is historically and technically reasonable because:

  • B influenced C.

  • C inherited many concepts and functions from B.

  • The C runtime still contains functions that B-style programs can use.

  • Linking with the runtime avoids manually implementing system calls.

5.4 Assembly-Level Program Entry

When directly generating assembly, there are two possible approaches:

  • Provide a custom _start symbol and perform system calls manually.

  • Generate a conventional main function and let the C runtime provide startup and shutdown behavior.

The second approach is simpler for the prototype. The C runtime:

  1. Initializes the process.

  2. Calls main.

  3. Receives the return value.

  4. Performs process termination.

On x86-64 System V systems, integer return values are placed in the rax register:

return value→rax\text{return value} \rightarrow \texttt{rax}return value→rax

Thus, returning an exit code can be implemented by moving a value into rax before returning from main.


6. Interfacing With C Libraries

6.1 Foreign Function Interface

The compiler uses a foreign function interface, or FFI, to call C functions from Crust.

An FFI declaration must describe:

  • The external symbol’s name.

  • Its calling convention.

  • Its parameter types.

  • Its return type.

  • Whether the function is unsafe.

  • The symbol name expected by the linker.

The declaration must match the C function’s ABI. A mismatch can cause:

  • Corrupted registers.

  • Incorrect stack usage.

  • Invalid return values.

  • Crashes.

  • Silent data corruption.

6.2 C-Compatible Representations

Structures passed to C must use a C-compatible layout. A representation attribute ensures that fields are arranged according to C layout rules rather than Rust’s default layout rules.

For example, a C-compatible structure may contain:

  • A pointer to an item buffer.

  • A current item count.

  • A capacity value.

A dynamic string buffer can be represented as:

StringBuilder=(items pointer,count,capacity)\text{StringBuilder} = (\text{items pointer}, \text{count}, \text{capacity})StringBuilder=(items pointer,count,capacity)

6.3 C Integer Types

C types do not always map directly to Rust primitive types. The FFI layer therefore uses C-compatible types such as:

  • C character.

  • C integer.

  • C long.

  • C double.

  • C size type.

  • C void.

Using the correct C type matters because the width and signedness of an integer affect the calling convention and memory layout.

6.4 Symbol Renaming

C libraries often use prefixed symbol names to avoid collisions because C does not provide namespaces. For example, a function exposed by a library may actually be named:

knob_read_entire_file

The Crust interface can expose it under a shorter module-level name while preserving the actual linker symbol name through a link-name attribute.

This produces a useful separation:

  • Source-level name: convenient Crust name.

  • Linker-level name: actual C symbol.

6.5 External Header-Only Libraries

A header-only C library cannot necessarily be used directly as Crust code. It must first be compiled as C with its implementation macro enabled.

The process is:

  1. Copy or include the header.

  2. Define the library’s implementation macro.

  3. Compile the header as a C translation unit.

  4. Emit an object file.

  5. Link the object file with the Crust program.

  6. Declare the required functions and structures in Crust.

This approach allows the compiler to reuse C libraries while keeping the main implementation in Crust.


7. Reading the B Source File

7.1 File-Reading Utility

The compiler uses a C utility that reads an entire file into a dynamic string buffer.

The function conceptually has the form:

read_entire_file(path,string builder)→success/failure\text{read\_entire\_file}(\text{path}, \text{string builder}) \rightarrow \text{success/failure}read_entire_file(path,string builder)→success/failure

Its behavior is:

  1. Open the file specified by the path.

  2. Read all bytes.

  3. Store them in a dynamically managed buffer.

  4. Update the buffer’s item count.

  5. Return a success indicator.

If reading fails, the compiler exits with a nonzero status.

7.2 String Builder Representation

The string builder stores:

  • items: pointer to the byte or character buffer.

  • count: number of valid characters.

  • capacity: allocated buffer capacity.

The compiler uses the item count to identify the end of the input:

end of input=items+count\text{end of input} = \text{items} + \text{count}end of input=items+count

This pointer is passed to the lexer as the end boundary.

7.3 Printing the Input

The compiler initially prints:

  • The number of bytes read.

  • The contents of the source file.

This provides an early integration test. Before parsing is attempted, the compiler verifies that:

  • The Crust executable runs.

  • The C library object is linked.

  • The file-reading function works.

  • The string buffer is populated correctly.

  • The compiler can access the buffer contents.


8. Lexical Analysis

8.1 Purpose of a Lexer

A lexer converts source characters into tokens. A token represents a meaningful syntactic unit such as:

  • An identifier.

  • An integer literal.

  • A keyword.

  • A punctuation mark.

  • An operator.

  • End of file.

  • A parse error.

The compiler uses an existing C lexer rather than implementing lexical analysis from scratch.

The compilation pipeline is therefore:

source characters→tokens→syntax analysis→assembly\text{source characters} \rightarrow \text{tokens} \rightarrow \text{syntax analysis} \rightarrow \text{assembly}source characters→tokens→syntax analysis→assembly

8.2 Lexer State

The lexer state contains information such as:

  • The beginning of the input.

  • The current input position.

  • The end of the input.

  • The current token.

  • The current token’s text.

  • The token’s location.

  • Storage for identifiers and string literals.

The lexer must be initialized with:

  1. A pointer to the beginning of the source.

  2. A pointer immediately after the final source character.

  3. Storage for token text or identifiers.

8.3 Token Values

The lexer returns numeric token codes.

Characters below a certain range may be returned directly as their character codes. For example:

  • ( may be returned as its character value.

  • ) may be returned as its character value.

  • ; may be returned as its character value.

  • { and } may be returned directly.

Other tokens use special values defined by the lexer, such as:

  • End of file.

  • Identifier.

  • Integer literal.

  • String literal.

  • Parse error.

A token can therefore be interpreted in two ways:

  1. Character token: the numeric value corresponds directly to punctuation.

  2. Named token: the numeric value corresponds to a lexer-defined category.

8.4 Token Iteration

The basic tokenization loop is:

  1. Request the next token.

  2. Check whether it is end of file.

  3. Inspect or print the token.

  4. Continue until the input is exhausted.

Conceptually:

while get_token(lexer) != end_of_file:
    process current token

The lexer returns a nonzero value when a token is available and zero when the input has ended.

8.5 Character Tokens and Named Tokens

A useful distinction is:

  • If the token value is below the lexer’s named-token range, it is probably a literal character.

  • If it is in the named-token range, it represents a category such as an identifier or integer literal.

For example, an identifier might be represented by a special token code, while a semicolon is represented directly by its character code.

8.6 String Storage

Identifiers and string literals require storage beyond the token code. The lexer writes their text into a provided buffer.

The compiler therefore supplies an identifier or string store, conceptually:

string store=character array of fixed capacity\text{string store} = \text{character array of fixed capacity}string store=character array of fixed capacity

The lexer records the token’s text in that buffer, while the token code identifies what kind of token it is.


9. Lexer Wrapper Module

9.1 Why Use a Wrapper

The C lexer uses long, prefixed names and C-style structures. The Crust implementation wraps these definitions in a module to make them easier to use.

Instead of repeatedly referring to long names, the compiler can expose concise module-level names such as:

  • Lexer.

  • init.

  • get_token.

  • get_location.

  • token.

9.2 C Structure Reproduction

The lexer structure must be reproduced accurately in Crust:

  • Field order must match.

  • Field types must match.

  • Pointer mutability must match.

  • C layout must be preserved.

  • Integer widths must match.

An incorrectly represented structure can cause the C function to read the wrong memory locations.

9.3 Initialization

The lexer initializer receives:

  • A mutable pointer to the lexer object.

  • A pointer to the beginning of the input.

  • A pointer to the end of the input.

  • A pointer to identifier or string storage.

  • The storage capacity.

The initialization procedure is:

  1. Allocate or zero-initialize the lexer structure.

  2. Set the input start pointer.

  3. Set the input end pointer.

  4. Supply storage for token text.

  5. Call the C initializer.

Zero-initialization is useful for C-style structures because many fields have a meaningful null or zero default.


10. Token Expectations and Error Reporting

10.1 Expecting a Specific Token

The parser needs a helper that verifies that the current token has an expected value.

An expectation operation conceptually performs:

  1. Fetch the next token.

  2. Compare it with the expected token.

  3. Continue if the values match.

  4. Report a diagnostic and stop if they differ.

The expected token may be:

  • A punctuation character.

  • A keyword token.

  • An identifier token.

  • An integer-literal token.

10.2 Separate “Get” and “Expect” Operations

The implementation intentionally keeps token retrieval and token validation separate.

get

Retrieves the next token without imposing a particular expectation.

This is useful when:

  • Several different tokens are valid.

  • The parser must inspect the token before deciding what it means.

  • A variable-length list is being parsed.

  • A branch depends on the next token.

expect

Checks that a specific token is present.

This is useful when:

  • The grammar requires a known punctuation mark.

  • A function declaration must contain parentheses.

  • A statement must end with a semicolon.

  • A block must end with a closing brace.

Keeping the operations separate provides flexibility during parsing.

10.3 Diagnostics

An error diagnostic should ideally include:

  • The error message.

  • The source file path.

  • The line number.

  • The character offset.

  • The unexpected token.

  • The expected token.

For example:

expected token 1, but received token 2

A stronger diagnostic adds location information:

source.b:line:offset: expected identifier, but received ';'

10.4 Location Queries

The lexer can provide the location of a token. The implementation distinguishes between:

  • The location of the first character of a token.

  • The location of the last character of a token.

For reporting a variable declaration or use, the first character is generally the most useful location.

10.5 Performance of Location Queries

The lexer’s location function is described as inefficient because it scans the source from the beginning to determine the line and offset.

Therefore:

  • It is appropriate for error reporting.

  • It should not necessarily be called for every token in performance-sensitive code.

  • A better lexer could track line and column incrementally during tokenization.

The compiler later considers storing a token’s location directly rather than repeatedly recomputing it.


11. Parsing the First B Subset

11.1 Supported Constructs

The prototype supports a small subset consisting of:

  • Function definitions.

  • External declarations.

  • Automatic variable declarations.

  • Integer assignments.

  • Variable reads.

  • Function calls.

  • Empty and single-argument function calls.

  • Function bodies delimited by braces.

Unsupported constructs include most of the full B language, including:

  • General expressions.

  • Binary operators beyond the simplest cases.

  • Loops.

  • Conditional statements.

  • Multiple-argument calls.

  • Arrays as full language objects.

  • Complete global-variable handling.

  • Complete type handling.

11.2 Top-Level Parsing

The compiler eventually uses two nested parsing loops:

Outer Loop

The outer loop parses multiple function definitions in a source file.

Inner Loop

The inner loop parses the statements inside one function body.

Conceptually:

while input contains another function:
    parse function declaration
    while function body is not closed:
        parse one statement

This distinction is necessary because a source file can contain several functions, and each function can contain several statements.

11.3 Function Definition Parsing

A minimal function definition is parsed in this order:

  1. Read the function name.

  2. Emit a public symbol declaration.

  3. Emit the function label.

  4. Expect an opening parenthesis.

  5. Expect a closing parenthesis for a no-argument function.

  6. Expect an opening brace.

  7. Parse statements.

  8. Detect the closing brace.

  9. Emit the function epilogue.

The generated assembly begins with a function label and ends with a return sequence.

11.4 Function Names

When the parser encounters a function name, it generates assembly similar to:

public function_name
function_name:

Making the symbol public allows the linker to resolve calls to that function from other parts of the program.

11.5 External Declarations

When the parser encounters extern, it:

  1. Expects an identifier.

  2. Emits an external symbol declaration.

  3. Expects a semicolon.

  4. Continues parsing the next top-level declaration.

The initial implementation supports one external declaration at a time, with multiple external declarations identified as a future extension.

11.6 Automatic Variable Declarations

When the parser encounters auto, it:

  1. Expects a variable identifier.

  2. Computes a new stack offset.

  3. Allocates space for one machine word.

  4. Stores the variable name and offset in a table.

  5. Expects the end of the declaration.

Because each word is 8 bytes, the offsets progress as:

8, 16, 24, 32, …8,\ 16,\ 24,\ 32,\ \ldots8, 16, 24, 32, …

The implementation initially supports a single automatic variable and later adds support for multiple declarations.

11.7 Identifier Statements

When a statement begins with an identifier, the parser must inspect the next token to determine whether the identifier represents:

  • An assignment.

  • A function call.

For example:

a = 69;

is an assignment, while:

putchar(a);

is a function call.

The next token distinguishes the two cases:

  • = indicates assignment.

  • ( indicates a function call.


12. Local Variable Management

12.1 Why Names Must Be Stored

When compiling a variable assignment or read, the compiler must convert a source-level name such as a into a machine-level memory location.

This requires a symbol table containing at least:

  • The variable’s name.

  • The variable’s stack offset.

Conceptually:

variable name→stack offset\text{variable name} \rightarrow \text{stack offset}variable name→stack offset

12.2 Stack Frame Layout

The compiler uses the base pointer, rbp, as a stable reference point for local variables.

A typical function prologue is:

push rbp
mov rbp, rsp

After the prologue:

  • rbp remains fixed during the function.

  • rsp moves downward as local variables are allocated.

  • Local variables are addressed relative to rbp.

If the first local variable has offset 888, its address is conceptually:

address(a)=rbp−8\text{address}(a) = \texttt{rbp} - 8address(a)=rbp−8

The second variable may be located at:

address(b)=rbp−16\text{address}(b) = \texttt{rbp} - 16address(b)=rbp−16

12.3 Why rsp Alone Is Insufficient

The stack pointer changes whenever stack storage is allocated or released. Therefore, its position is not stable enough to serve as the sole reference for local-variable offsets.

The base pointer provides a fixed frame reference:

  • rsp: current top of the stack.

  • rbp: stable base of the current function frame.

12.4 Variable Record

A local-variable record contains information similar to:

AutoVar:
    name
    offset

The compiler later considers adding source-location information as well:

AutoVar:
    name
    offset
    declaration location

This would allow redefinition diagnostics to point to the original declaration.

12.5 Dynamic Array for Variables

The compiler initially considers a hash table but ultimately uses a dynamic array because:

  • The number of local variables is expected to be small.

  • The implementation is simpler.

  • A linear search is adequate for a prototype.

  • It avoids complex macro-based hash-table integration.

A lookup scans the array:

  1. Compare the requested name with each stored name.

  2. Return the matching variable record.

  3. Return a null pointer if no match exists.

The complexity of lookup is:

O(n)O(n)O(n)

where nnn is the number of local variables in the current function.

12.6 String Duplication

Variable names returned by the lexer may reside in reusable lexer storage. The compiler therefore duplicates the name when saving it in the variable table.

This is necessary because the lexer may overwrite its token buffer when reading later tokens.

The general rule is:

If a parser needs a token’s text after the lexer advances, the parser must copy or otherwise preserve that text.

12.7 Function-Local State

The variable table and stack offset must be reset for each function.

If the same table is reused across functions without resetting it:

  • Variables from one function appear to exist in another.

  • Stack offsets accumulate across functions.

  • Variable lookups may resolve to the wrong record.

  • Generated code may access invalid locations.

  • The resulting executable may crash.

Each function therefore needs an independent logical symbol environment.


13. Assignment Code Generation

13.1 Assignment Syntax

The initial compiler supports assignments of integer literals:

a = 69;

The parser performs the following steps:

  1. Read the variable name.

  2. Look up the variable in the local-variable table.

  3. Report an error if it is not declared.

  4. Expect =.

  5. Expect an integer literal.

  6. Expect a semicolon.

  7. Generate a store instruction.

13.2 Generated Store

If variable a has stack offset 888 and the assigned value is 696969, the generated assembly conceptually performs:

mov qword [rbp - 8], 69

This stores the 64-bit machine word in the variable’s stack slot.

13.3 Integer-Literal Limitation

The first implementation accepts only integer literals on the right-hand side of assignments.

Therefore, this is supported:

a = 69;

But a more complex expression such as:

a = b + 34;

is not yet supported.

This limitation is intentional. Expression parsing and expression evaluation are identified as later extensions.


14. Variable Reads and Function Calls

14.1 Variable Read Syntax

The prototype supports passing a local variable as a function argument:

putchar(a);

The compiler:

  1. Reads the function name.

  2. Looks up the function or external symbol.

  3. Parses the opening parenthesis.

  4. Reads the variable name.

  5. Looks up the variable.

  6. Loads its value from the stack.

  7. Places the value in the correct argument register.

  8. Parses the closing parenthesis.

  9. Parses the semicolon.

  10. Emits the call instruction.

14.2 x86-64 System V Calling Convention

On Linux x86-64 systems, the first integer or pointer argument is passed in the rdi register.

Thus, for a one-argument call:

putchar(a);

the generated sequence is conceptually:

mov rdi, qword [rbp - 8]
call putchar

The value stored in the local variable is loaded into rdi before the call.

14.3 Zero-Argument Calls

The compiler is extended to support calls with no arguments:

function();

The parser distinguishes this case by examining the token immediately after the opening parenthesis:

  • A closing parenthesis means there are no arguments.

  • An identifier or other expression begins an argument list.

The generated code for a zero-argument call is simply:

call function

14.4 Multiple Arguments

Multiple arguments are not yet implemented. Supporting them requires:

  1. Parsing a comma-separated argument list.

  2. Evaluating each argument.

  3. Placing arguments in the correct registers.

  4. Handling arguments beyond the register limit on the stack.

  5. Preserving registers according to the ABI.

For the System V AMD64 convention, the first several integer or pointer arguments use registers such as:

  • rdi

  • rsi

  • rdx

  • rcx

  • r8

  • r9

A future implementation would need to map argument position to register or stack location.


15. Function Prologue and Epilogue

15.1 Function Prologue

The function prologue establishes a stack frame:

push rbp
mov rbp, rsp

Its purposes are:

  • Preserve the caller’s base pointer.

  • Create a stable frame reference.

  • Allow local variables to be addressed relative to rbp.

15.2 Local Allocation

For each automatic variable, the compiler subtracts one word from rsp:

sub rsp, 8

After allocating nnn local variables, the total allocation is:

8n bytes8n\text{ bytes}8n bytes

The compiler tracks this amount in a variable such as vars_offset.

15.3 Function Epilogue

When the closing brace of a function is reached, the compiler emits an epilogue:

  1. Restore the stack pointer.

  2. Restore the caller’s base pointer.

  3. Set the return value if necessary.

  4. Return to the caller.

Conceptually:

add rsp, total_local_size
pop rbp
mov rax, 0
ret

The exact instruction sequence may vary, but the essential operation is to undo the prologue’s stack changes.

15.4 Separate Function Stack Accounting

Stack allocation must be tracked independently for each function.

If a function has no local variables, its epilogue must not deallocate the locals belonging to another function. The compiler therefore resets the local-variable table and allocation counter when beginning a new function.


16. Assembly Generation With FASM

16.1 Why Generate Assembly

The compiler uses assembly as its backend because assembly generation is straightforward for a small language:

  • Source constructs map directly to instructions.

  • Stack offsets can be emitted explicitly.

  • Function labels and calls are visible.

  • There is no need to implement a complex intermediate representation initially.

The compilation path is:

B source→generated assembly→object file→executable\text{B source} \rightarrow \text{generated assembly} \rightarrow \text{object file} \rightarrow \text{executable}B source→generated assembly→object file→executable

16.2 Assembly Prologue

The compiler emits an assembly preamble containing directives such as:

  • Output format.

  • Code section declaration.

  • External symbol declarations.

  • Public function declarations.

A typical generated file needs a text section for executable instructions.

16.3 Sections

Assembly output is divided into sections. The executable code belongs in a text or code section.

A section directive may also specify:

  • The section name.

  • Alignment.

  • Permissions or attributes.

Correct section selection is important because the linker must know which regions contain code and which contain data.

16.4 Public and External Symbols

The assembly backend uses:

  • public to export a symbol from the generated object.

  • extern to declare a symbol defined elsewhere.

For a function defined by the compiler:

public main
main:

For a function supplied by the C runtime:

extern putchar

16.5 Position-Independent Code

Position-independent code, or PIC, can execute correctly regardless of where it is loaded in memory.

When calling external functions in ELF environments, position-independent code may use:

  • The procedure linkage table, or PLT.

  • The global offset table, or GOT.

  • Relocations resolved by the linker or dynamic loader.

A call through the PLT can be represented conceptually as:

call putchar@PLT

The exact syntax depends on the assembler.

16.6 PLT and GOT

Procedure Linkage Table

The PLT provides call stubs for external functions. It allows code to call a symbol whose final address may not be known until linking or loading.

Global Offset Table

The GOT stores addresses used by position-independent code. References can be made relative to the GOT rather than to fixed absolute addresses.

The relationship is:

  • The PLT assists external function calls.

  • The GOT assists position-independent address resolution.

  • The linker and loader cooperate to resolve these references.

16.7 Avoiding PIE

The prototype eventually chooses not to use position-independent executable generation in some cases because it simplifies assembly generation.

With non-PIE output:

  • External calls are easier to emit.

  • Absolute or ordinary relocations can be used.

  • The compiler does not need to generate PLT-specific syntax for every external call.

This is a prototype tradeoff rather than a general recommendation. Position independence is important for many production environments, but eliminating it reduces backend complexity.


17. Linking and Testing

17.1 Assembly to Object File

The generated assembly is assembled into an object file:

assembly→object file\text{assembly} \rightarrow \text{object file}assembly→object file

The assembler checks whether:

  • Instructions have valid operand sizes.

  • Labels are defined.

  • Sections are correctly formed.

  • External references are syntactically valid.

17.2 Object File to Executable

The linker combines:

  • The generated object file.

  • C runtime startup code.

  • C library objects.

  • Other required object files.

The result is an executable.

17.3 Operand Sizes

Assembly instructions may require explicit operand sizes. For example, an instruction involving a memory location may need to specify whether the operation is:

  • Byte-sized.

  • Word-sized.

  • Doubleword-sized.

  • Quadword-sized.

A register such as rax implies a 64-bit operation, but a memory operand may not provide enough information by itself. The assembler may therefore report:

operand size not specified

The compiler must emit an explicit size when the assembler cannot infer it.

17.4 Character-Code Testing

The prototype uses character codes to test whether generated code works correctly.

For example, the ASCII code for E is 69:

69→E69 \rightarrow \texttt{E}69→E

If the generated executable prints E, then several stages have worked correctly:

  • The integer literal was parsed.

  • The variable was allocated.

  • The assignment was generated.

  • The variable was loaded.

  • The argument was placed in rdi.

  • The external function was linked.

  • The function was called.

  • The C runtime produced the expected character.

This provides an effective end-to-end test.


18. Supporting Multiple Functions

18.1 Initial Limitation

The first compiler version effectively handled one function. When a second function was added, the compiler produced incorrect output because function-level state was shared.

The main problem was that:

  • The local-variable table was shared.

  • The stack allocation offset was shared.

  • The parser did not have an outer loop for functions.

18.2 Nested Parsing Loops

The solution is to introduce:

  • An outer loop for functions.

  • An inner loop for statements in each function body.

The structure is:

while not end of file:
    parse one function
    reset function-local state
    while not end of function:
        parse one statement

18.3 Function State Reset

At the beginning of each function, the compiler resets:

  • The local-variable array.

  • The local-variable count.

  • The stack allocation offset.

  • Any function-specific labels or metadata.

This ensures that each function has an independent stack frame and symbol environment.

18.4 Function Termination

The parser identifies the end of a function when it reads the closing brace. It then:

  1. Emits the epilogue.

  2. Breaks out of the statement loop.

  3. Returns to the outer function loop.

  4. Attempts to parse the next function.

At end of file, the outer loop terminates.

18.5 Recursion

Once functions can call one another, recursion becomes possible even without explicit loop constructs.

For example:

main() {
    main();
}

This is syntactically compilable but causes unbounded stack growth:

each recursive call→new stack frame\text{each recursive call} \rightarrow \text{new stack frame}each recursive call→new stack frame

Eventually, the process encounters stack exhaustion or a stack overflow.

This demonstrates that recursion is not a special compiler feature. It naturally emerges from ordinary function calls and stack-frame creation.


19. Handling Redefinitions and Undeclared Variables

19.1 Duplicate Declarations

The compiler detects duplicate automatic-variable declarations.

For example:

auto a;
auto a;

The second declaration is rejected because the name already exists in the current function’s variable table.

The lookup process is:

  1. Search the existing local-variable array.

  2. Compare each stored name.

  3. If a match is found, report a redefinition.

  4. Otherwise, allocate a new stack slot.

19.2 Undeclared Variable Use

A variable read or assignment must refer to a previously declared variable.

For example:

putchar(c);

is invalid if c has not been declared.

The compiler reports:

  • The fact that the variable cannot be found.

  • The location where the name was used.

  • The name being searched for.

19.3 Original Declaration Location

A future enhancement is to store the declaration location inside each variable record. Then a duplicate declaration could report both:

  • Where the duplicate occurred.

  • Where the original declaration occurred.

This produces a more helpful diagnostic:

variable 'a' was redefined here;
originally declared there

20. Dynamic Arrays Versus Hash Tables

20.1 Hash Table Attempt

The compiler considers using a C single-header hash-table library. Such libraries often rely heavily on macros.

Using them from Crust would require:

  • Compiling the C implementation.

  • Reproducing its structures.

  • Declaring helper functions.

  • Porting or recreating macros.

  • Handling generic pointer-based storage.

  • Reproducing C’s type-erasure techniques.

20.2 Why the Hash Table Is Abandoned

The hash-table approach is set aside because:

  • The macro layer is cumbersome to reproduce.

  • The compiler’s symbol tables are small.

  • Linear search is sufficient for the prototype.

  • Simpler code makes debugging easier.

20.3 Linear Search

A dynamic array provides a straightforward alternative:

for each variable:
    if names match:
        return variable
return not found

This has O(n)O(n)O(n) lookup complexity, but for a small function with a few local variables, the cost is negligible.

The choice illustrates an important engineering principle:

A theoretically faster data structure is not automatically the best choice when the simpler structure is fast enough for the actual workload.


21. Rust and Crust Type-System Friction

21.1 References and Slices

A slice is conceptually a pair:

(pointer,length)(\text{pointer}, \text{length})(pointer,length)

However, ordinary Rust slices are tied to Rust’s reference and ownership model. Avoiding references makes normal slice usage awkward in Crust.

A manually represented slice can instead be treated as a structure containing:

  • A raw pointer.

  • A length.

This mirrors the underlying representation more directly.

21.2 Raw-Pointer Slice Construction

The implementation considers constructing a pointer-based view from:

  • A data pointer.

  • A length.

This is useful for iterating over dynamic-array storage without using references. However, it introduces additional unsafe operations and type conversions.

21.3 Copying Lightweight Records

When a variable record is returned from a lookup, the implementation must decide whether to:

  • Return a pointer.

  • Return a copied value.

  • Return a reference.

  • Return an optional representation.

Because references are avoided, lightweight records may be copied directly. If a record contains pointers, copying the record copies the pointer values, not the pointed-to data.

21.4 Visibility

Crust retains Rust’s visibility rules. Structures, fields, functions, modules, and enum types may need to be explicitly public when accessed across module boundaries.

This creates friction in a low-level prototype because C-style code often assumes that declarations are accessible once included.

21.5 Unused-Item Warnings

Rust can warn about unused functions, fields, imports, enum variants, or variables. In a compiler under construction, many definitions are added before they are used, so warnings can become noisy.

Excessive warnings may reduce their usefulness because developers may begin ignoring them. The implementation therefore distinguishes between:

  • Warnings that identify genuine mistakes.

  • Warnings caused by intentionally incomplete features.

  • Warnings caused by scaffolding that will be used later.

21.6 Unsafe Operations Inside Unsafe Functions

Newer Rust editions may require unsafe operations to be enclosed in explicit unsafe blocks even inside functions already declared unsafe.

The reasoning is that an unsafe function serves two separate purposes:

  1. It tells callers that invoking the function requires safety obligations.

  2. It permits unsafe operations inside the function.

Newer rules separate these responsibilities, requiring explicit marking of the individual unsafe operations as well.

For a Crust dialect intended to make unsafe programming concise, this distinction is viewed as unnecessary overhead, so the implementation uses an edition with less restrictive behavior.


22. Compiler Architecture

The prototype gradually develops the following architecture.

22.1 Input Layer

The input layer:

  • Receives a source-file path.

  • Reads the entire file.

  • Stores its contents in a dynamic buffer.

22.2 Lexical Layer

The lexical layer:

  • Initializes the C lexer.

  • Converts source characters to tokens.

  • Stores identifier and literal text.

  • Tracks token positions.

22.3 Parsing Layer

The parser:

  • Reads top-level function definitions.

  • Parses declarations.

  • Parses function bodies.

  • Distinguishes assignments from calls.

  • Validates required punctuation.

  • Reports syntax errors.

22.4 Symbol-Management Layer

The symbol-management layer:

  • Records automatic variables.

  • Associates names with stack offsets.

  • Detects redefinitions.

  • Resolves variable uses.

  • Maintains function-local scope.

22.5 Code-Generation Layer

The backend emits:

  • Assembly sections.

  • External declarations.

  • Public symbols.

  • Function labels.

  • Stack-frame setup.

  • Variable allocation.

  • Loads and stores.

  • Calls.

  • Function epilogues.

22.6 Build Layer

The build system:

  1. Compiles Crust source to an object file.

  2. Compiles C library implementations to object files.

  3. Assembles generated assembly.

  4. Links all object files with the C runtime.

  5. Produces the final executable.


23. Important Design Decisions

23.1 Use Existing C Components

Reusing C libraries provides working implementations of:

  • File reading.

  • Lexical analysis.

  • String handling.

  • C-compatible utilities.

The cost is the need to manually reproduce C declarations and layouts in Crust.

23.2 Use Fixed-Size Machine Words

Treating all B values as 64-bit machine words simplifies:

  • Stack allocation.

  • Offset computation.

  • Assignment.

  • Register usage.

  • Calling conventions.

The cost is that the compiler does not yet support meaningful type distinctions.

23.3 Use Stack Allocation for Automatic Variables

Stack allocation is appropriate because B’s auto variables are function-local and have invocation-based lifetimes.

It also makes code generation simple:

  • Allocate by decrementing rsp.

  • Address variables relative to rbp.

  • Release all local storage in the epilogue.

23.4 Use a Linear Symbol Table

A dynamic array and linear search are sufficient for a small compiler. This avoids premature complexity while preserving a clear path toward later optimization.

23.5 Generate Direct Assembly

Direct assembly generation allows the compiler to demonstrate the complete compilation path without implementing an intermediate representation or optimizer.

The resulting code is not necessarily optimal, but it is easy to understand and debug.


24. Current Limitations and Natural Extensions

The prototype successfully demonstrates a minimal end-to-end compiler, but many features remain to be implemented.

24.1 Expression Parsing

The compiler currently accepts only simple integer assignments and variable reads. A complete expression parser would need to support:

  • Binary arithmetic.

  • Operator precedence.

  • Parenthesized expressions.

  • Unary operators.

  • Temporary values.

  • Register allocation or temporary stack slots.

For example:

a = b + 34;

requires loading both operands, performing addition, and storing the result.

24.2 Multiple Arguments

Function calls with multiple arguments require:

  • Comma-separated argument parsing.

  • ABI register assignment.

  • Stack arguments after the register limit.

  • Preservation of caller- and callee-saved registers.

24.3 Global Variables

Global variables require a static data section rather than stack allocation. The compiler would need to:

  • Distinguish global and local declarations.

  • Emit data-section definitions.

  • Resolve global names across functions.

  • Support initialization.

  • Handle external global symbols.

24.4 Arrays

Although B supports arrays, the compiler does not yet implement their complete semantics. Arrays would require:

  • Storage allocation.

  • Index expressions.

  • Address calculation.

  • Element loads and stores.

  • Array initialization.

24.5 Control Flow

The language subset lacks:

  • if statements.

  • Loops.

  • Conditional branches.

  • Labels generated from structured control flow.

  • Boolean expressions.

Control flow would require generating labels and branch instructions.

24.6 Complete Diagnostics

Diagnostics can be improved by storing:

  • Token locations directly.

  • Declaration locations.

  • Function names.

  • Expected grammar categories rather than only numeric token codes.

  • Contextual information about the active function.

24.7 Self-Hosting

A long-term goal could be a self-hosted B compiler: a compiler written in B that compiles B programs. That would require implementing enough of B to compile the compiler itself and establishing a bootstrap chain.

24.8 Optimization

The current compiler emits straightforward code and does not optimize repeated assignments or expressions. Future optimizations could include:

  • Constant folding.

  • Dead-store elimination.

  • Register allocation.

  • Removal of unnecessary loads and stores.

  • Common-subexpression elimination.


25. Key Takeaways

B is a historically important predecessor to C with a very small, machine-word-oriented language model.

A compiler can be built incrementally by compiling one concrete example and extending the implementation feature by feature.

Crust demonstrates how a Rust-like language can be used as a low-level C-interoperable systems language when references, the standard library, and safety checks are avoided.

The compiler’s central mapping is from source-level names to stack offsets:

variable name→offset from rbp\text{variable name} \rightarrow \text{offset from } \texttt{rbp}variable name→offset from rbp

The complete prototype pipeline is:

B source→file buffer→tokens→parsed constructs→x86-64 assembly→object file→linked executable\text{B source} \rightarrow \text{file buffer} \rightarrow \text{tokens} \rightarrow \text{parsed constructs} \rightarrow \text{x86-64 assembly} \rightarrow \text{object file} \rightarrow \text{linked executable}B source→file buffer→tokens→parsed constructs→x86-64 assembly→object file→linked executable

The most important practical lesson is that a small compiler does not need to begin with a complete language implementation. A functioning lexer, parser, symbol table, stack-frame strategy, and assembly backend are enough to produce a working executable, after which additional language features can be added systematically.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent