A tour: building wc
Your first program showed the language one feature at a time.
This page reads a whole program instead: examples/wc.maxon, a working replacement for Unix wc
that counts its files on every processor of the machine.
It is the file you can read on the Examples page, unedited. The program carries no comments — the code is meant to answer for itself, and a tour is where the why belongs. Read the left column top to bottom and you will have read the whole program.
What it does
Section titled “What it does”wc [flags] FILE...It prints the lines, words and bytes of every FILE, and their total when there is more than one.
-l, -w and -c choose which of those columns to print; with no flag it prints all three.
$ wc a.txt b.txt 3 9 47 a.txt 2 3 16 b.txt 5 12 63 totalA word is a run of bytes that are not whitespace, and a line is a line feed — the counts wc
documents. It exits 0 normally and 1 when a flag is wrong or a file cannot be read.
Names first
Section titled “Names first”typealias Tally = int(0 to u64.max)typealias WorkerCount = int(1 to 64) implements ElementIndex
typealias PathArray = Array with FilePathtypealias FlagArray = Array with Flagtypealias Column = function(Counts) returns Tallytypealias ColumnArray = Array with Columntypealias CounterArray = Array with Counter.handletypealias CountPromise = Promise with (Counts, FileReadError)typealias CountPromiseArray = Array with CountPromise
let programPathArgument = 0let mostWorkers = 64
enum Outcome counted = 0 troubled = 1end 'Outcome'
enum Whitespace tab = 0x09 lineFeed = 0x0A carriageReturn = 0x0D space = 0x20end 'Whitespace'The file opens with nothing but names.
The first two are ranged type aliases. A number in a type
position states the values it may hold: WorkerCount = int(1 to 64) cannot hold 0, so no code that
receives one has to wonder whether it is about to start no workers at all.
The rest are container aliases. A generic type is instantiated by naming it — Array with FilePath
— and always through an alias, so every container in the program wears a domain name. Column is a
function type: a value that takes some Counts and gives a number. Counter.handle names a
service that the program has not started yet. See Collections.
Enums can carry a value. Outcome gives the exit codes names; Whitespace names the bytes the
word scanner treats as gaps, so it never compares against a bare 0x20.
enum Flag lines = "-l" words = "-w" bytes = "-c"
function summary() returns String return match self 'describe' lines gives "count lines" words gives "count words" bytes gives "count bytes" end 'describe' end 'summary'
function column() returns Column return match self 'pick' lines gives function(counts Counts) gives counts.lines words gives function(counts Counts) gives counts.words bytes gives function(counts Counts) gives counts.bytes end 'pick' end 'column'end 'Flag'
enum UsageError implements Error unknownFlag noFiles invalidPath
function message() returns String return match self 'describe' unknownFlag gives "unknown flag" noFiles gives "name at least one FILE" invalidPath gives "a FILE holds a character this system forbids in paths" end 'describe' end 'message'end 'UsageError'Two more enums, and both do work.
Flag’s raw values are the strings a person types. That is the whole flag table: the spelling,
the help text in summary(), and in column() what the flag selects.
column() returns a closure — a function written as a value. Each of the three picks one field
out of a Counts. The rest of the program holds them as Columns and never asks which is which.
Every body here is one match expression: match self 'describe' … end 'describe' produces a
value, each arm using gives. Every case is listed and there is no default, so a new flag cannot be
added without its help text and its column. The label 'describe' is repeated on end, which is what
keeps nested blocks readable.
UsageError implements Error, which is all it takes to be throwable. An error is an ordinary
enum, cheap to make and exhaustive to handle. See Error handling.
Reading the command line
Section titled “Reading the command line”type Options export var paths = PathArray.create(0) export var columns = ColumnArray.create(0)
static function parse(args StringArray) returns Options throws UsageError let options = Self{} let chosen = FlagArray.create(0)
for (argument, text) in args.withIterator() 'eachArgument' if argument.index() == programPathArgument 'programPath' continue end 'programPath'
if text.startsWith("-") 'aFlag' chosen.push(try Flag.fromRawValue(text) otherwise throw UsageError.unknownFlag) end 'aFlag' else 'aFile' options.paths.push(try FilePath.from(text) otherwise throw UsageError.invalidPath) end 'aFile' end 'eachArgument'
if options.paths.isEmpty() 'nothingToCount' throw UsageError.noFiles end 'nothingToCount'
for flag in Flag.allCases 'eachColumn' if chosen.isEmpty() or chosen.contains(flag) 'shown' options.columns.push(flag.column()) end 'shown' end 'eachColumn'
return options end 'parse'end 'Options'Options is a plain record. Its fields carry defaults, so Self{} builds a complete value.
Self is how a type names itself; a record literal may only be written inside its own type, which
keeps construction in the type’s hands. export on a field makes it readable outside the type.
args.withIterator() hands back the position and the value together, so the loop can skip the
program’s own path. Each branch of the if/else names what it decides — 'aFlag', 'aFile' —
and repeats that name on its end.
try Flag.fromRawValue(text) otherwise throw UsageError.unknownFlag is the everyday shape of error
handling: a call that can fail and, on the same line, what to do instead. The enum turns a typed string
back into a case, so an unknown flag is caught without a chain of comparisons.
The columns are chosen by walking Flag.allCases — generated by the compiler, in declaration order —
so wc -w -l prints lines before words, as wc does, whatever order the flags were typed in.
Counting
Section titled “Counting”extension int function isWhitespace() returns bool return self == Whitespace.space or (self >= Whitespace.tab and self <= Whitespace.carriageReturn) end 'isWhitespace'end 'int'
type Counts export var lines = 0 as Tally export var words = 0 as Tally export var bytes = 0 as Tally
static function zero() returns Self return Self{} end 'zero'
static function of(content ByteArray) returns Self let counts = Self{bytes: content.count() as Tally} var inWord = false
for b in content 'eachByte' if b == Whitespace.lineFeed 'lineEnds' counts.lines = counts.lines + 1 end 'lineEnds'
if not b.isWhitespace() and not inWord 'wordStarts' counts.words = counts.words + 1 end 'wordStarts'
inWord = not b.isWhitespace() end 'eachByte'
return counts end 'of'
static function ofFile(path FilePath) returns Self throws FileReadError let content = try File.readBinary(path) return Self.of(content) end 'ofFile'
function add(other Counts) self.lines = self.lines + other.lines self.words = self.words + other.words self.bytes = self.bytes + other.bytes end 'add'end 'Counts'extension int adds a method to a primitive type: self is the byte, and the comparisons read the
Whitespace constants directly, because an enum with raw values compares with the numbers it names.
Counts is the three numbers and the ways to make them. of is the whole of counting — one pass
over the bytes, a line at each line feed, a word wherever a non-blank byte follows a blank one. inWord
is the only state it needs. ofFile reads a file and counts it, and throws FileReadError because the
read can fail.
content.count() answers the array’s own index type, and the as Tally converts it. Two aliases with
the same range are still two types — a count of bytes and a position in an array do not mix by
accident.
add writes the other count into this one. A method that assigns to self’s fields needs no marking;
records are passed by reference, so the caller’s Counts is the one that changes.
type Counter static function create() returns Self return Self{} end 'create'
export function count(path FilePath) returns isolated Counts throws FileReadError return try Counts.ofFile(path) end 'count'end 'Counter'Counter is the type that becomes a service, and it is an ordinary type. export on a method
marks the message API: what another thread may ask this type to do. count reads one file and
answers its counts, or throws FileReadError when the file cannot be read.
A message says how its data crosses to the other thread. path FilePath is a value, so the sender
passes a copy and needs no word. returns isolated Counts is a value the service
gives away: the caller owns the counts outright once the reply arrives. A record parameter or reply with
neither word is refused where the service is spawned. Numbers, strings, paths and service handles need no word.
See Concurrency.
Reporting
Section titled “Reporting”type Report let columns as ColumnArray var total = Counts.zero() export var troubled = false
static function create(columns ColumnArray) returns Self return Self{columns: columns} end 'create'
function addCounts(counts Counts, label String) self.total.add(counts) printRow(counts, label: label) end 'addCounts'
function addFailure(label String) printError("wc: {label}: cannot read\n") self.troubled = true end 'addFailure'
function printRow(counts Counts, label String) let row = StringBuilder.create()
for column in self.columns 'eachColumn' row.append("{column(counts):8}") end 'eachColumn'
print("{row.build()} {label}\n") end 'printRow'
function printTotal() printRow(self.total, label: "total") end 'printTotal'end 'Report'Report holds what the run has seen: the columns to print, the running total, and whether anything
went wrong. addCounts folds a file’s counts into the total and prints its row; addFailure says on
standard error that a file could not be read and records that the run was troubled.
printRow is where the closures are spent: column(counts) calls whichever function the flag chose.
{column(counts):8} is string interpolation with a format specifier — the value, right-aligned in
eight places. A StringBuilder collects the row so it is printed once.
Using the processors
Section titled “Using the processors”function workersFor(files PathArray) returns WorkerCount let processors = Scheduler.processorCount() let wanted = processors if processors < files.count() else files.count() return mostWorkers if wanted > mostWorkers else wanted as WorkerCountend 'workersFor'
function submitCount(replies CountPromiseArray, counter Counter.handle, path FilePath) replies.push(try counter.count(path, sendTimeout: ForeverMs) otherwise (e) 'refused' match e 'why' mailboxFull then panic("submitCount: runs on main's green thread, which no promise names and so nothing cancels, and a send given ForeverMs waits for room — mailboxFull cannot occur") serviceStopped then panic("submitCount: a counter stopped before the files were sent") end 'why' end 'refused')end 'submitCount'
function countFiles(paths PathArray, report Report) let workerCount = workersFor(paths) let counters = CounterArray.create(0)
for _ in 1 to workerCount 'spawnWorkers' counters.push(spawn Counter.create()) end 'spawnWorkers'
let replies = CountPromiseArray.create(0) var nextWorker = 0 as ElementIndex
for path in paths 'sendFiles' let counter = try counters.get(nextWorker) otherwise panic("countFiles: nextWorker stays below the worker count") submitCount(replies, counter: counter, path: path) nextWorker = (nextWorker + 1) mod workerCount end 'sendFiles'
for (file, reply) in replies.withIterator() 'receiveCounts' let path = try paths.get(file.index()) otherwise panic("countFiles: one reply per file") let counts = try await reply otherwise 'unreadable' report.addFailure("{path}") continue end 'unreadable'
report.addCounts(counts, label: "{path}") end 'receiveCounts'
for counter in counters 'shutDown' counter.shutdown() end 'shutDown'end 'countFiles'spawn turns a type into a service running on its own green thread, scheduled across the
machine’s processors. spawn Counter.create() runs the factory over there and hands back a
Counter.handle. workersFor starts one per processor, or one per file when there are fewer files —
the as WorkerCount at the end is checked at run time, and Options.parse has already guaranteed at
least one file.
try counter.count(path, sendTimeout: ForeverMs) returns once the message is queued. It
hands back a promise, so every file is in flight before the first answer is read. path is a value, so
the service gets a copy of its own. See the memory model.
A send is a try because it can fail on the spot: a service’s mailbox holds at most 1024 messages, and
a stopped service takes none. sendTimeout: ForeverMs makes a send to a full mailbox wait its turn
until a worker takes a message, so mailboxFull reaches only a cancelled coroutine. submitCount runs
on main’s own green thread, and the panic in that arm says why it is unreachable.
try await reply otherwise 'unreadable' takes each answer back, in the order the files were named,
not the order the workers finished — so the output is the same at one worker or sixty-four. A message
that was queued always runs, so its reply carries what the handler returns or throws: a file that
could not be read reaches the 'unreadable' block, which reports it and moves on to the next reply.
A service outlives the function that spawned it until someone says otherwise, so every worker is shut down explicitly. See Concurrency.
Finishing
Section titled “Finishing”function printUsage(problem UsageError) printError("wc: {problem.message()}\n\n") printError("usage: wc [flags] FILE...\n") printError("Counts the lines, words and bytes of every FILE, and their total.\n\n")
for flag in Flag.allCases 'eachFlag' printError(" {flag.rawValue}\t{flag.summary()}\n") end 'eachFlag'end 'printUsage'
function main() returns ExitCode let options = try Options.parse(CommandLine.args()) otherwise (problem) 'badUsage' printUsage(problem) return Outcome.troubled end 'badUsage'
let report = Report.create(options.columns) countFiles(options.paths, report: report)
if options.paths.count() > 1 'severalFiles' report.printTotal() end 'severalFiles'
return Outcome.troubled if report.troubled else Outcome.countedend 'main'printUsage walks Flag.allCases again, so the help text cannot fall behind the enum.
try Options.parse(…) otherwise (problem) 'badUsage' binds the error that was thrown, and the handler
block can then do several things with it before main returns.
main returns an ExitCode, and Outcome.troubled is one, because the enum’s raw values are the
exit codes. Outcome.troubled if report.troubled else Outcome.counted is an if expression —
the conditional produces a value rather than choosing a statement.
Run it yourself
Section titled “Run it yourself”maxon build examples/wc.maxon./examples/wc -l -w examples/*.maxon