MIMIC

Files and the outside world

Real programs read their arguments, open files and talk to the terminal. In Mimic these operations have one thing in common: they have side effects. The compiler tracks this. A function that touches the outside world, even indirectly, never runs in parallel and never runs out of order, while everything around it stays parallel.

None of these operations crash on failure. They return Option or Result (chapter 7).

They live in a few standard modules, used by path from any file, with no import:

Module For Examples
fs files and directories fs::read, fs::write, fs::list_dir, fs::remove
bytes binary data bytes::from, bytes::hex, bytes::base64, bytes::to_text
hash checksums and hashes of bytes hash::crc32, hash::xxhash64, hash::sha256
compress compression and compact encodings compress::rle, compress::lzw, compress::varints
path paths as text path::join, path::file_name, path::extension
io standard input and error io::read_line, io::read_input, io::eprint
os the program and other programs os::args, os::env, os::run, os::exit
time clocks and dates time::now, time::clock, time::sleep, time::utc
random random numbers random::int, random::float, random::seed
http, ws, tcp, udp the network chapter 17

The module name says where a function comes from, and short names like read or int can't collide with yours. If you use one often, use fs::read brings in the short name. print and the string, list and map functions stay global, because almost every program uses them.

Arguments and environment

mimic run greet.mim -- Ada --loud

Everything after -- goes to your program:

module main

fn main() {
    let names = os::args()                         // ["Ada" "--loud"]
    let who = if ≢ names > 0 { names[0] } else { "world" }
    let shout = contains(names, "--loud")
    let greeting = "hello, {who}!"
    print(if shout { upper(greeting) } else { greeting })

    match os::env("HOME") {
        Some(home) => print("home is {home}"),
        None => print("no HOME set"),
    }
}

Reading and writing files

module main

fn main() {
    let dir = path::join(fs::temp_dir(), "mimic-tutorial")
    let todo = path::join(dir, "todo.txt")
    print(fs::make_dir(dir))
    print(fs::write(todo, "buy milk\nfix bike\n"))
    print(fs::append(todo, "call mum\n"))

    let text = fs::read(todo) else { return }
    let items = lines(text)
    print(items)
    print("{≢ items} things to do")

    match fs::read(path::join(dir, "missing.txt")) {
        Ok(_) => print("found it?"),
        Err(why) => print(starts_with(why, "cannot read")),    // the reason names the file
    }
    print(fs::remove(todo))
    print(fs::remove(dir))
}
Ok(true)
Ok(18)
Ok(9)
["buy milk" "fix bike" "call mum"]
3 things to do
true
Ok(true)
Ok(true)

How it works:

  • Writing returns Ok(bytes written). fs::write replaces the file's contents and fs::append adds to the end.
  • Reading returns the text as Ok(…). On failure you get Err with a reason like cannot read todo.txt: No such file or directory.
  • lines splits text into lines. A final newline doesn't produce an empty extra line, and Windows \r\n line endings are handled.

Bytes

Text files are read as str. For binary data such as images, archives or protocol messages, use bytes: a [u8] array stores one byte per element.

module main

fn main() {
    let header = bytes::from([137 80 78 71])          // the start of a PNG file
    print(bytes::hex(header))
    let file = path::join(fs::temp_dir(), "mimic-tour.bin")
    print(fs::write_bytes(file, header))
    let back = fs::read_bytes(file) else { return }
    print(bytes::hex(back))                            // the same four bytes
    print(back[1] + back[2])                           // each byte reads as an i64
    print(bytes::base64(bytes::of_text("Mimic")))
    print(bytes::to_text(bytes::from([72 105])))
    print(fs::remove(file))
}
89504e47
Ok(4)
89504e47
158
TWltaWM=
Ok("Hi")
Ok(true)

Hashes

The hash module checks and fingerprints bytes: checksums (crc32, crc64, adler32), fast hashes for tables and caches (xxhash64, murmur3, fnv1a64, and siphash with a key), and digests (sha256, and md5 and sha1 for old formats). A digest comes back as bytes, which bytes::hex prints.

module main

fn main() {
    let data = bytes::of_text("123456789")
    print(hash::crc32(data))
    print(bytes::hex(hash::sha256(bytes::of_text("abc"))))
    print(hash::xxhash64(data))
}
3421780262
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
-8306817102742376829

The 64-bit hashes use all 64 bits, so as an i64 about half of them are negative.

Compression

The compress module packs bytes and numbers: run-length encoding (rle) for data with long runs, LZW (lzw) for text with repeats, and varints (varints) for lists of numbers that change by small steps. Each decoder returns a Result, and Err for bytes it did not make.

module main

fn main() {
    let data = bytes::of_text("aaaaaaaabbbbcc")
    let packed = compress::rle(data)
    print(bytes::hex(packed))                        // (8, a) (4, b) (2, c)
    print(compress::unrle(packed))
    print(≢ compress::lzw(bytes::of_text(repeat("to be or not to be ", 50))))
    print(bytes::hex(compress::varints([1000 1001 1003 999])))
    print(compress::unvarints(compress::varints([1000 1001 1003 999])))
}
086104620263
Ok([97 97 97 97 97 97 97 97 98 98 98 98 99 99])
164
d00f020407
Ok([1000 1001 1003 999])

Directories

module main

