- Rust 100%
camllight #
camllight is a native code compiler for the Caml Light programming
language, written in Rust. It compiles Caml Light source files into standalone
native executables through LLVM 20 and links them with a non-moving mark-sweep
garbage collector. The compiler front end, typechecker, and intermediate passes
are dependency-free; only the LLVM backend uses llvm-sys.
The project is organised as a full compilation pipeline rather than a standalone parser:
- Front end — a hand-written lexer and recursive-descent parser produce a
source-spanned, syntax-only AST. Expression, pattern, and type precedence
uses Pratt parsing, with binding powers that mirror the
%left/%rightdeclarations in Caml Light's ownsrc/compiler/parser.mly. - Typechecking — a Hindley–Milner inference engine checks the AST and records an inferred type for every expression.
- LMLI lowering — typed source is converted to LMLI, the typed intermediate language from Tarditi's thesis, then alpha-renamed, converted to A-normal form, reified, and closure-converted.
- U-Bform lowering — types are erased, runtime constructor tags and representations are materialised, and closures and calls are lowered to a type-erased B-form.
- Native code generation — U-Bform is translated to LLVM IR, including precise garbage-collection roots, read and write barriers, global-root registration, and exception hooks. The result is linked into a native executable.
The crate also exposes each stage as a library API, so the lexer, parser, typechecker, and intermediate representations can be reused by interpreters, analyzers, formatters, and other tools.
Building #
cargo build --release
cargo test
Building requires LLVM 20 for llvm-sys. Set LLVM_SYS_201_PREFIX if the LLVM
installation is not found automatically. The release compiler is
target/release/camllight. Rust 1.82 or newer is required.
Command-line usage #
camllight [OPTIONS] [FILE]
FILE is read as Caml Light source; when it is omitted, input is read from
standard input. A file whose name ends in .mli is parsed as an interface, and
any other file as an implementation. Use --interface or --impl to override
this.
| Option | Meaning |
|---|---|
-a, --ast |
Print the abstract syntax tree |
-t, --tokens |
Print the token stream |
-T, --typecheck |
Typecheck with the standard Caml Light environment |
-c, --compile |
Compile and link a native executable |
-r, --run |
Compile to a temporary executable and run it |
-o, --output FILE |
Output path for --compile |
--emit-obj FILE |
Also write the generated native object file |
--emit-llvm FILE |
Also write textual LLVM assembly |
-i, --interface |
Parse as a module interface (.mli) |
--impl, --implementation |
Parse as a module implementation (.ml) |
-q, --quiet |
Only report errors |
-h, --help |
Print help |
Examples:
# Check a file and print a one-line summary
cargo run -q -- Camllight/examples/grep/expr.ml
# Inspect the token stream or pretty-print the AST
cargo run -q -- --tokens Camllight/examples/grep/expr.ml
cargo run -q -- --ast Camllight/examples/grep/expr.mli
# Typecheck with the standard Caml Light environment
cargo run -q -- --typecheck Camllight/examples/grep/expr.ml
# Parse standard input
echo 'let square x = x * x;;' | cargo run -q -- --quiet
# Compile a source file to a native executable and run it
cargo run -q -- --compile hello.ml --output hello
./hello
# Compile and run in one step, leaving no temporary files
cargo run -q -- --run hello.ml
--compile and --run take a program through the whole pipeline (front end,
typechecking, LMLI passes, U-Bform, LLVM) and link it with the mark-sweep
collector in src/gc.rs using the C compiler named by CC (default cc).
#open "name" loads name.mli for the signature and links name.o; when no
object file exists, the driver compiles name.ml to name.o first. Module
initializers run in dependency order before the program's own bindings. See
Modules and #open.
Set CAML_GC_STATS=1 to print collector statistics, including
live_objects=0, when the generated program exits normally. The same line
reports peak_live_objects and peak_live_bytes; CAML_GC_THRESHOLD sets a
fixed allocation threshold, and CAML_GC_STRESS=1 collects before every
allocation.
Successful checks print a summary unless --quiet is used. Errors are written
to standard error with a line:column location and cause exit status 1; invalid
command-line usage exits with status 2.
Compilation pipeline #
Caml Light source
│ lexer + recursive-descent parser
▼
syntax-only AST
│ Hindley–Milner typechecking
▼
per-expression type table
│ AST-to-LMLI conversion, alpha renaming, ANF conversion,
│ reification, closure conversion
▼
closure-converted LMLI
│ type erasure and representation selection
▼
U-Bform
│ LLVM lowering, GC roots and barriers, exception hooks
▼
native object
│ link with libcamllight_gc.a
▼
standalone executable
The parser itself remains syntax-only: it does not type-check or resolve names. Constructor resolution, record-field resolution, and type inference happen in the typechecker. Unsupported source constructs produce a spanned diagnostic instead of a guessed translation.
Library usage #
The crate exposes the front end as a library as well as the full compiler pipeline.
use camllight::{parse_expression, parse_implementation, ExprKind};
let expr = parse_expression("1 + 2 * 3").unwrap();
match expr.kind {
ExprKind::Infix { operator, .. } => assert_eq!(operator, "+"),
_ => unreachable!(),
}
let phrases = parse_implementation("let twice f x = f (f x);;").unwrap();
assert_eq!(phrases.len(), 1);
Main parsing entry points:
parse_implementation(&str) -> Result<Vec<ImplPhrase>, ParseError>parse_interface(&str) -> Result<Vec<IntfPhrase>, ParseError>parse_expression(&str) -> Result<Expr, ParseError>parse_pattern(&str) -> Result<Pattern, ParseError>parse_type(&str) -> Result<TypeExpr, ParseError>lex(&str) -> Result<Vec<Token>, ParseError>
The single-item helpers accept an optional trailing ;;.
For lower-level use, Lexer and Parser are public. Caml Light sources are
usually Latin-1 rather than UTF-8, so decode_source(&[u8]) is provided: it
keeps valid UTF-8 unchanged and otherwise maps each byte to the code point of the
same value.
Every AST node carries a Span with 1-based start/end line and column
information. ParseError exposes a message and the span where parsing failed.
Typechecking #
The typechecker is separate from the parser and takes an explicit environment.
standard_environment() provides the usual Caml Light values, operators,
constructors, and standard-library functions.
use camllight::{
elaborate, parse_expression, standard_environment, Type,
};
let expression = parse_expression("let id x = x in id 1").unwrap();
let mut environment = standard_environment();
let mut types: Vec<Type> = Vec::new();
let ty = elaborate(&expression, &mut environment, &mut types).unwrap();
assert_eq!(ty, Type::int());
The Vec<Type> is indexed by ExprId. It is extended with Type::Unknown if
needed, and a successful elaboration fills every expression it reaches.
Typechecker entry points:
elaborate(&ast::Expr, &mut Environment, &mut Vec<Type>) -> Result<Type, TypeError>elaborate_implementation(&[ast::ImplPhrase], &mut Environment, &mut Vec<Type>) -> Result<(), TypeError>elaborate_interface(&[ast::IntfPhrase], &mut Environment, &mut Vec<Type>) -> Result<(), TypeError>Elaborator::new(&mut Environment, &mut Vec<Type>)for a reusable inference statestandard_environment() -> Environmentfor the standard Caml Light bindings
Inference uses the level-based generalization algorithm from
Oleg Kiselyov's sound_eager.ml,
applies the Caml Light value restriction, and resolves nominal variants,
records, exceptions, mutable fields, references, vectors, strings, and streams.
Stream parsers are not yet elaborated. See
docs/typechecking.md for details.
Compiler passes #
The typed AST can be lowered through the same passes used by the compiler driver:
convert_implementation_with_constructors— AST to LMLIalpha_rename— remove shadowing before later passesanf_convert— convert LMLI to A-normal formreify— compute GC traces and runtime constructor descriptorsclosure_convert— lower functions and closuresubform_lower— erase types and select runtime representationsllvm_lower— emit a verified LLVM moduleLlvmModule::write_object— write a native object file
See AGENTS.md and the documentation index for the full API and the invariants of each pass.
Precedence #
Binding powers increase from the lowest-precedence operators at the top of the table to the tightest-binding operations at the bottom.
| Binding | Operators | Associativity |
|---|---|---|
| lowest | where |
right |
; (sequence) |
right | |
:=, <- |
right | |
, (tuple) |
left | |
or, || |
left | |
&, && |
left | |
not |
prefix | |
comparisons and INFIX0: =, ==, <>, !=, <, <=, >, >=, and other operators beginning with = < > | & ~ $ |
left | |
concatenation (@, ^) and other INFIX1 operators |
right | |
:: |
right | |
additive (+, -, +., -.) and other INFIX2 operators, including lor, lxor |
left | |
multiplicative (*, /, *., /.), mod, quo, land, and other INFIX3 operators |
left | |
exponentiation (**, **.) and INFIX4 operators, including lsl, lsr, asr |
right | |
unary minus (-, -.) |
prefix | |
user-defined infix operators (installed with #infix) |
left | |
| function application | n/a | |
| tightest | field access and indexing: ., .(, .[ |
left |
prefix operators such as ! and ? |
prefix |
Patterns use their own precedence, from loosest to tightest: as, |, ,,
::. Type expressions are parsed recursively with right-associative -> and
tuples; type application binds tighter than both.
The lexer classifies operators by their first character into the INFIX0–INFIX4
families, matching Caml Light's lexer. Operators declared dynamically with
#infix fall back to a generic precedence.
Supported syntax #
The front end covers the Caml Light language as described by the reference manual and implemented in this distribution, including extensions:
- Core expressions: constants, identifiers, application, prefix and infix
operators, tuples, lists, arrays, records, field access, vector/string
indexing, sequences,
let/let rec,if,while,for,match,try,function,fun, type constraints,where, and assignments. - Patterns: wildcards, constants, variables, constructor application, tuples,
lists, records, arrays, or-patterns, aliases (
as), and range patterns. - Types: type variables, arrows, tuples, type constructors and application, plus type declarations with variants, records, and mutable fields.
- Streams and parsers: stream expressions
[< ... >],parser/match ... with parsercases, stream patterns, and guards. - Declarations and interfaces:
let,type,exception,valuedeclarations (including primitive slot/name annotations), and#directives such as#openand#infix. - Alternate function-binding syntax, user-defined operators, nested comments, string escapes, and Latin-1 source files.
The parser does not perform constructor resolution. Uppercase and lowercase
identifiers are preserved as written, and contextual rules decide where an
identifier may act as a constructor (for example, in match cases versus
let f x = ...). This keeps the AST independent of the type environment.
Not every accepted construct is executable yet. In particular, stream expressions and stream parsers currently produce a conversion diagnostic instead of native code. Float and string patterns, mutable reference and record-field assignment, and top-level destructuring bindings are compiled.
Tests #
cargo test
The test suite contains focused lexer/parser tests, typechecker tests for
inference and declarations, U-Bform and LLVM lowering tests, end-to-end compiler
tests that build and run native executables, collector stress tests, and an
integration test that parses the Caml Light distribution's own sources and
examples under Camllight/. It parses all 531 .ml/.mli files except
Camllight/examples/minilogo/abstract.ml, which is not valid Caml Light: it
mixes MiniLogo script lines beginning with %% into the source file. That one
file is explicitly skipped.
Layout #
| Path | Contents |
|---|---|
src/lexer.rs |
Tokenizer, comments, literals, Latin-1 handling |
src/token.rs |
Token and keyword definitions |
src/parser.rs |
Recursive-descent grammar and Pratt precedence |
src/ast.rs |
AST types and source spans |
src/elaborate.rs |
Hindley–Milner typechecker, environment, and type errors |
src/prelude.rs |
Standard Caml Light typing environment |
src/lmli.rs |
LMLI kinds, constructors, types, expressions, and primitives |
src/frontend_convert.rs |
Lowering from the Caml Light AST to LMLI |
src/alpha_rename.rs |
Type-preserving LMLI shadowing removal |
src/anf_convert.rs |
Type-preserving LMLI A-normal form conversion |
src/reify.rs |
LMLI trace computation and runtime type reification |
src/closure_convert.rs |
LMLI closure conversion: code, closures, and environments |
src/ubform.rs |
Type-erased, representation-annotated U-Bform IR |
src/ubform_lower.rs |
Closure-converted LMLI to U-Bform lowering |
src/llvm_lower.rs |
U-Bform to LLVM lowering, GC roots, barriers, and exceptions |
src/gc.rs |
Non-moving mark-sweep collector and caml_* runtime ABI |
src/span.rs, src/error.rs |
Locations and parse errors |
src/lib.rs |
Public API and source decoding |
src/main.rs |
camllight command-line compiler driver |
tests/ |
Unit, typechecker, parser, lowering, and end-to-end compiler tests |
The grammar reference is Camllight/src/compiler/parser.mly, with the lexer in
Camllight/src/compiler/lexer.mlp and the original AST in
Camllight/src/compiler/syntax.ml.