A systems language that pairs Oberon’s Active Objects with the
expressiveness of Ruby and Crystal — compiled to native code, from
userland to bare metal.
Overview
Reef is a statically-typed systems programming language that combines
three things which rarely appear together: the Active Object concurrency
model from Oberon, the expressiveness of languages like Ruby and Crystal, and native
compilation that runs anywhere from userland to bare metal.
Active Objects come from A2 Oberon and two decades of research at ETH Zürich. Each
Active Object owns its state and guards it with a lock, so concurrent access is
synchronized by the language rather than by programmer discipline —
exclusive methods take the write lock and are mutually exclusive;
shared methods take a reader lock and may run concurrently, and the compiler
rejects any attempt to mutate the object’s state from a shared method.
The result is data-race freedom for Active Object state, enforced at compile time. An
Active Object that declares run() also gets its own background thread.
The syntax is built for people, not for parsers: end-based blocks, string interpolation,
pattern matching with guards, generics, sum types, and traits. Reef compiles to C and
then to native code through GCC or Clang, with no VM and no runtime dependency —
the same toolchain path, and the same optimizer, that C code takes.
Current Status: Active Development — a research project with a
working compiler, runtime, and standard library. Reef is pre-1.0: the language is stable
enough to build real systems in, and we are still changing it.
Core Strengths
Active Objects
Language-level safe concurrency. Each object owns its state and guards it with a
lock — exclusive methods take the write lock and are mutually
exclusive, shared methods take a reader lock and run concurrently.
The compiler rejects state mutation from a shared method, giving
data-race freedom for Active Object state, enforced at compile time. Objects
declaring run() get their own background thread.
Modern Type System
Generics with monomorphization, sum types, pattern matching with
exhaustiveness checking, traits, and closures with escape analysis.
Clean Syntax
End-based blocks, Ruby/Crystal-like elegance, string interpolation,
pattern matching with guards, and default parameters.
Systems Performance
Native compilation via C backend. Supports inline assembly for AMD64,
ARM64, and RISC-V. Baremetal compilation for OS development.
Examples
Real programs, compiled and run against Reef v0.7.7. Pick one to see its source and the actual terminal session it produced.
Checksum CLI
Practical
A complete sha256sum-style tool in one file.
Source
// reefsum.reef - File checksum calculator
// Demonstrates: sys.args (CLI parsing), crypto modules, io.file, exit codes
//
// Usage:
// reefsum sha256 file.txt
// reefsum md5 file.txt
// reefsum sha1 file.txt
// reefsum crc32 file.txt
// reefsum --help
//
// Exit codes:
// 0 - Success
// 1 - Error (file not found, unknown algorithm)
// 64 - Usage error (missing arguments)
import sys.args as args
import io.file as file
import core.str as str
import core.result as result
import crypto.sha256 as sha256
import crypto.md5 as md5
import crypto.sha1 as sha1
import crypto.crc32 as crc32
// Version info
fn VERSION(): string
return "1.0.0"
end VERSION
// Print usage information
proc print_usage()
println("Usage: reefsum <algorithm> <file>")
println("")
println("Calculate checksums of files using various algorithms.")
println("")
println("Algorithms:")
println(" sha256 SHA-256 (256-bit, most secure)")
println(" sha1 SHA-1 (160-bit, legacy)")
println(" md5 MD5 (128-bit, legacy)")
println(" crc32 CRC32 (32-bit, fast)")
println("")
println("Options:")
println(" -h, --help Show this help message")
println(" -V, --version Show version information")
println(" -u, --upper Output hash in uppercase (default: lowercase)")
println("")
println("Examples:")
println(" reefsum sha256 document.txt")
println(" reefsum md5 archive.zip")
println(" reefsum crc32 data.bin --upper")
println("")
println("Output format:")
println(" <hash> <filename>")
end print_usage
// Print version information
proc print_version()
print("reefsum version ")
println(VERSION())
println("Supported algorithms: sha256, sha1, md5, crc32")
end print_version
// Calculate and print checksum
// Returns: true on success, false on error
fn calculate_checksum(algorithm: string, filename: string, uppercase: bool): bool
// Check if file exists
if not file.fileExists(filename)
print("reefsum: ")
print(filename)
println(": No such file or directory")
return false
end if
// Read file contents as binary (handles null bytes)
let contents_r = file.readBinaryFile(filename)
if result.is_err(contents_r)
print("reefsum: ")
print(filename)
println(": error reading file")
return false
end if
let contents = result.unwrap_ok(contents_r)
// Calculate hash based on algorithm
// All algorithms now support binary data with *_bytes functions
mut hash = ""
if str.equals(algorithm, "sha256")
hash = sha256.sha256_bytes(contents)
elif str.equals(algorithm, "sha1")
hash = sha1.sha1_bytes(contents)
elif str.equals(algorithm, "md5")
hash = md5.md5_bytes(contents)
elif str.equals(algorithm, "crc32")
if uppercase
hash = crc32.crc32_binary_hex(contents)
else
hash = crc32.crc32_binary_hex_lower(contents)
end if
else
print("reefsum: unknown algorithm '")
print(algorithm)
println("'")
println("Use --help to see supported algorithms.")
return false
end if
// Print in standard checksum format: <hash> <filename>
print(hash)
print(" ")
println(filename)
return true
end calculate_checksum
fn main(): int
let argc = args.count()
// Show help if --help or -h flag
if args.has_flag("help") or args.has_flag("h")
print_usage()
return 0
end if
// Show version if --version or -V flag
if args.has_flag("version") or args.has_flag("V")
print_version()
return 0
end if
// Need at least algorithm and filename
if argc < 3
if argc == 1
print_usage()
return 0
else
println("reefsum: missing file operand")
println("Try 'reefsum --help' for more information.")
return 64 // Usage error
end if
end if
// Parse options
let uppercase = args.has_flag("upper") or args.has_flag("u")
// Get algorithm (first non-flag argument)
let algorithm = args.get(1)
// Validate algorithm before processing files
if str.starts_with(algorithm, "-")
println("reefsum: missing algorithm")
println("Try 'reefsum --help' for more information.")
return 64 // Usage error
end if
// Process each file argument, track errors
mut i = 2
mut had_error = false
while i < argc
let arg = args.get(i)
// Skip flags
if not str.starts_with(arg, "-")
if not calculate_checksum(algorithm, arg, uppercase)
had_error = true
end if
end if
i = i + 1
end while
if had_error
return 1 // One or more files failed
end if
return 0
end main
Parse, validate, and format JSON with typed errors.
Source
// json_pretty.reef - JSON pretty printer and viewer
// Demonstrates: encoding.json, io.file, io.console, core.str
//
// This example reads a JSON file and displays its contents in a
// formatted, human-readable way with indentation and type information.
import io.file as file
import io.console as console
import encoding.json as json
import core.str as str
import core.convert as convert
import core.result as result
import core.error as error
import core.option as option
// Get a human-readable type name
fn get_type_name(type_code: int): string
if type_code == json.JSON_TYPE_NULL()
return "null"
elif type_code == json.JSON_TYPE_BOOL()
return "boolean"
elif type_code == json.JSON_TYPE_NUMBER()
return "number"
elif type_code == json.JSON_TYPE_STRING()
return "string"
elif type_code == json.JSON_TYPE_ARRAY()
return "array"
elif type_code == json.JSON_TYPE_OBJECT()
return "object"
else
return "unknown"
end if
end get_type_name
// Print indentation
proc print_indent(level: int)
mut i = 0
while i < level
print(" ")
i = i + 1
end while
end print_indent
proc main()
println("=================================")
println(" JSON Pretty Printer")
println("=================================")
println("")
// Get filename from user
let filename = option.unwrap_or(console.readLinePrompt("Enter JSON filename: "), "")
let path = str.trim_ws(str.chomp(filename))
if str.is_empty(path)
println("No filename provided.")
return
end if
// Check if file exists
if not file.fileExists(path)
print("Error: File '")
print(path)
println("' not found.")
return
end if
// Read the file
let content_r = file.readFile(path)
if result.is_err(content_r)
println("File could not be read.")
return
end if
let content = result.unwrap_ok(content_r)
if str.is_empty(content)
println("File is empty.")
return
end if
println("")
println("Parsing JSON...")
println("")
// Allocate arrays for parsing
let keys = json.json_alloc_keys()
let values = json.json_alloc_values()
let types = json.json_alloc_types()
// Parse the JSON (strict: malformed input is now Err, not a bare count)
let parse_r = json.json_parse(content, keys, values, types)
if result.is_err(parse_r)
println("Error: Invalid JSON format.")
print(" ")
println(error.error_message(result.unwrap_err(parse_r)))
return
end if
let count = result.unwrap_ok(parse_r)
println("=================================")
println(" Parsed JSON Contents")
println("=================================")
println("")
print("Found ")
print_int(count)
println(" key-value pairs:")
println("")
// Display each key-value pair with type information
mut i = 0
while i < count
let key = keys[i]
let value = values[i]
let type_code = types[i]
// Determine nesting level by counting dots in the key
mut level = 0
mut j = 0
let key_len = str.length(key)
while j < key_len
if str.char_at(key, j) == '.'
level = level + 1
end if
j = j + 1
end while
// Print with indentation
print_indent(level)
// Extract just the leaf key name (after last dot)
let last_dot = str.last_index_of_char(key, '.')
mut display_key = key
if last_dot >= 0
display_key = str.substring(key, last_dot + 1, key_len - last_dot - 1)
end if
// Print key in bold format
print("\"")
print(display_key)
print("\": ")
// Print value based on type
if type_code == json.JSON_TYPE_STRING()
print("\"")
print(value)
print("\"")
elif type_code == json.JSON_TYPE_NULL()
print("null")
elif type_code == json.JSON_TYPE_BOOL()
print(value)
elif type_code == json.JSON_TYPE_NUMBER()
print(value)
elif type_code == json.JSON_TYPE_ARRAY()
print("[...]")
elif type_code == json.JSON_TYPE_OBJECT()
print("{...}")
else
print(value)
end if
// Print type annotation
print(" (")
print(get_type_name(type_code))
println(")")
i = i + 1
end while
println("")
println("=================================")
println(" Summary")
println("=================================")
println("")
// Count types
mut null_count = 0
mut bool_count = 0
mut number_count = 0
mut string_count = 0
mut array_count = 0
mut object_count = 0
i = 0
while i < count
let type_code = types[i]
if type_code == json.JSON_TYPE_NULL()
null_count = null_count + 1
elif type_code == json.JSON_TYPE_BOOL()
bool_count = bool_count + 1
elif type_code == json.JSON_TYPE_NUMBER()
number_count = number_count + 1
elif type_code == json.JSON_TYPE_STRING()
string_count = string_count + 1
elif type_code == json.JSON_TYPE_ARRAY()
array_count = array_count + 1
elif type_code == json.JSON_TYPE_OBJECT()
object_count = object_count + 1
end if
i = i + 1
end while
print(" Strings: ")
print_int(string_count)
println("")
print(" Numbers: ")
print_int(number_count)
println("")
print(" Booleans: ")
print_int(bool_count)
println("")
print(" Nulls: ")
print_int(null_count)
println("")
print(" Arrays: ")
print_int(array_count)
println("")
print(" Objects: ")
print_int(object_count)
println("")
println("")
println("Done!")
end main
TLS 1.3 via the system OpenSSL backend, ~90 lines.
Source
// HTTPS Test - Demonstrates net.http with HTTPS support
// Tests the HTTP client's ability to fetch content over HTTPS
import net.http
import core.str
import core.result as res
import core.error as error
proc main()
println("=== HTTPS Test ===")
println("")
// Test HTTPS GET request
println("Fetching https://www.google.com/ ...")
let r = http.http_get("https://www.google.com/")
if res.is_err(r)
println("Request failed!")
println("Error: " + error.error_message(res.unwrap_err(r)))
else
let response = res.unwrap_ok(r)
if http.http_response_is_ok(response)
println("Success!")
println("Status: " + response.status_text)
println("")
println("Response headers:")
mut i = 0
while i < response.header_count and i < 5
println(" " + response.headers[i])
i = i + 1
end while
println("")
println("Body length: " + int_to_str(str_length(response.body)) + " bytes")
println("")
println("First 200 chars of body:")
println("---")
if str_length(response.body) > 200
println(str_substring(response.body, 0, 200))
else
println(response.body)
end if
println("---")
else
println("Request completed but status was not 2xx.")
println("Status code: " + int_to_str(response.status_code))
end if
end if
end main
// Helper functions
fn str_length(s: string): int
return str.length(s)
end str_length
fn str_substring(s: string, start: int, len: int): string
return str.substring(s, start, len)
end str_substring
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut result = ""
mut num = n
while num > 0
let digit = num - ((num / 10) * 10)
mut digit_char = ""
if digit == 0
digit_char = "0"
elif digit == 1
digit_char = "1"
elif digit == 2
digit_char = "2"
elif digit == 3
digit_char = "3"
elif digit == 4
digit_char = "4"
elif digit == 5
digit_char = "5"
elif digit == 6
digit_char = "6"
elif digit == 7
digit_char = "7"
elif digit == 8
digit_char = "8"
else
digit_char = "9"
end if
result = str.concat(digit_char, result)
num = num / 10
end while
return result
end int_to_str
Build, run & output
dtterm
$ reefc https_test.reef -o ht$ ./ht
=== HTTPS Test ===
Fetching https://www.google.com/ ...
Success!
Status: OK
Response headers:
Content-Type: text/html; charset=ISO-8859-1
Date: Tue, 21 Jul 2026 21:04:28 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Security-Policy-Report-Only: object-src 'none';base-uri 'self';script-src 'nonce-TFGpBReZE_moXxEpi9VvTw' 'strict-dynamic' 'report-sample' 'unsafe-eval' 'unsafe-inline' https: http:;report-uri https://csp.withgoogle.com/csp/gws/other-hp
Body length: 80909 bytes
First 200 chars of body:
---
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many speci
---
Compression CLI
Systems
Links real zlib with `-l z` — C interop without bindings generators.
Source
// reefzip.reef - File compression utility
// Demonstrates: sys.args (CLI parsing), compress modules, io.file, exit codes
//
// BUILD: This example requires zlib (-lz):
// reefc reefzip.reef -lz
//
// Usage:
// reefzip lz4 file.txt # Compress to file.txt.lz4
// reefzip gzip file.txt # Compress to file.txt.gz
// reefzip zlib file.txt # Compress to file.txt.zlib
// reefzip -d lz4 file.txt.lz4 # Decompress
// reefzip --help
//
// Exit codes:
// 0 - Success
// 1 - Error (file not found, compression/decompression failed)
// 64 - Usage error (missing arguments, unknown algorithm)
import sys.args as args
import io.file as file
import core.str as str
import core.convert as convert
// Note: lz4 requires liblz4-dev to be installed
// import compress.lz4 as lz4
import compress.gzip as gzip
import compress.zlib as zlib
// Note: reef_fopen, reef_fclose, reef_fread, reef_fwrite, reef_fseek, reef_ftell
// are compiler builtins - no extern declaration needed
// Version info
fn VERSION(): string
return "1.0.0"
end VERSION
// Print usage information
proc print_usage()
println("Usage: reefzip [OPTIONS] <algorithm> <file>")
println("")
println("Compress or decompress files.")
println("")
println("Algorithms:")
println(" lz4 LZ4 compression (fast)")
println(" gzip Gzip compression (good ratio)")
println(" zlib Zlib/deflate compression")
println("")
println("Options:")
println(" -h, --help Show this help message")
println(" -V, --version Show version information")
println(" -d, --decompress Decompress instead of compress")
println(" -o, --output FILE Specify output file")
println(" -l, --level N Compression level (1-9, default: 6)")
println("")
println("Examples:")
println(" reefzip lz4 document.txt # -> document.txt.lz4")
println(" reefzip gzip archive.tar # -> archive.tar.gz")
println(" reefzip -d lz4 document.txt.lz4 # -> document.txt")
println(" reefzip zlib data.bin -o out.zz # custom output name")
end print_usage
// Print version information
proc print_version()
print("reefzip version ")
println(VERSION())
println("Supported algorithms: lz4, gzip, zlib")
end print_version
// Get file extension for algorithm
fn get_extension(algorithm: string): string
if str.equals(algorithm, "lz4")
return ".lz4"
elif str.equals(algorithm, "gzip")
return ".gz"
elif str.equals(algorithm, "zlib")
return ".zlib"
end if
return ".compressed"
end get_extension
// Read file into byte array
// Returns: number of bytes read, fills buffer
fn read_file_bytes(filename: string, buffer: [byte], max_size: int): int
unsafe
let fp: pointer = reef_fopen(filename, "rb")
if fp == nil
return -1
end if
// Get file size
reef_fseek(fp, 0, 2) // SEEK_END
let file_size = reef_ftell(fp)
reef_fseek(fp, 0, 0) // SEEK_SET
if file_size > max_size
reef_fclose(fp)
return -2 // File too large
end if
// Read file contents
let buf_ptr: pointer = buffer as pointer
let bytes_read = reef_fread(buf_ptr, 1, file_size, fp)
reef_fclose(fp)
return bytes_read
end unsafe
end read_file_bytes
// Write byte array to file
fn write_file_bytes(filename: string, buffer: [byte], size: int): bool
unsafe
let fp: pointer = reef_fopen(filename, "wb")
if fp == nil
return false
end if
let buf_ptr: pointer = buffer as pointer
let bytes_written = reef_fwrite(buf_ptr, 1, size, fp)
reef_fclose(fp)
return bytes_written == size
end unsafe
end write_file_bytes
// Maximum file size (10 MB for demo)
fn MAX_FILE_SIZE(): int
return 10 * 1024 * 1024
end MAX_FILE_SIZE
// Compress file
// Returns: true on success, false on error
fn compress_file(algorithm: string, input_file: string, output_file: string, level: int): bool
// Check if input file exists
if not file.fileExists(input_file)
print("reefzip: ")
print(input_file)
println(": No such file or directory")
return false
end if
// Allocate buffers (using zlib allocator)
let input_buffer = zlib.zlib_alloc_buffer(MAX_FILE_SIZE())
let output_buffer = zlib.zlib_alloc_buffer(MAX_FILE_SIZE() + 1024) // Extra space for headers
// Read input file
let input_size = read_file_bytes(input_file, input_buffer, MAX_FILE_SIZE())
if input_size < 0
if input_size == -1
print("reefzip: cannot open '")
print(input_file)
println("'")
elif input_size == -2
print("reefzip: file too large (max ")
print_int(MAX_FILE_SIZE() / 1024 / 1024)
println(" MB)")
end if
return false
end if
// Compress based on algorithm
mut compressed_size = 0
if str.equals(algorithm, "lz4")
// LZ4 requires liblz4-dev - not available
println("reefzip: lz4 algorithm requires liblz4-dev to be installed")
println(" Use 'gzip' or 'zlib' instead")
return false
elif str.equals(algorithm, "gzip")
let bound = gzip.gzip_compress_bound(input_size)
compressed_size = gzip.gzip_compress(input_buffer, input_size, output_buffer, bound)
elif str.equals(algorithm, "zlib")
let bound = zlib.zlib_compress_bound(input_size)
if level > 0
compressed_size = zlib.zlib_compress_level(input_buffer, input_size, output_buffer, bound, level)
else
compressed_size = zlib.zlib_compress(input_buffer, input_size, output_buffer, bound)
end if
else
print("reefzip: unknown algorithm '")
print(algorithm)
println("'")
return false
end if
if compressed_size <= 0
println("reefzip: compression failed")
return false
end if
// Write output file
if not write_file_bytes(output_file, output_buffer, compressed_size)
print("reefzip: cannot write '")
print(output_file)
println("'")
return false
end if
// Print summary
print(input_file)
print(" -> ")
print(output_file)
print(" (")
print_int(input_size)
print(" -> ")
print_int(compressed_size)
print(" bytes, ")
let ratio = (compressed_size * 100) / input_size
print_int(ratio)
println("% of original)")
return true
end compress_file
// Decompress file
// Returns: true on success, false on error
fn decompress_file(algorithm: string, input_file: string, output_file: string): bool
// Check if input file exists
if not file.fileExists(input_file)
print("reefzip: ")
print(input_file)
println(": No such file or directory")
return false
end if
// Allocate buffers (using zlib allocator)
let input_buffer = zlib.zlib_alloc_buffer(MAX_FILE_SIZE())
let output_buffer = zlib.zlib_alloc_buffer(MAX_FILE_SIZE())
// Read input file
let input_size = read_file_bytes(input_file, input_buffer, MAX_FILE_SIZE())
if input_size < 0
print("reefzip: cannot open '")
print(input_file)
println("'")
return false
end if
// Decompress based on algorithm
mut decompressed_size = 0
if str.equals(algorithm, "lz4")
// LZ4 requires liblz4-dev - not available
println("reefzip: lz4 algorithm requires liblz4-dev to be installed")
return false
elif str.equals(algorithm, "gzip")
decompressed_size = gzip.gzip_decompress(input_buffer, input_size, output_buffer, MAX_FILE_SIZE())
elif str.equals(algorithm, "zlib")
decompressed_size = zlib.zlib_decompress(input_buffer, input_size, output_buffer, MAX_FILE_SIZE())
else
print("reefzip: unknown algorithm '")
print(algorithm)
println("'")
return false
end if
if decompressed_size <= 0
println("reefzip: decompression failed (corrupted or wrong algorithm?)")
return false
end if
// Write output file
if not write_file_bytes(output_file, output_buffer, decompressed_size)
print("reefzip: cannot write '")
print(output_file)
println("'")
return false
end if
// Print summary
print(input_file)
print(" -> ")
print(output_file)
print(" (")
print_int(input_size)
print(" -> ")
print_int(decompressed_size)
println(" bytes)")
return true
end decompress_file
// Remove extension from filename
fn remove_extension(filename: string, ext: string): string
let flen = str.length(filename)
let elen = str.length(ext)
if flen > elen
// Check if filename ends with ext
let suffix = str.substring(filename, flen - elen, elen)
if str.equals(suffix, ext)
return str.substring(filename, 0, flen - elen)
end if
end if
// Default: add .out extension
return filename + ".out"
end remove_extension
// Parse compression level
fn parse_level(s: string): int
if str.is_empty(s)
return 6 // Default
end if
// Simple integer parsing
mut result = 0
let slen = str.length(s)
mut i = 0
while i < slen
let c = str.char_at(s, i)
if c >= '0' and c <= '9'
unsafe
let digit: int = c
result = result * 10 + (digit - 48)
end unsafe
end if
i = i + 1
end while
// Clamp to valid range
if result < 1
result = 1
end if
if result > 9
result = 9
end if
return result
end parse_level
fn main(): int
let argc = args.count()
// Show help if --help or -h flag
if args.has_flag("help") or args.has_flag("h")
print_usage()
return 0
end if
// Show version if --version or -V flag
if args.has_flag("version") or args.has_flag("V")
print_version()
return 0
end if
// Need at least algorithm and filename
if argc < 3
if argc == 1
print_usage()
return 0
else
println("reefzip: missing file operand")
println("Try 'reefzip --help' for more information.")
return 64 // Usage error
end if
end if
// Parse options
let decompress = args.has_flag("decompress") or args.has_flag("d")
let output_opt = args.get_flag_value("output")
let output_opt2 = args.get_flag_value("o")
let output_file_opt = if str.is_empty(output_opt) then output_opt2 else output_opt end if
let level_str = args.get_flag_value("level")
let level_str2 = args.get_flag_value("l")
let final_level_str = if str.is_empty(level_str) then level_str2 else level_str end if
let level = parse_level(final_level_str)
// Get algorithm (first non-flag argument after program name)
mut algorithm = ""
mut input_file = ""
mut i = 1
while i < argc
let arg = args.get(i)
if not str.starts_with(arg, "-")
if str.is_empty(algorithm)
algorithm = arg
elif str.is_empty(input_file)
input_file = arg
end if
elif str.equals(arg, "-o") or str.equals(arg, "--output") or str.equals(arg, "-l") or str.equals(arg, "--level")
// Skip flag value
i = i + 1
end if
i = i + 1
end while
// Validate inputs
if str.is_empty(algorithm)
println("reefzip: missing algorithm")
println("Try 'reefzip --help' for more information.")
return 64 // Usage error
end if
if str.is_empty(input_file)
println("reefzip: missing file operand")
println("Try 'reefzip --help' for more information.")
return 64 // Usage error
end if
// Determine output filename
let output_file = if str.is_empty(output_file_opt) then
if decompress then
remove_extension(input_file, get_extension(algorithm))
else
input_file + get_extension(algorithm)
end if
else
output_file_opt
end if
// Perform compression or decompression
if decompress
if decompress_file(algorithm, input_file, output_file)
return 0
else
return 1
end if
else
if compress_file(algorithm, input_file, output_file, level)
return 0
else
return 1
end if
end if
end main
Build, run & output
dtterm
$ reefc reefzip.reef -lz -o reefzip$ printf 'The quick brown fox jumps over the lazy dog.\n' > ./rz_demo.txt$ ./reefzip gzip ./rz_demo.txt
./rz_demo.txt -> ./rz_demo.txt.gz (45 -> 52 bytes, 115% of original)
$ ls -la ./rz_demo.txt.gz
-rw-rw-r-- 1 user user 52 Jul 21 16:14 ./rz_demo.txt.gz
$ ./reefzip -d gzip ./rz_demo.txt.gz
./rz_demo.txt.gz -> ./rz_demo.txt (52 -> 45 bytes)
$ cat ./rz_demo.txt
The quick brown fox jumps over the lazy dog.
Mandelbrot renderer
Systems
Tight float loops, renders a 400x300 PPM image (pre-rendered PNG in assets/) — compute code that reads clean.
Source
// mandelbrot.reef - Mandelbrot fractal generator
// Demonstrates: graphics.core, graphics.image, math.basic, io.file
//
// This example generates a Mandelbrot set fractal image and saves it
// as a PPM file. The Mandelbrot set is a famous mathematical fractal
// defined by the iteration z = z^2 + c in the complex plane.
import graphics.core as core
import graphics.image as image
import io.file as file
import io.console as console
import core.str as str
import core.convert as convert
import core.option as option
import math.basic as math
import sys.platform.runtime as runtime
// Image dimensions
fn IMG_WIDTH(): int
return 400
end IMG_WIDTH
fn IMG_HEIGHT(): int
return 300
end IMG_HEIGHT
// Maximum iterations for escape test
fn MAX_ITER(): int
return 100
end MAX_ITER
// Mandelbrot set boundaries (viewing window)
fn X_MIN(): float
return 0.0 - 2.5
end X_MIN
fn X_MAX(): float
return 1.0
end X_MAX
fn Y_MIN(): float
return 0.0 - 1.25
end Y_MIN
fn Y_MAX(): float
return 1.25
end Y_MAX
// Calculate escape iteration count for a point
// Returns 0 to MAX_ITER (0 = in set, 1-MAX_ITER = escaped)
fn mandelbrot_escape(c_re: float, c_im: float): int
mut z_re = 0.0
mut z_im = 0.0
mut iter = 0
let max = MAX_ITER()
while iter < max
// z^2 = (a + bi)^2 = a^2 - b^2 + 2ab*i
let z_re_sq = z_re * z_re
let z_im_sq = z_im * z_im
// Check escape: |z|^2 > 4
if z_re_sq + z_im_sq > 4.0
return iter
end if
// z = z^2 + c
let new_re = z_re_sq - z_im_sq + c_re
let new_im = 2.0 * z_re * z_im + c_im
z_re = new_re
z_im = new_im
iter = iter + 1
end while
return 0 // Didn't escape - likely in the set
end mandelbrot_escape
// Convert iteration count to a color
fn iter_to_color(iter: int, max_iter: int): core.Color
if iter == 0
// In the set - black
return core.black()
end if
// Map iteration to a color using HSV-like coloring
// This creates a nice gradient from blue to red to yellow to white
// Normalize iteration to 0-1 range
let t = (iter * 255) / max_iter
// Create color based on escape speed
// Faster escape = brighter/warmer colors
mut r = 0
mut g = 0
mut b = 0
if t < 64
// Blue to cyan
r = 0
g = t * 4
b = 255
elif t < 128
// Cyan to green
r = 0
g = 255
b = 255 - (t - 64) * 4
elif t < 192
// Green to yellow
r = (t - 128) * 4
g = 255
b = 0
else
// Yellow to red
r = 255
g = 255 - (t - 192) * 4
b = 0
end if
// Clamp values
if r > 255
r = 255
end if
if g > 255
g = 255
end if
if b > 255
b = 255
end if
if r < 0
r = 0
end if
if g < 0
g = 0
end if
if b < 0
b = 0
end if
unsafe
return core.rgb(r as byte, g as byte, b as byte)
end unsafe
end iter_to_color
// Alternative color scheme: smooth coloring
fn iter_to_color_smooth(iter: int, max_iter: int): core.Color
if iter == 0
return core.black()
end if
// Use multiple passes through the color wheel
let t = ((iter * 5) % 256)
mut r = 0
mut g = 0
mut b = 0
// Sinusoidal color scheme approximation
if t < 85
r = t * 3
g = 255 - t * 3
b = 0
elif t < 170
let adjusted_t = t - 85
r = 255 - adjusted_t * 3
g = 0
b = adjusted_t * 3
else
let adjusted_t = t - 170
r = 0
g = adjusted_t * 3
b = 255 - adjusted_t * 3
end if
if r > 255
r = 255
end if
if g > 255
g = 255
end if
if b > 255
b = 255
end if
unsafe
return core.rgb(r as byte, g as byte, b as byte)
end unsafe
end iter_to_color_smooth
// Save image as PPM format using direct file I/O
// Uses compiler builtin functions: reef_fopen, reef_fclose, reef_fputs
// This writes incrementally to avoid O(n²) string concatenation
fn save_as_ppm(img: image.Image, filename: string): bool
let w = image.image_width(img)
let h = image.image_height(img)
unsafe
let fp: pointer = reef_fopen(filename, "w")
if fp == nil
return false
end if
// Write header
let _ = reef_fputs("P3\n", fp)
let _ = reef_fputs(convert.to_string(w), fp)
let _ = reef_fputs(" ", fp)
let _ = reef_fputs(convert.to_string(h), fp)
let _ = reef_fputs("\n255\n", fp)
// Write pixel data row by row
mut y = 0
while y < h
mut x = 0
while x < w
let color = image.get_pixel(img, x, y)
let r: int = color.r
let g: int = color.g
let b: int = color.b
let _ = reef_fputs(convert.to_string(r), fp)
let _ = reef_fputs(" ", fp)
let _ = reef_fputs(convert.to_string(g), fp)
let _ = reef_fputs(" ", fp)
let _ = reef_fputs(convert.to_string(b), fp)
if x < w - 1
let _ = reef_fputs(" ", fp)
end if
x = x + 1
end while
let _ = reef_fputs("\n", fp)
y = y + 1
end while
reef_fclose(fp)
end unsafe
return true
end save_as_ppm
// Generate the Mandelbrot fractal
proc generate_mandelbrot(img: image.Image, use_smooth: bool)
let w = image.image_width(img)
let h = image.image_height(img)
let max_iter = MAX_ITER()
// Calculate scale factors for mapping pixels to complex plane
let x_range = X_MAX() - X_MIN()
let y_range = Y_MAX() - Y_MIN()
let h_f = runtime.reef_int_to_float(h - 1)
let w_f = runtime.reef_int_to_float(w - 1)
mut y = 0
while y < h
// Map pixel y to imaginary part
let y_f = runtime.reef_int_to_float(y)
let c_im = Y_MIN() + (y_f * y_range) / h_f
mut x = 0
while x < w
// Map pixel x to real part
let x_f = runtime.reef_int_to_float(x)
let c_re = X_MIN() + (x_f * x_range) / w_f
// Calculate escape iteration
let iter = mandelbrot_escape(c_re, c_im)
// Convert to color
let color = if use_smooth then
iter_to_color_smooth(iter, max_iter)
else
iter_to_color(iter, max_iter)
end if
image.set_pixel(img, x, y, color)
x = x + 1
end while
// Progress indicator every 30 rows
if y % 30 == 0
print(" Row ")
print_int(y)
print("/")
print_int(h)
println("")
end if
y = y + 1
end while
end generate_mandelbrot
proc main()
println("=================================")
println(" Mandelbrot Fractal Generator")
println("=================================")
println("")
println("This program generates an image of the Mandelbrot set,")
println("one of the most famous fractals in mathematics.")
println("")
// Ask for color scheme
println("Color schemes:")
println(" 1. Gradient (blue to red)")
println(" 2. Smooth cycling colors")
let scheme_input = option.unwrap_or(console.readLinePrompt("Choose color scheme (1-2): "), "")
let scheme = str.trim_ws(str.chomp(scheme_input))
let use_smooth = str.equals(scheme, "2")
println("")
print("Image size: ")
print_int(IMG_WIDTH())
print("x")
print_int(IMG_HEIGHT())
println("")
print("Max iterations: ")
print_int(MAX_ITER())
println("")
println("")
println("Generating fractal (this may take a moment)...")
println("")
// Create the image
let img = image.create_image_rgba(IMG_WIDTH(), IMG_HEIGHT())
// Clear to black
image.clear(img, core.black())
// Generate the fractal
generate_mandelbrot(img, use_smooth)
println("")
println("Generation complete!")
println("")
// Get filename
let default_name = "mandelbrot.ppm"
print("Save as (default: ")
print(default_name)
let input = option.unwrap_or(console.readLinePrompt("): "), "")
let trimmed = str.trim_ws(str.chomp(input))
let filename = if str.is_empty(trimmed) then default_name else trimmed end if
print("Saving to ")
print(filename)
println("...")
if save_as_ppm(img, filename)
println("")
println("Success! Mandelbrot fractal saved.")
println("")
println("To view the image:")
println(" - Open with any image viewer that supports PPM")
print(" - Convert to PNG: convert ")
print(filename)
println(" mandelbrot.png")
println("")
println("Fun facts about the Mandelbrot set:")
println(" - Discovered by Benoit Mandelbrot in 1980")
println(" - Has infinite detail at any zoom level")
println(" - The boundary has a fractal dimension of 2")
println(" - Contains infinitely many copies of itself")
else
println("")
println("Error: Failed to save the file.")
end if
println("")
println("Done!")
end main
Build, run & output
dtterm
$ reefc mandelbrot.reef -o mb$ printf '1\nmb_demo.ppm\n' | ./mb
=================================
Mandelbrot Fractal Generator
=================================
This program generates an image of the Mandelbrot set,
one of the most famous fractals in mathematics.
Color schemes:
1. Gradient (blue to red)
2. Smooth cycling colors
Choose color scheme (1-2):
Image size: 400x300
Max iterations: 100
Generating fractal (this may take a moment)...
Row 0/300
Row 30/300
Row 60/300
Row 90/300
Row 120/300
Row 150/300
Row 180/300
Row 210/300
Row 240/300
Row 270/300
Generation complete!
Save as (default: mandelbrot.ppm): Saving to mb_demo.ppm...
Success! Mandelbrot fractal saved.
To view the image:
- Open with any image viewer that supports PPM
- Convert to PNG: convert mb_demo.ppm mandelbrot.png
Fun facts about the Mandelbrot set:
- Discovered by Benoit Mandelbrot in 1980
- Has infinite detail at any zoom level
- The boundary has a fractal dimension of 2
- Contains infinitely many copies of itself
Done!
$ ls -la ./mb_demo.ppm
-rw-rw-r-- 1 user user 1001749 Jul 21 16:13 ./mb_demo.ppm
$ head -c 40 ./mb_demo.ppm
P3
400 300
255
0 8 255 0 8 255 0 8 255 0
The 400×300 PPM the run above wrote, converted to PNG.
Concurrent hasher
Concurrency
Worker Active Objects with their own threads, no locks in user code.
Source
// parallel_hash.reef - Concurrent file checksums with Active Objects
// Demonstrates: worker AOs with run() threads, await-gated queues,
// io.dir, io.file, crypto.sha256, sys.args
//
// Usage:
// parallel_hash <directory>
//
// Hashes every regular file directly inside <directory> with SHA-256.
// Work is spread across 4 worker Active Objects, each with its own
// thread; a collector Active Object aggregates results; main prints
// them sorted by filename, sha256sum-style.
import sys.args as args
import io.dir as dir
import io.file as file
import crypto.sha256 as sha256
import core.result as result
import core.str as str
active object Collector
names: [string]
digests: [string]
count: int
target: int
init()
self.names = new [string](0)
self.digests = new [string](0)
self.count = 0
self.target = 0
end init
exclusive proc add(name: string, digest: string)
self.names = self.names.append(name)
self.digests = self.digests.append(digest)
self.count = self.count + 1
end add
// Blocks until every dispatched file is hashed. self.target holds
// the parameter: await conditions only close over self, not locals.
exclusive proc wait_for(expected: int)
self.target = expected
await self.count == self.target
end wait_for
exclusive fn digest_for(name: string): string
mut i = 0
while i < self.count
if str.equals(self.names[i], name)
return self.digests[i]
end if
i = i + 1
end while
return "?"
end digest_for
end Collector
active object Worker
queue: [string]
done: bool
sink: Collector
init(sink: Collector)
self.queue = new [string](0)
self.done = false
self.sink = sink
end init
exclusive proc submit(path: string)
self.queue = self.queue.append(path)
end submit
exclusive proc finish()
self.done = true
end finish
// Blocks until a path is queued or finish() was called; "" means
// done-and-drained. The await lives here, not in run() directly,
// and run() reaches it via a (legal) exclusive self-call.
exclusive fn take(): string
await self.queue.length() > 0 or self.done
if self.queue.length() == 0
return ""
end if
let path = self.queue[0]
self.queue = self.queue.remove(0)
return path
end take
run()
loop
let path: string = self.take()
if str.equals(path, "")
break
end if
let contents_r = file.readBinaryFile(path)
if result.is_ok(contents_r)
self.sink.add(path, sha256.sha256_bytes(result.unwrap_ok(contents_r)))
else
self.sink.add(path, "(unreadable)")
end if
end loop
end run
end Worker
// Selection sort using only append/remove (Reef arrays have no insert).
fn sorted(items: [string]): [string]
mut remaining: [string] = items
mut out: [string] = new [string](0)
while remaining.length() > 0
mut min_i = 0
mut i = 1
while i < remaining.length()
if str.compare(remaining[i], remaining[min_i]) < 0
min_i = i
end if
i = i + 1
end while
out = out.append(remaining[min_i])
remaining = remaining.remove(min_i)
end while
return out
end sorted
proc main()
if args.count() < 2
println("Usage: parallel_hash <directory>")
println("Hashes every regular file in <directory> with SHA-256,")
println("spread across 4 concurrent worker Active Objects.")
return
end if
let root = args.get(1)
let listing_r = dir.list_dir(root)
if result.is_err(listing_r)
println("parallel_hash: cannot read directory: ${root}")
return
end if
// Keep regular files only.
mut files: [string] = new [string](0)
let entries = result.unwrap_ok(listing_r)
for entry in entries
let path = root + "/" + entry
if not dir.is_directory(path)
files = files.append(path)
end if
end for
let collector = new Collector()
let workers = [new Worker(collector), new Worker(collector),
new Worker(collector), new Worker(collector)]
mut i = 0
for path in files
workers[i % 4].submit(path)
i = i + 1
end for
for w in workers
w.finish()
end for
collector.wait_for(files.length())
let ordered = sorted(files)
for path in ordered
println("${collector.digest_for(path)} ${path}")
end for
end main
The same language, freestanding, booting under QEMU.
This example is planned but not yet published. It waits on BUG-116 — the baremetal shadow-frame port — and ships once that fix lands. The slot is kept here deliberately.
Technical Details
Compilation
Lexer, parser, type checker, and code generator produce readable C code.
GCC/Clang compiles to native executables.
Runtime
Written in C99, with no dependency on a VM or language runtime beyond it.
Mark-and-sweep garbage collector with concurrent marking and lazy sweeping:
application threads keep running while the collector marks. Precise stack scanning
via a shadow-frame chain — the collector knows exactly which slots hold
pointers rather than guessing conservatively.
reef-os library for kernel programming. CPU primitives, serial drivers,
spinlocks, and Limine bootloader support.
License & Availability
Reef is open source under the Apache License 2.0 with the LLVM runtime
library exception (Apache-2.0 WITH LLVM-exception).
The runtime library exception means programs you compile with Reef carry
no attribution obligation from the portions of the Reef runtime
embedded in your binary, and Reef code may be combined with GPLv2 software.
Apache-2.0 includes an explicit patent grant.
No contributor license agreement is required. Apache-2.0 §5
places contributions under the same terms as the rest of the project.
Reef is developed by Leafscale, LLC. Because it is Apache-2.0 licensed, anyone
can fork, build on, and continue it independently of us.