fn main() {
    let root = path::join(fs::temp_dir(), "mimic-tour")
    print(fs::make_dir(path::join(root, "src/parts")))     // parents are created too
    print(fs::write(path::join(root, "src/main.mim"), "module main"))
    print(fs::write(path::join(root, "README.md"), "# tour"))
    print(fs::list_dir(root))                             // sorted
    print(fs::is_dir(path::join(root, "src")))
    print(fs::is_file(path::join(root, "README.md")))
    print(fs::size(path::join(root, "README.md")))

    // clean up: fs::remove removes files and empty directories
    print(fs::remove(path::join(root, "src/main.mim")))
    print(fs::remove(path::join(root, "src/parts")))
    print(fs::remove(path::join(root, "src")))
    print(fs::remove(path::join(root, "README.md")))
    print(fs::remove(root))
    print(fs::exists(root))
}
Ok(true)
Ok(11)
Ok(6)
Ok(["README.md" "src"])
true
true
Ok(6)
Ok(true)
Ok(true)
Ok(true)
Ok(true)
Ok(true)
false

Paths

Path functions only work on text, so they have no side effects and stay parallel:

module main

fn main() {
    let p = "photos/2026/beach.jpeg"
    print(path::file_name(p))
    print(path::stem(p))
    print(path::extension(p))
    print(path::parent(p))
    print(path::join(path::parent(p), path::stem(p) + ".png"))
}
beach.jpeg
beach
jpeg
photos/2026
photos/2026/beach.png

Standard input, output and errors

module main

// count the words of everything typed (or piped) in
fn main() {
    let text = io::read_input()
    let words = split(text, " ") ▷ ≢
    print("{words} words")
    io::eprint("done")            // to standard error, not mixed into the output
}
echo "the quick brown fox" | mimic run count.mim

To read one line at a time, use io::read_line(), which returns None at the end of the input:

fn total(acc: i64) -> i64 {
    match io::read_line() {
        None => acc,
        Some(line) => match parse_int(trim(line)) {
            Some(n) => total(acc + n),
            None => total(acc),                // skip lines that are not numbers
        },
    }
}

os::exit(code) ends the program at once with an exit status. A non-zero status tells the shell that something went wrong:

let config = fs::read("app.conf") else {
    io::eprint("cannot start: app.conf is missing")
    os::exit(1)
    return
}

The terminal

print always ends the line. io::write(x) does not, so you can build a line piece by piece or redraw a progress bar in place:

fn progress(done: i64, total: i64) {
    let width = 30
    let filled = done * width div total
    io::write("\r[" + repeat("#", filled) + repeat(" ", width - filled) + "] {done * 100 div total}%")
}

On a terminal, io::write shows its text at once. When output goes to a file or a pipe, call io::flush() when it must appear.

The term module covers full-screen programs such as games and editors:

module main

fn game(x: i64) -> i64 {
    term::clear()
    term::move_to(x, 5)
    io::write("\x1b[1;32m@\x1b[0m")          // a green @
    match term::read_key() {
        Some("left") => game(x - 1),
        Some("right") => game(x + 1),
        Some("q") => x,
        _ => game(x),
    }
}

fn main() {
    let raw = term::raw(true) else { return }   // keys one at a time, no echo
    term::alternate_screen(true)
    term::show_cursor(false)
    let x = game(10)
    term::alternate_screen(false)
    print("stopped at {x}")
}                                            // the terminal is restored at exit
  • term::read_key() returns a word for special keys ("up", "enter", "escape", "ctrl-a", …) or the character typed.
  • term::size() gives the columns and rows.
  • os::on_interrupt(() => …) runs a function when Ctrl-C is pressed, instead of stopping the program.

All of this works on Windows too.

Time

time::now() is the current time and time::clock() is a stopwatch. Both count nanoseconds, so they mix with duration literals like 250ms and 2s:

module main

fn main() {
    let t = time::timestamp(2026, 11, 12, 14, 30, 5)      // a UTC date and time
    print(time::format(t))
    print(time::format(t + 90min))
    let d = time::utc(t)
    print("{d.day}/{d.month}/{d.year}, weekday {d.weekday}")

    let start = time::clock()
    time::sleep(20ms)
    print(time::clock() - start >= 20ms)
}
2026-11-12T14:30:05Z
2026-11-12T16:00:05Z
12/11/2026, weekday 4
true

Random numbers

module main

fn main() {
    random::seed(2026)                     // repeatable; leave out for a fresh sequence
    let rolls = ⍳ 10 ¨ (i => random::int(1, 7))
    print(rolls)
    print(rolls ▷ +/)
    let coin = if random::float() < 0.5 { "heads" } else { "tails" }
    print(coin)
}
[6 5 1 1 1 5 3 6 4 4]
36
tails

Drawing a random number changes hidden state, so it counts as an effect: the ¨ above runs in order, which is what makes the sequence repeatable.

Running other programs

os::run starts a program and waits for it to finish. os::shell runs a whole command line:

module main

fn main() {
    let r = os::run("echo", ["hello" "from echo"]) else { return }
    print(r.status)
    print(trim(r.stdout))

    match os::shell("ls /no/such/place") {
        Ok(o) => print("failed: {o.status != 0}, said something: {≢ o.stderr > 0}"),
        Err(e) => print(e),
    }
}
0
hello from echo
failed: true, said something: true

Names are never taken from you

Because the standard modules are used by path, names like args, env, read or parent stay free for your own variables and functions. Even if you name a module of your own fs or time, your module wins inside your program.

The full list of functions is in the standard library reference.

Back to the index.

From docs/tutorial/16-files-and-programs.md in the Mimic repository.