Crust Programming Language


Crust Programming Language

Maria
Welcome back to our recreation programming session. Today’s project combines two unusual ideas: a deliberately unsafe Rust variant called Crust, and a compiler for the historical B programming language. The goal is not to build a production compiler in one sitting, but to implement a small, working subset and use it to explore how language implementation works.

Corey
Let’s begin with Crust. It is essentially Rust with its safety features intentionally set aside so that the programming style feels closer to C. The main rules are that every function is unsafe, the code uses pointers rather than references, the standard library is avoided in favor of libc, and mutability is the default or at least an optional convention being considered.

Maria
That makes Crust useful as a recreational experiment, especially for C developers who find ordinary Rust too restrictive. But there is an important warning: this style is not recommended for security-critical applications. Removing the borrow checker and relying on raw pointers makes memory-safety mistakes possible, even if a small example happens to run correctly.

Corey
The first Crust experiments included a hello-world program, dynamic arrays, and calls to array-related functions. The larger project was chosen because it would be more interesting than another tiny example: writing a compiler for B, the language created by Ken Thompson before C.

Maria
The name C is connected to B because C followed it historically. B is now genuinely obsolete: unlike languages such as COBOL, it does not have a large body of actively maintained legacy software keeping it alive. There is no clearly established official modern compiler, and the available language reference appears to come from Ken Thompson’s original documentation.

Corey
B resembles C syntactically, but it is much simpler. The material describes B as having essentially one data type: a machine word. Variables are therefore word-sized values rather than explicitly typed integers, characters, floats, and so on. The compiler project consequently uses the target machine’s word size—in this case, 64-bit values for x86-64.

Maria
B also has storage classes. Automatic storage is allocated for each function invocation, which corresponds roughly to stack storage. External storage is allocated before execution and can be shared among functions. Internal storage is local to a function but persists across invocations, similar in spirit to a static local variable in C.

Corey
The keyword auto is interesting here. In B, it identifies automatic storage. In older C, auto also referred to stack-allocated variables, although modern C programmers rarely need to write it because that behavior is normally implicit. In C++, auto later acquired an entirely different meaning related to type deduction.

Maria
The initial B example was intentionally tiny. It declared putchar as an external function, assigned 34 to one variable and 35 to another, and passed their sum to putchar. Since 34 plus 35 equals 69, and ASCII code 69 represents the letter E, printing E became a convenient test for whether the compiler was working.

Corey
The implementation strategy was incremental: start with one very small source program, then add just enough compiler functionality to translate it. After that works, add another feature and expand the supported language. This is a practical way to develop a compiler because every stage leaves you with a concrete, testable result.

Maria
Before the compiler could process B, the Crust executable itself had to be made to run without Rust’s normal runtime. That required a no-std-style setup, an explicit panic handler, external C bindings, object-file output, and a makefile to link the generated object with the required libraries.

Corey
The makefile first produced an object file from the Crust source and then linked that object into an executable. Debug information and optimization settings were added, and the panic behavior was configured to abort. The result was a minimal environment where Crust code could call C functions directly.

Maria
The compiler also needed to read the B source file. Instead of reimplementing file reading immediately, the project reused a C utility library called knob. Its C implementation was compiled separately into an object file, then linked into the Crust executable.

Corey
That required writing foreign-function bindings in Crust. A C string-builder structure was represented with a C-compatible layout, containing a pointer to character data, a count, and a capacity. The binding for read-entire-file accepted a path and a pointer to that structure, filled it with the file contents, and returned a success or failure value.

Maria
The C names used prefixes such as knob_read_entire_file because C has no built-in namespaces. In Crust, the function could be exposed under a module and given a cleaner name through a link-name attribute. That allowed code to call something like knob::read_entire_file while still linking to the actual C symbol.

Corey
Once the file was read, the next compiler phase was lexing. Lexing converts source text into tokens such as identifiers, integer literals, punctuation, and special token codes. The project reused another single-header C library, STB C Lexer, rather than writing a lexer from scratch.

Maria
Using the lexer involved several FFI details. The Crust code had to reproduce the lexer’s structures, including its character types, integer types, token fields, input boundaries, and string storage. The lexer also needed to be initialized with the beginning and end of the source buffer and with storage for identifiers and string-like token data.

Corey
The lexer returned character codes for single-character tokens and larger numeric codes for categories such as identifiers, integer literals, parse errors, and end of file. The compiler printed those tokens while debugging, which made it possible to see whether the B program was being recognized correctly.

Maria
Error reporting was added as the parser grew. A helper could fetch a token, compare it with an expected token, and print a diagnostic when the result differed. The lexer also provided source-location information, such as the file position and line information associated with a token.

