Captain / Documentation / Part 6. The standard library

The `Std` source modules

Contents ↓

Five modules under lib/std/ are written in Captain. They are candidates for a standard library, not published interfaces yet: they work, and they are tested against independent implementations, but their names and signatures may change. All of them except Std::FileTree are pure.

Several exist to reproduce what an ECMAScript program does (UTF-16 ordering, Date.toISOString, JSON.stringify, String.prototype.trim). Captain's own rules differ, on purpose: text is ordered by code point, and time is never read from an ambient clock. These modules are for the case where a format or a contract was defined by JavaScript and the bytes have to match.

Each is used as Using library modules describes: use Std::Utc., call Utc::..., and build with -I lib/std (or -I lib).

Module File VM
Std::Utc lib/std/utc.capt 6
Std::TextUtilities lib/std/text.capt 6
Std::TextLists lib/std/text_lists.capt 2
Std::JsonEncoding lib/std/json_encoding.capt 6
Std::FileTree lib/std/file_tree.capt 6

The file name of Std::TextUtilities does not follow its module name; the compiler goes by the module line, not the file name.

Std::Utc

Calendar arithmetic and ISO 8601 timestamps from integer milliseconds. The time is always an argument: a value the caller observed, never a clock the module reads.

Procedure Gives What it does
isoSeconds milliseconds: i64 Result[Text] the UTC timestamp YYYY-MM-DDTHH:MM:SSZ; years before 0 or after 9999 are written -YYYYYY or +YYYYYY; fails with #DateRange outside ±8.64 × 10^15 ms, the range ECMAScript Date allows
isoMillis milliseconds: i64 Result[Text] the same with milliseconds, ...SS.mmmZ, as Date.prototype.toISOString writes it
sourceTime epoch: Option[Text] nowMillis: i64 Result[Text] isoSeconds of epoch (decimal seconds, as text) if given, else of nowMillis; fails with #EpochSyntax for anything but digits
leap year: i64 bool Gregorian leap year
monthDays month: i64 year: i64 i64 days in the month (1 to 12)
pad number: i64 width: i32 Text the number with leading zeros to at least width characters
digit text: Text i64 the value of one decimal digit; anything else is 0
wide value: i64 i64 returns its argument; used inside the module to make an i64 variable from a literal, which would otherwise be i32

Std::TextUtilities

Text helpers for byte-exact ports of textual formats.

Procedure Gives What it does
slice text: Text from: i32 to: i32 Text the characters at positions from up to but not including to; positions outside the text are ignored rather than faulting
printableAscii text: Text bool every character is printable ASCII, space to ~
quotedAscii text: Text Result[Text] the text in double quotes with \ and " escaped; fails with #AsciiText unless it is printable ASCII
hexDigit text: Text i32 the value of one lowercase hex digit; anything else is 0
utf16Units text: Text List[i32] the UTF-16 code units of the text
utf16SortKey text: Text Text a key whose ordinary text order is the UTF-16 order of the original; compute it once when sorting many items
utf16Compare left: Text right: Text i32 -1, 0 or 1 by UTF-16 code unit order, as JavaScript compares strings
trimEcma text: Text Text removes ECMAScript white space and line terminators from both ends, as String.prototype.trim does
trimEcmaEnd text: Text Text the same, from the end only (trimEnd)

UTF-16 order and code point order differ only for characters above U+FFFF compared with characters from U+E000 to U+FFFF, which is exactly why a port that sorts like JavaScript needs utf16Compare.

Std::TextLists

Procedure Gives What it does
equalOrdered left: List[Text] right: List[Text] bool the same length and the same items in the same order, duplicates included

Captain's = does not compare lists, so this is how two lists of text are compared.

Std::JsonEncoding

Writing JSON text from Captain values.

Procedure Gives What it does
quote text: Text Text a JSON string literal: " and \ escaped, control characters as \u00XX, everything else as itself
quoteEcma text: Text Text the same, but with JSON.stringify's short escapes \b, \t, \n, \f, \r
stringObjectEcma object: JsonTextObject Text a compact JSON object of string members, in JSON.stringify's property order: integer-like keys first in numeric order, then the others in source order

stringObjectEcma takes the JsonTextObject that Json decodeStrict:... produces (JSON and number text), so a program can read a string-valued object and write it back in the order JavaScript would. This is compatibility output, not a canonical form.

Std::FileTree

A bounded, sorted walk of a directory tree, built on listDirectory. It imports Std::TextUtilities, so give the compiler both (-I lib/std).

Procedure Gives What it does
entries root: Path prefix: Text excludedRoot: List[Text] Result[List[FileTree::Entry]] every entry beneath root/prefix, depth first, each directory's entries in UTF-16 order of their names; when prefix is empty, top-level names listed in excludedRoot are skipped (with a non-empty prefix it has no effect). Effect: listDirectory
join root: Path relative: Text Result[Path] root and relative joined with one /; fails with #TreePath if relative is not canonical
canonical relative: Text bool empty, or /-separated components that are not empty, . or .. and contain no NUL or backslash

FileTree::Entry is { path: Text, kind: Symbol }: the path relative to root, and the kind listDirectory reported (#file, #directory, #link, #other). Links are listed, not followed. The walk fails with #TreeLimit past 64 levels or 4096 entries, rather than return part of a tree.

Example

ports.capt
module Example::Ports.

use Std::TextUtilities.
use Std::JsonEncoding.

;; Sort two names the way JavaScript's default sort would.
export jsOrder a: Text b: Text -> Text [
  ((TextUtilities::utf16Compare left: a right: b) > 0)
    ifTrue: [ ret (b append: " ") append: a ].
  ret (a append: " ") append: b.
].

export field name: Text value: Text -> Text [
  ret ((JsonEncoding::quote text: name) append: ":") append: (JsonEncoding::quote text: value).
].

export middle text: Text -> Text [
  ret TextUtilities::slice text: (TextUtilities::trimEcma text: text) from: 1 to: 4.
].
Terminal
$ captain build ports.capt -I lib/std -o ports.capb
built ports.capb ([..] bytes, sha256 [..])
$ captain run ports.capb jsOrder a=$'\U0001F600' b=$'~'
run log: jsOrder.runlog
"😀 ~"
$ captain run ports.capb field name=say value='hi "there"'
run log: field.runlog
"\"say\":\"hi \\\"there\\\"\""
$ captain run ports.capb middle text="  abcdef  "
run log: middle.runlog
"bcd"

U+1F600 is above U+FFFF, so in UTF-16 it starts with a surrogate (0xD83D), which sorts before U+FF5E; by code point it would sort after.