Repository navigation
Description
IO.printLine (src/stdlib/io.kex:8) is welded to stdout. Meanwhile
FileHandle<R, W> (src/stdlib/filehandle.kex) already carries the entire
vocabulary you would want, gated by typestate:
make FileHandle<CanRead, W>—getLine,get,readLine,read,eof?,
atEnd?,feedmake FileHandle<R, CanWrite>—printLine,print,writeLine,write
The abstraction exists. What is missing is that it is not a named trait, so
nothing else can implement it, and IO does not go through it.
Extract the traits
Readable and Writable, following the existing -able convention
(Showable, Inspectable, Enumerable, Blankable, Errorable). The
existing make blocks become make FileHandle<R, CanWrite>, implement: Writable
— constrained implementations already work, make Optional<Showable>, implement: Showable (src/stdlib/kex.kex:23) is the precedent.
IO.stdout / IO.stderr / IO.stdin then become handle values, and
IO.printLine(x) stays as the ergonomic default meaning
IO.stdout.printLine(x).
Two inconsistencies this forces
Most of the actual work:
- Argument type.
IO.printLine : Showable -> Voidvs
FileHandle.prin 8000 tLine : String -> Bool.Showableis right. - Return type.
VoidvsBool.Boolis a poor error channel, but
Result<Void, IOError>on every print is miserable to use. Erlang's answer
is worth stealing: the call returnsokand failure belongs to the device,
not the call site.
Bytes, without a phantom parameter
Byte-level operations sit beside the text ones on the same handle —
read : String? / readBytes : Bytes, write / writeBytes — using the type
from #138.
No third capability parameter for text vs binary. The R/W parameters
model something the resource genuinely restricts: open O_RDONLY and the OS
refuses the write. Text vs binary restricts nothing — the same fd supports both,
and reading bytes from a handle opened "for text" is well-defined. It is a
per-call decoding choice, and encoding it as a per-handle type parameter
overstates the guarantee, which is the same objection
docs/typestate-file-plan.md already raises against a lifecycle parameter:
A lifecycle parameter can be defeated through an alias without ownership
checking and would overstate the guarantee.
No newline translation. CRLF↔LF is a C/Python legacy and Windows-only;
Erlang and Go do not do it. Nothing in the tree does today — the only \r\n is
HTTP protocol framing in runtime/src/kex_intrinsic_web.erl and REPL line
trimming — so there is nothing to preserve and no reason to introduce it.
Feed<A> is documented but does not exist
docs/streams.md describes a Feed<A> as the one-shot, stateful, foul
counterpart to Stream<A>, with its own row in the summary table
(Feed<A> — not pure, not reusable, "IO resources, event sources") and examples
like foul messages: Feed<Message> = socket.feed.
No such type exists. grep -rn '\bFeed\b' src/ is empty; FS.File.feed is
declared feed : FilePath -> Stream<String>? (src/stdlib/fs.kex:49) and
FileHandle.feed :> Stream<String>?.
That typing is a lie the docs themselves flag: the same table marks Stream<A>
pure and reusable, which a file feed is neither. Consuming a "stream" of file
lines twice cannot work, and nothing currently stops it.
So this issue should settle:
- Whether
Feed<A>becomes a real type distinct fromStream<A>, or the docs
drop it andStreamabsorbs the one-shot case. - Whether
Readableyields aFeedat all, and what a byte feed looks like
— chunked (Feed<Bytes>with a chunk size) rather than per-byte, since a
Feed<Byte>would be the cons-list mistake again. - Backpressure, or the explicit absence of it.
The payoff: sinks as values
Once Writable is a trait, a sink that collects into memory is just another
implementation, and a library can accept one.
Not "so output can be captured in tests" — Mock.IO
(src/stdlib/http.kex:143) already does that on both backends, with
start/stop/output/clear/input. That objection lands, and the case for
this issue does not rest on it.
What Mock.IO is, is a switch rather than a value, and that is what it
cannot do:
- Compose. One global redirect. Output from one library cannot go to a
buffer while another's goes to the terminal. - Be passed. A library cannot accept a sink, so — for example —
OptionParserstill names stdout itself (src/stdlib/optionparser.kex:113,
:122,:137); the mock only moves stdout underneath it. Where its errors go
is a policy decision belonging to the embedding program. - Be anything but a test affordance. A file, a socket, or an in-memory
buffer as an ordinary value is not reachable through it.
See also #141: Mock.IO's capture is evaluator-wide in the interpreter and
per-process on BEAM, so spawned output is captured by one and not the other.
Erlang's answer is the group leader, which a spawned process inherits — and
that is the same mechanism a handle-as-a-value design needs, so the two are
aligned.
Handles do not confer purity
Worth stating so nobody later reads "pass a handle" as "now it is pure".
docs/purity.md: "Pure functions cannot call foul functions — enforced at
semantic analysis". handle.printLine(...) is a call to a foul function, so a
function writing to a passed-in handle is foul no matter where the handle came
from. Injection makes a thing substitutable, not pure.
Only two things would change that, and neither is this issue:
- Return a description instead of performing it — the caller emits. This is
whatOptionParser.help -> Stringalready does;runis foul because it
interleaves deciding what to say with saying it. - Effect polymorphism —
foulparameterised over an argument's effects
(Koka, Frank, Scala capabilities). Kex's model is binary and per-function
with no such form, so this is a language change.
The purity win is therefore a separate and cheaper move than this issue: push
emission to the edge and let libraries return text.
Note: parameterized traits
The cleanest form of all this is Readable<A> / Writable<A>, with Net.HTTP
(#81) falling out of the same abstraction. That does not work today:
grammar.ebnf:107allowstrait Foo<A>, andast::TraitDefcarries a
typeParamsfield (src/ast/ast.hxx:579) —- but
src/semantic/traits.cxxnever readstypeParams; they are parsed and
dropped, - and
grammar.ebnf:124istrait_list = UPPER_IDENT ( COMMA UPPER_IDENT )*,
soimplement: Writable<Bytes>cannot even be written. - All fourteen stdlib traits are nullary.
Dropping the phantom-parameter idea above takes this off the critical path —
separate readBytes/writeBytes methods work with nullary traits. It stays the
better long-term shape and would want its own issue.
Related
-
Binarytype, byte primitives, codecs, and binary I/O #138 —Bytes, needed for the byte-level operations -
Net module —
Http→Net.Http, File-style interface #81 —Net.HTTP, the other consumer of a handle abstraction -
Mock.IO captures spawned-process output in the interpreter but not on BEAM #141 —
Mock.IOcapture diverges between backends; the group-leader model would settle both -
Remove module-level foulness:
foulshould be per-function only #130 — per-functionfoul, which is what letsOptionParser.runbe foul whileparseandhelpstay pure
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
Issue actions
Open in GitHub Copilot app
Activity