Corey
There was a performance caveat: the lexer’s location lookup was described as inefficient because it scans from the beginning of the source. That is acceptable for occasional error reporting, but it would be wasteful to call it for every token. A later improvement was to store the token’s starting location when the token was first encountered.

Maria
The first code-generation target was FASM assembly. The generated file began with an ELF64 format declaration, an executable text section, and external declarations. Functions were emitted as public symbols, and external C functions such as putchar were declared so that the linker could resolve them.

Corey
The project initially experimented with position-independent linking and the procedure linkage table, or PLT. For an external function, FASM can generate a call through the PLT, which is the mechanism used for dynamically linked functions. The alternative was to link without position-independent executable requirements, which simplified this early compiler.

Maria
The generated assembly used the x86-64 calling convention. For the simple putchar call, the character value was placed in the register used for the first integer argument, RDI, and then putchar was called. Returning from main used RAX for the exit code when linking through the C runtime.

Corey
Local B variables were placed on the stack. The compiler emitted a function prologue that saved RBP and copied the current stack pointer into it. Each automatic variable consumed one machine word, or eight bytes on x86-64, and its offset relative to RBP was recorded.

Maria
Recording those offsets required a small table of variables. Each entry stored the variable’s name and its stack offset. At first, the implementation considered using a hash table from STB data structures, but adapting its macro-heavy C interface to Crust looked like a potential rabbit hole, so a simpler dynamic array and linear search were used instead.

Corey
The variable table supported declarations and lookups. When an auto declaration was parsed, the compiler duplicated the name, assigned the next stack offset, increased the total allocation by eight bytes, and stored the result. When a variable was used, the compiler searched the array by name and reported an error if no matching declaration existed.

Maria
The parser handled a small set of top-level forms: external declarations, automatic variables, and identifiers that introduced either assignments or function calls. The early version only supported simple integer assignments and simple variable reads, but that was enough to generate a working program.

Corey
For an assignment such as a equals 69, the compiler looked up the stack offset for a, parsed the integer literal, and emitted an instruction that stored 69 at the corresponding location relative to RBP. For a call such as putchar a, it loaded that stack value into the first argument register and emitted a call instruction.

Maria
At the end of a function, the compiler emitted an epilogue. It restored the stack pointer by adding back the total amount allocated for local variables, restored the saved RBP, placed a zero return value in RAX, and returned. This made the generated function obey the basic structure expected by the C runtime.

Corey
A key bug appeared when multiple functions were added. The variable table and stack offset were accidentally shared across functions, so local variables from one function affected another. The fix was to reset the per-function state when beginning each new function, which mirrors the fact that automatic variables belong to individual function bodies.

Maria
The compiler was then extended from one function to multiple functions. An outer loop parsed functions, while an inner loop parsed the statements inside each function. End-of-file ended the outer loop, and a closing brace ended the current function body.

Corey
Function calls were initially restricted to a single variable argument, and then calls with no arguments were added. That small change demonstrated the general development pattern: identify the next concrete case, adjust the parser and code generator, rebuild, and test the resulting assembly.

Maria
The final demonstration compiled a B program that declared a variable, assigned it a character code, passed it to putchar, and successfully produced the expected character. Multiple functions and recursive calls were also possible by the end, although recursion could overflow the stack because there was no termination condition.

Corey
This was still only a small subset of B. It did not yet provide the full language, complete expressions, conditionals, loops, general argument handling, global variables, or all storage classes. Features such as addition, richer parsing, and more complete code generation would be natural next steps.

Maria
The larger lesson is that a compiler can be built incrementally from very small pieces: read the source, tokenize it, parse one construct, generate assembly for that construct, link it, and test the executable. Reusing C libraries through FFI made the Crust experiment faster, while the deliberately unsafe style kept the implementation close to the machine.

Corey
But the experiment also showed the boundary between recreational and production programming. Crust made low-level integration and pointer manipulation convenient, yet it deliberately gave up protections that matter in real systems. For a toy compiler or local exploration, that tradeoff can be entertaining and educational; for security-sensitive software, the same tradeoff would be dangerous.

Maria
So the episode’s achievement was not a finished B compiler. It was a working foundation: a Crust executable, C-library bindings, file loading, tokenization, diagnostics, parsing of a small B subset, stack-based local variables, function calls, and x86-64 assembly generation.

Corey
And that foundation is exactly what makes the project worth continuing. Once one tiny B program can travel all the way from source text to an executable that prints the expected result, the remaining work becomes a sequence of extensions rather than an entirely unknown problem.

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