Reef Language Reference

Last reviewed on version: 0.9.0

Welcome to the Reef Language Reference. Chapters are numbered in reading order; gaps of 5 leave room to insert later. The filename prefix is the order — not a historical id.

Every self-contained ```reef example is checked by make docs-check.


Quick Navigation

Language

  1. Compiler Usage — commands, options, workflows
  2. Project Structurereefc new, reef.toml, src/
  3. Language Basics — syntax, types, operators, control flow
  4. Functions and Proceduresfn, proc, parameters
  5. String Interpolation${} and multi-line strings
  6. User-Defined Types — structs, enums, arrays, sets, subranges
  7. Error HandlingResult / Option
  8. Passive Objects — classes, extends, virtual methods, typecase
  9. Active Objects — Reef's concurrency model
  10. Traits — interfaces and where bounds
  11. Generics — generic types and functions
  12. Closures — lambdas and capture
  13. Defer — cleanup at function exit
  14. Spawn — fire-and-forget threads
  15. Modulesimport / export / visibility
  16. Testing — writing and running tests

Systems

  1. Unsafeunsafe blocks and raw memory
  2. FFI — calling C
  3. Inline Assemblyasm proc / asm fn
  4. Systems Programming — daemons, fork, signals
  5. Filesystem Operations — the fs.* family
  6. Streaming I/Oio.file / io.buffer / sys.fd
  7. Raw Syscalls — libc-free Linux syscalls
  8. reef-os Library — OS-development primitives

Reference Guide Contents

Compiler Usage — Compiler Reference

What's Covered:

  • All reefc commands (build, run, new, init, clean, doc, info, doctor)
  • Compilation options (-o, --check, --emit-c, --emit-ast, --keep-c)
  • External library linking (-l, --obj, --cflags)
  • Runtime and target options (--runtime, --target)
  • Baremetal compilation (--no-stdlib, --linker-script, --entry)
  • GC configuration (--no-gc)
  • Environment variables (REEF_HOME, REEF_STDLIB, REEF_RUNTIME)
  • Common workflows and troubleshooting

Read this when: Learning the compiler, debugging builds, linking libraries


Project Structure — Project Organization

What's Covered:

  • Creating projects with reefc new
  • reef.toml configuration
  • Build commands (build, run, doc, clean)
  • Module organization and imports
  • Multi-file project patterns
  • Environment variables (REEF_STDLIB_PATH, REEF_RUNTIME_PATH)

Read this when: Starting a new project, organizing code, configuring builds

This is the repo-layout chapter (reef.toml, src/main.reef). The module language (import / export / visibility) is 075_MODULES.md.


Language Basics — Language Fundamentals

What's Covered:

  1. Introduction - What is Reef, key features
  2. Getting Started - First program
  3. Lexical Structure - Comments, identifiers, keywords
  4. Types Overview - All primitive types
  5. Variables - let, mut, type inference
  6. Operators - Arithmetic, comparison, logical, sets
  7. Control Flow - if, unless, while, for, loop, match

Read this when: Learning Reef from scratch, understanding syntax


Functions and Procedures — Functions and Procedures

What's Covered:

  • Function declarations (fn)
  • Procedure declarations (proc)
  • Parameters and return types
  • Default parameters
  • Return statements
  • Labeled ends
  • Calling conventions

Read this when: Writing reusable code, organizing programs


String Interpolation — String Interpolation

What's Covered:

  • ${variable} interpolation in string literals
  • Multi-line strings
  • Format specifiers

Read this when: Building messages, logs, or any formatted text


User-Defined Types — User-Defined Types

What's Covered:

  • Structs and Records
  • Enums (Sum Types)
  • Arrays
  • Sets
  • Subranges
  • Type Aliases
  • Pattern Matching

Read this when: Creating custom data structures, using advanced types

Passive objects (classes, inheritance) are not in this chapter — see 040_OBJECTS.md.


Error Handling — Error Handling Guide

What's Covered:

  • Option types for optional values
  • Result types for fallible operations
  • Common patterns (check-and-unwrap, defaults, early return)
  • Combining with defer for cleanup
  • Design guidelines and best practices
  • Comparison with exceptions

Read this when: Handling errors, designing APIs, understanding Reef's philosophy


Passive Objects — Classes and Inheritance

What's Covered:

  • object declarations, init, exclusive/shared methods
  • Single inheritance (extends, override, inherited)
  • Virtual dispatch through a base-typed reference
  • is / as / typecase
  • Traits on objects (delegate-to-virtual; subclasses inherit the base impl)
  • finalize chaining
  • What 0.9 does not do (dyn Trait, generic objects, object spawn args)

Read this when: Building a hierarchy, a widget tree, or any virtual dispatch


Active Objects — Concurrency Model

What's Covered:

  • Active Object fundamentals
  • Fields and methods
  • init() constructors
  • finalize() destructors
  • exclusive methods (mutual exclusion)
  • shared methods (concurrent reads)
  • run() background threads
  • Thread safety guarantees
  • Best practices and patterns

Read this when: Writing concurrent code, using Reef's unique features

Note: Active Objects are Reef's defining feature — worth deep study.


Traits — Traits and Type Constraints

What's Covered:

  • Trait definitions with abstract methods
  • Implementation blocks (impl Trait for Type)
  • Generic constraints (where T: Trait)
  • Self access in implementations
  • Traits on object classes (delegate-to-virtual)
  • Current limitations

Read this when: Defining interfaces, constraining generic types, organizing code with polymorphism


Generics — Generic Programming

What's Covered:

  • Generic types (Box[T], Map[K,V])
  • Generic structs
  • Generic Active Objects
  • Default parameters with generics
  • Monomorphization
  • Type parameters
  • Instantiation
  • Type inference for generic calls

Read this when: Writing reusable, type-safe abstractions


Closures — Lambda Expressions and Closures

What's Covered:

  • Lambda expressions with fn and proc
  • Expression body: fn(x: int): int => x + 1
  • Block body: fn(x: int): int ... end fn
  • Variable capture (immutable and mutable)
  • Function types: Fn[int, int]
  • Higher-order functions (map, filter, fold, foreach)
  • Escape analysis optimization

Read this when: Using functional programming patterns, callbacks, HOFs


Defer — Defer Statement

What's Covered:

  • defer ... end defer for cleanup at function exit
  • LIFO order of multiple defers
  • Interaction with return and Active Object methods

Read this when: Managing resources, guaranteeing cleanup


Spawn — Spawn Expression

What's Covered:

  • Fire-and-forget spawn function_call()
  • How arguments are rooted across the handshake
  • When to use Active Object await instead

Read this when: Starting a background task that does not need a result


Modules — Code Organization

What's Covered:

  • Module structure
  • Import statements
  • Import aliases
  • Export sections
  • Public vs private declarations
  • Module resolution
  • Multi-file projects

Read this when: Organizing larger projects, using libraries

Project layout (reef.toml, src/) is 010_PROJECT_STRUCTURE.md.


Testing — Testing Guide

What's Covered:

  • TestRunner active object
  • Assertion methods (assert_eq_int, assert_true, etc.)
  • Organizing test files
  • Testing patterns (edge cases, error conditions, Active Objects)
  • Best practices for writing tests

Read this when: Writing tests, setting up test infrastructure, ensuring code quality


Unsafe — Unsafe Blocks

What's Covered:

  • unsafe ... end unsafe
  • Raw pointers and integer↔pointer casts
  • FFI and systems-programming use cases
  • What unsafe does not relax (owner-check, type rules outside the block)

Read this when: Talking to C, MMIO, or otherwise leaving the safe subset


Foreign Function Interface (FFI) — Foreign Function Interface

What's Covered:

  • extern "C" declarations
  • Type mapping (Reef ↔ C)
  • Calling C functions
  • Safety considerations
  • Integration with C libraries

Read this when: Integrating with existing C code, using system libraries


Inline Assembly — Inline Assembly

What's Covered:

  • Assembly procedures (asm proc) and functions (asm fn)
  • x86-64 (AMD64) with Intel syntax
  • ARM64 (AArch64) support
  • Parameter access and return values
  • Baremetal compilation (--target amd64-baremetal)
  • Custom entry points and linker scripts
  • OS kernel development example

Read this when: Writing OS kernels, embedded systems, performance-critical code, hardware access


Systems Programming — Systems Programming

What's Covered:

  • Process management (sys.process), including fork
  • Signals, file descriptors, polling
  • Daemons and init-style programs
  • Fork-safety of the collector

Read this when: Writing daemons, init systems, or other low-level hosted programs


Filesystem Operations — Filesystem Operations

What's Covered:

  • File metadata and type queries (fs.stat)
  • Permission modification and testing (fs.perm)
  • Symbolic and hard link operations (fs.link)
  • Copy, remove, rename operations (fs.ops)
  • Recursive directory tree operations
  • Safety checks for destructive operations

Read this when: Working with files, replacing shell-outs, writing deployment scripts


Streaming I/O — Streaming I/O

What's Covered:

  • Choosing between io.file, io.buffer, and sys.fd
  • GC impact of slurp-vs-stream
  • Result[Option[T], Error] for fallible reads

Read this when: Reading large files or choosing an I/O level


Raw Syscalls — Raw Linux Syscalls

What's Covered:

  • Direct syscalls bypassing libc
  • Linux AMD64 syscall wrappers
  • Linux ARM64 syscall wrappers
  • Process control, file I/O, memory management
  • Syscall ABI reference

Read this when: Building libc-free binaries, embedded development, maximum system control


reef-os Library — OS Development Library

What's Covered:

  • CPU control primitives (x86-64, ARM64)
  • I/O port operations
  • Control registers and MSRs
  • Memory barriers
  • Spinlock synchronization
  • Serial port debugging
  • Limine boot protocol

Read this when: Writing OS kernels, bare-metal programming, hardware drivers


Learning Path

Beginner Track

  1. Compiler Usage and Project Structure
  2. Language Basics, then Functions, then String Interpolation
  3. User-Defined Types and Error Handling
  4. Hello world and small programs with Result/Option

Intermediate Track

  1. Passive Objects (a widget or AST node hierarchy)
  2. Active Objects (the concurrency model)
  3. Traits, then Generics, then Closures
  4. Defer, Spawn, Modules, Testing

Systems Programming Track

  1. Unsafe and FFI
  2. Inline Assembly
  3. Systems Programming, Filesystem, Streaming I/O
  4. Raw Syscalls and reef-os for kernel / libc-free work

Code Examples

Complete, self-contained examples in this reference are checked against the compiler by make docs-check, which extracts every ```reef block and runs reefc --check over it. Chapters also carry two kinds of block that are expected not to compile on their own, and are not defects:

  • Fragments — mid-narrative snippets with no proc/module wrapper, or code that refers to a type declared in an earlier, separately-fenced block.
  • Deliberate error illustrations — code shown precisely because the compiler rejects it, with the diagnostic quoted in the surrounding prose.

Examples are drawn from reef-compiler/examples/ (test programs) and reef-stdlib/ (standard library code).


Reference vs Specification

This Reference Guide:

  • Practical, example-driven
  • Based on actual implementation
  • Tested code samples
  • Crystal-style balance (thorough but accessible)

Language Specification (reef-language-spec-v2.md):

  • Narrative language definition (current to 0.7.5)
  • Design rationale and future features
  • Where it summarizes, these reference pages govern

Use both: Reference for learning and definitive answers, Specification for the narrative overview and design rationale.


Implementation Status

All features in this reference are fully implemented in Reef 0.9 unless marked as:

  • [Planned] - In specification but not yet implemented
  • [Partial] - Partially implemented with known limitations
  • [Deprecated] - No longer recommended

Getting Help

Compiler errors? See each section's "Common Errors" subsections

Not working as expected? Check:

  1. Compiler version: reefc --version
  2. Examples directory for similar code
  3. Known issues: the project's issue tracker

Contributing examples? All examples are welcome!