Every entry compiles and runs verbatim against Reef v0.9.2. Pick one to see its full 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.optparse (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.optparse as opt
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
// 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 p = opt.command("reefsum")
p.about("Calculate checksums of files using various algorithms.")
p.version("1.0.0")
let upper = p.bool_flag("upper", 'u', false, "Output hash in uppercase (default: lowercase)")
let algorithm = p.arg("algorithm")
let files = p.rest()
match p.parse()
Status_OkHelp() =>
return 0
end
Status_OkVersion() =>
return 0
end
Status_Err(e) =>
if opt.argc() < 2
p.usage()
return 0
end if
println("reefsum: " + opt.format(e))
println("Try 'reefsum --help' for more information.")
return 64
end
Status_OkParsed() =>
if files.len() == 0
println("reefsum: missing file operand")
println("Try 'reefsum --help' for more information.")
return 64
end if
let algo = algorithm.value()
let uppercase = upper.value()
mut had_error = false
let names = files.values()
mut i = 0
while i < names.length()
if not calculate_checksum(algo, names[i], uppercase)
had_error = true
end if
i = i + 1
end while
if had_error
return 1
end if
return 0
end
end match
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
xterm
$ 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: Wed, 26 Aug 2026 16:55:43 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Security-Policy-Report-Only: object-src 'none';base-uri 'self';script-src 'nonce-jPaME85ovLeL_wrdD_da7Q' 'strict-dynamic' 'report-sample' 'unsafe-eval' 'unsafe-inline' https: http:;report-uri https://csp.withgoogle.com/csp/gws/other-hp
Body length: 83290 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.optparse (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.optparse as opt
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
// 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
fn main(): int
let p = opt.command("reefzip")
p.about("Compress or decompress files.")
p.version("1.0.0")
let decompress = p.bool_flag("decompress", 'd', false, "Decompress instead of compress")
let output = p.string_flag("output", 'o', "", "Specify output file")
let level_flag = p.int_flag("level", 'l', 6, "Compression level (1-9, default: 6)")
let algorithm = p.arg("algorithm")
let input = p.arg("file")
match p.parse()
Status_OkHelp() =>
return 0
end
Status_OkVersion() =>
return 0
end
Status_Err(e) =>
if opt.argc() < 2
p.usage()
return 0
end if
println("reefzip: " + opt.format(e))
println("Try 'reefzip --help' for more information.")
return 64
end
Status_OkParsed() =>
let algo = algorithm.value()
let input_file = input.value()
mut level = level_flag.value()
if level < 1
level = 1
end if
if level > 9
level = 9
end if
mut output_file = input_file + get_extension(algo)
if decompress.value()
output_file = remove_extension(input_file, get_extension(algo))
end if
if output.present()
output_file = output.value()
end if
if decompress.value()
if decompress_file(algo, input_file, output_file)
return 0
else
return 1
end if
else
if compress_file(algo, input_file, output_file, level)
return 0
else
return 1
end if
end if
end
end match
return 0
end main
Build, run & output
xterm
$ 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 -> 64 bytes, 142% of original)
$ ls -la ./rz_demo.txt.gz
-rw-rw-r-- 1 user user 64 Aug 26 11:55 ./rz_demo.txt.gz
$ ./reefzip -d gzip ./rz_demo.txt.gz
./rz_demo.txt.gz -> ./rz_demo.txt (64 -> 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
xterm
$ 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 Aug 26 11:55 ./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.optparse
//
// 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.optparse as opt
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()
let p = opt.command("parallel_hash")
p.about("Hash files in parallel")
let directory = p.arg("directory")
mut root = ""
match p.parse()
Status_OkParsed() =>
root = directory.value()
end
Status_OkHelp() =>
return
end
Status_OkVersion() =>
return
end
Status_Err(e) =>
println("parallel_hash: " + opt.format(e))
return
end
end match
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
A widget tree: inheritance, virtual dispatch, typecase.
Source
// 0.9 Phase 9 M3: widget-tree showcase. A small hierarchy, virtual
// dispatch through a Base-typed list, typecase, and the
// delegate-to-virtual trait pattern (spec §4.5). D42: the trait method
// is a different name from the class virtual it forwards to.
object Widget
id: string
init(id: string)
self.id = id
end init
shared fn kind(): string
return "widget"
end kind
shared fn render(): string
return "<widget ${self.id}/>"
end render
end Widget
object Label extends Widget
text: string
init(id: string, text: string)
inherited init(id)
self.text = text
end init
override shared fn kind(): string
return "label"
end kind
override shared fn render(): string
return "<label ${self.id}>${self.text}</label>"
end render
end Label
object Button extends Widget
text: string
init(id: string, text: string)
inherited init(id)
self.text = text
end init
override shared fn kind(): string
return "button"
end kind
override shared fn render(): string
return "<button ${self.id}>${self.text}</button>"
end render
end Button
object Panel extends Widget
kids: [Widget]
init(id: string)
inherited init(id)
self.kids = new [Widget](0)
end init
exclusive proc add(c: Widget)
self.kids = self.kids.append(c)
end add
override shared fn kind(): string
return "panel"
end kind
override shared fn render(): string
mut s = "<panel ${self.id}>"
let n = self.kids.length()
for i in 0..n
s = s + self.kids[i].render()
end for
return s + "</panel>"
end render
end Panel
trait Printable
fn show(): string;
end Printable
impl Printable for Widget
fn show(): string
return self.kind()
end show
end impl
fn describe[T](x: T): string where T: Printable
return x.show()
end describe
proc tag_of(w: Widget)
typecase w
Button b =>
println("typecase: button ${b.text}")
end
Label l =>
println("typecase: label ${l.text}")
end
Panel p =>
println("typecase: panel ${p.id}")
end
else =>
println("typecase: other")
end
end typecase
end tag_of
proc main()
let root = new Panel("root")
let hello = new Label("h", "hello")
let ok = new Button("b", "ok")
root.add(hello)
root.add(ok)
println("kinds: ${root.kind()} ${hello.kind()} ${ok.kind()}")
let w: Widget = ok
println("virtual: ${w.kind()}")
println("trait-base: ${w.show()}")
println("trait-derived: ${ok.show()}")
println("generic: ${describe(ok)}")
tag_of(ok)
tag_of(hello)
tag_of(root)
println("tree: ${root.render()}")
println("widget-tree: OK")
end main
The same language, freestanding, booting under QEMU.
Source
// kernel_limine.reef - Minimal Limine kernel in Reef
// Uses framebuffer output via reef_putchar
// ============================================================
// CPU Control (still useful for halting)
// ============================================================
// Halt CPU (wait for interrupt)
asm proc hlt() for amd64
HLT
end hlt
// ============================================================
// Kernel Main - prints messages using reef_putchar (from limine_boot.c)
// ============================================================
// External: reef_putchar is provided by limine_boot.c
extern "C" proc reef_putchar(c: char)
// Helper to print a string
proc print_string(s: string)
mut i = 0
// BUG-123: reading s[i] up to and including the NUL terminator requires
// unsafe -- the checked form panics on the index == length read that
// this idiom needs (same idiom as core.str.length, which wraps it the
// same way).
unsafe
mut ch = s[i]
while ch != '\0'
reef_putchar(ch)
i = i + 1
ch = s[i]
end while
end unsafe
end print_string
proc main()
// Print welcome message
print_string("================================")
reef_putchar('\n')
print_string(" Reef OS - Limine Edition")
reef_putchar('\n')
print_string("================================")
reef_putchar('\n')
reef_putchar('\n')
print_string("Hello from Reef!")
reef_putchar('\n')
print_string("Kernel booted successfully.")
reef_putchar('\n')
reef_putchar('\n')
print_string("Features:")
reef_putchar('\n')
print_string(" - Inline assembly (x86-64)")
reef_putchar('\n')
print_string(" - Limine boot protocol")
reef_putchar('\n')
print_string(" - Framebuffer graphics")
reef_putchar('\n')
reef_putchar('\n')
print_string("System halted.")
reef_putchar('\n')
// Halt loop
loop
hlt()
end loop
end main
Build, run & output
xterm
$ make -f Makefile.limine iso$ qemu-system-x86_64 -cdrom build-limine/reef-os.iso -serial stdio -display none
=== Reef OS Limine Kernel ===
Serial initialized.
Limine base revision OK.
Framebuffer acquired.
Screen cleared.
Calling reef_main()...
================================
Reef OS - Limine Edition
================================
Hello from Reef!
Kernel booted successfully.
Features:
- Inline assembly (x86-64)
- Limine boot protocol
- Framebuffer graphics
System halted.