std::stream

std/src/stream.mo

Standard library: byte streams -- one read/write/close surface over every file-descriptor-backed channel (stdio, an open file, and in later phases a TCP connection and a child-process pipe), with a ByteBuf payload and a structured StreamError (plans/implementations/io-streams.md).

Every ByteBuf a Stream.read hands back must be released with ByteBuf.free exactly once after it is consumed, and so must every buffer built for a Stream.write. Compiled, free is a no-op; interpreted, a missing one leaks a registry slot for the life of the process.

typeStreamErrorKind#
pub type StreamErrorKind {
    not_found,
    permission_denied,
    connection_refused,
    connection_reset,
    broken_pipe,
    invalid_input,
    timed_out,
    address_in_use,
    host_unresolved,
    other
}

What kind of failure a stream operation hit. Not exhaustive: other is the escape valve, and StreamError.message always carries the OS text.

The DECLARATION ORDER is the natives' kind code (0 = not_found .. 9 = other): stream_error_kind_of_errno (runtime/src/runtime.c) and stream_error_code (rust/core/src/core_native.rs) produce it, and StreamError.kinds below decodes it. Keep all four in lock-step.

structStreamError#
pub struct StreamError {
    kind : StreamErrorKind,
    message : String
}
instance_#
pub instance Copy StreamErrorKind {
    def copy (k : StreamErrorKind) : Pair StreamErrorKind StreamErrorKind :=
        Pair.pair k k
}

A kind is a plain tag and a StreamError is a tag plus a Copy String, so sharing one is a bit-copy, not an ownership move.

instance_#
pub instance Copy StreamError {
    def copy (e : StreamError) : Pair StreamError StreamError := Pair.pair e e
}
defStreamError.kind_of_code#
pub def StreamError.kind_of_code (code : I64) : StreamErrorKind

A native's kind code as the kind; anything out of range is other.

defStreamError.of#
pub def StreamError.of (kind : StreamErrorKind) (message : String) : StreamError
defStreamError.is_not_found#
pub def StreamError.is_not_found (e : StreamError) : Bool

Whether e is not_found -- the one kind a caller may read as "absent" (an optional file) rather than as a failure.

classStream#
pub class Stream S {
    def read (s : S) (max_bytes : I64) : IO (Result StreamError ByteBuf)
    def write (s : S) (buf : ByteBuf) : IO (Result StreamError I64)
    def close (s : S) : IO Unit
}

A byte stream. read of a zero-length buffer is END OF STREAM, never an error; write writes ALL of the buffer and reports its full length; close never fails.

typeFdStream#
pub type FdStream {
    fdstream
}

A stream over one file descriptor. Opaque, like Child: compiled, the value IS the descriptor; interpreted, it is a slot in the evaluator's stream registry whose slots 0/1/2 are stdio. The constructor is never built -- never pattern-match, compare or print one.

Never use an FdStream after Stream.close: the same value may already name a LATER stream (the OS reuses the descriptor number compiled, the registry reuses the slot interpreted), so a stale read or write lands on someone else's file.

instance_#
pub instance Stream FdStream {
    def read (s : FdStream) (max_bytes : I64) : IO (Result StreamError ByteBuf) := do {
        let r <- IO.mk (stream_read s max_bytes);
        return (stream_result r)
    }
    def write (s : FdStream) (buf : ByteBuf) : IO (Result StreamError I64) := do {
        let r <- IO.mk (stream_write s buf);
        return (stream_result r)
    }
    def close (s : FdStream) : IO Unit := IO.mk (stream_close s)
}
defFdStream.read_mode#
pub def FdStream.read_mode : I64

FdStream.open_file's modes.

defFdStream.write_mode#
pub def FdStream.write_mode : I64

Create or truncate.

defFdStream.append_mode#
pub def FdStream.append_mode : I64

Create or append (every write lands at the end).

defFdStream.open_file#
pub def FdStream.open_file (path : Path) (mode : I64) : IO (Result StreamError FdStream)

Open path for reading (FdStream.read_mode), writing (FdStream.write_mode: created 0644, or truncated) or appending (FdStream.append_mode).

