Manuscript Documentation
v2026.12.0

Cleaning up#

Files, sockets and processes need closing, even when the function leaves early because something failed. In Manuscript you do not write the close. A value that owns a resource closes it when its scope ends.

count.ms
import (
    lines from "@std/io/steps.ms",
    collect from "@std/io/streams.ms",
    open from "@std/os/fs.ms",
)

fn count_orders(path String) Int! {
    file := open(path)?
    rows := collect(file.reader()? | lines)?
    if rows.is_empty() {
        return error(Error(f"{path} is empty", kind: "EBADMSG"))
    }

    return ok(rows.length() - 1)
}

fn main() Void! {
    count := count_orders("orders.csv")?
    print(f"{count} orders")
}
text
2 orders

Run it next to an orders.csv file containing a header and two rows. With an empty orders.csv, it prints error: orders.csv is empty to standard error and exits with 1.

What to notice#

  • open returns a file handle. Binding it with file := ... is all it takes: the handle closes when count_orders returns, on the normal path and on every ? or return error(...) before it.
  • If open itself fails, there is nothing to close and the error goes to the caller.
  • Cancellation and runtime faults close it as well. You cannot forget a close by returning early.
  • file.reader()? | lines pipes the byte stream into lines (| passes the left value into the next step), and collect reads the lines into a list.
  • Scopes nest. Inner resources close before outer ones, and in one scope the last declared closes first.

When you need to close early#

Declare the binding with var and call close() when you are done reading but not yet done with the function. A second close is harmless:

Manuscript
var file = open(path)?
head := file.read_lines(max_lines: 1)?
void file.close()
slow_work(head)

close() returns a Result, because closing can fail. Flush output before you close it so delivery errors reach you: output.flush()?. ms check --only lint warns when a scope-closed resource has an uncalled flush.

Next: Doing things at once . Exact rules: Scope-end cleanup .