defFdStream.raw_fd#
pub def FdStream.raw_fd (s : FdStream) : IO I32

The raw descriptor, for FFI calls that take one (SSL_set_fd).

defFdStream.of_raw_fd#
pub def FdStream.of_raw_fd (fd : I32) : FdStream

Adopt a raw descriptor an FFI call handed back (a pty master).

COMPILED ONLY: compiled, an FdStream IS the descriptor; interpreted, it is a slot in the evaluator's stream registry, so adopting an arbitrary descriptor would alias a stranger. Callers must pass a descriptor the OS just produced for them (forkpty's master), and a test harness that uses this is self-hosted/LLVM-only by construction.

defFdStream.poll_read#
pub def FdStream.poll_read : I64

FdStream.poll's readiness bits (poll(2)'s POLLIN/POLLOUT).

defFdStream.poll_write#
pub def FdStream.poll_write : I64
defFdStream.poll#
pub def FdStream.poll (s : FdStream) (events : I64) (timeout_ms : I64) : IO (Result StreamError Bool)

Wait up to timeout_ms for readiness: ok true ready, ok false timed out. The deadline belongs to the caller; this is one wait, not a loop.

defFdStream.seek_start#
pub def FdStream.seek_start : I64

FdStream.seek's origins (lseek(2)'s SEEK_SET/SEEK_CUR/SEEK_END).

defFdStream.seek_current#
pub def FdStream.seek_current : I64
defFdStream.seek_end#
pub def FdStream.seek_end : I64
defFdStream.seek#
pub def FdStream.seek (s : FdStream) (offset : I64) (whence : I64) : IO (Result StreamError I64)

Move the stream's offset to offset bytes from whence and return the new offset from the start. Only a file seeks; a pipe, socket or terminal is an error. seek 0 seek_end is the file's size.

defFdStream.set_timeout#
pub def FdStream.set_timeout (s : FdStream) (recv_ms : I64) (send_ms : I64) : IO (Result StreamError Unit)

A socket's per-read and per-write timeout (SO_RCVTIMEO/SO_SNDTIMEO). A read or write that exceeds it fails with timed_out. Only sockets accept this; a file descriptor is invalid_input. A write that hits the bound may already have sent a PREFIX of its buffer: that stream is not resumable (a retry would duplicate the prefix), so abandon the connection rather than retry.

defFdStream.stdin#
pub def FdStream.stdin : FdStream

Writes to stdout go through the C runtime's stdio buffer (Rust's Stdout when interpreted) -- IO.println and IO.write_stdout are exactly such writes -- and IO.flush_stdout flushes them.

defFdStream.stdout#
pub def FdStream.stdout : FdStream
defFdStream.stderr#
pub def FdStream.stderr : FdStream

Written unbuffered -- a log line must not wait for a flush.

typePartialLinePolicy#
pub type PartialLinePolicy {
    /// Hand it over anyway (stdin's historical policy).
    deliver,
    /// Drop it: on a protocol pipe a frame without its terminator is a
    /// truncated message, not a message.
    discard
}

What a line reader does with a final line cut off by end of stream rather than by \n.

instance_#
pub instance Copy PartialLinePolicy {
    def copy (p : PartialLinePolicy) : Pair PartialLinePolicy PartialLinePolicy :=
        Pair.pair p p
}

A two-way tag: sharing one is a register move.

defFdStream.read_line_bounded#
pub def FdStream.read_line_bounded (s : FdStream) (max_len : I64) (policy : PartialLinePolicy) : IO (Result StreamError (Option String))

One line from s, WITHOUT its \n (a \r stays). Result.ok Option.none at end of stream. A line longer than max_len bytes is invalid_input; max_len <= 0 means unbounded.

Specialised to FdStream rather than generic over [Stream S]: the self-hosted backend miscompiles a constrained generic's dictionary call (plans/implementations/2026-10-18-compiled-constrained-generic- dict-call-miscompiles.md) -- the generic version segfaulted compiled while passing interpreted. Go back to [Stream S] once that is fixed.