Captain / Documentation / Part 9. Reference

Diagnostic codes

Contents ↓

Every error the Captain toolchain reports carries a code such as CAP-TYPE-015. The code is stable: tools, editors and tests can match on it. The message and the help line are for people, and their wording may improve from one release to the next, so don't match on them.

This chapter lists every code the toolchain emits for a Captain program and its run, grouped by the stage that reports it. For each code it says what the code means, shows a typical message, and says how to fix the program. Which toolchain release it describes is in Versions and VM generations.

Reading a diagnostic

captain check prints each problem with its code, where it is, the source line, and often a help line that says what to write instead:

Refused by the checker: CAP-TYPE-015
module Book::Invoice.

export lineTotal price: Decimal quantity: i32 -> Decimal [
  ret price * quantity.
].
Terminal
$ captain check invoice.capt
error[CAP-TYPE-015]: cannot apply arithmetic to Decimal and i32
  --> invoice.capt:4:7
4 |   ret price * quantity.
  |       ^^^^^^^^^^^^^^^^
  help: an integer becomes a decimal only when you say so: `(n as: Decimal)`, exactly, at scale 0
checked 1 file as 1 module, 1 with errors

With --json, captain check prints one captain.check/1 document instead. Each diagnostic has code, message, help, path, range and severity fields:

Terminal
$ captain check invoice.capt --json
{"captain":"[..]","diagnostics":[{"code":"CAP-TYPE-015","help":"an integer becomes a decimal only when you say so: `(n as: Decimal)`, exactly, at scale 0","message":"cannot apply arithmetic to Decimal and i32","path":"invoice.capt","range":{[..]},"severity":"error"}],[..]"verdict":"errors"}

The editor support (captain lsp) reports the same codes.

Where codes come from

Prefix Reported by When
CAP-LEX-* the lexer check, build
CAP-PARSE-* the parser check, build
CAP-MODULE-*, CAP-CHECK-READ module assembly check, build
CAP-RESOLVE-* name resolution check, build
CAP-TYPE-* the type checker check, build
CAP-SCHEMA-* clause checking in declarations check, build
CAP-FRONTIER-*, CAP-EFFECT-*, CAP-SECRET-* effect checking check, build
CAP-PROTO-* protocol instances check, build
CAP-TOOL-* tool requirements check, build
CAP-BUILD-* the compiler build
CAP-RUN-* the virtual machine run, and any host that runs a program
CAP-PLAN-*, CAP-REPLAY-* plans and replay run --plan, replay
CAP-SDK-* the Rust SDK an embedding program

A program that fails to lex or parse stops there: the parser reports the first problem in a file and nothing after it. The checker reports every problem it finds. Numbers missing from a family (CAP-TYPE-019 to CAP-TYPE-029, CAP-EFFECT-033, for example) are not used.

CAP-LEX-CHAR

A character that cannot start any token.

  • `!` is only valid as part of `!=` — Captain's "not" is (b not).
  • `#` must start a symbol (`#Name`) or a shape (`#(`)
  • unexpected character `@`

Fix: remove the character, or write the construct Captain has for it.

CAP-LEX-NUM

A numeric literal that is not allowed.

  • integer literals may not have leading zeros, with the help for file modes, use a tagged string: "0640"#mode. A leading zero means octal in other languages; Captain refuses to guess.
  • `_` may not follow a numeric literal — Captain has no digit separators.
Refused by the checker: CAP-LEX-NUM
module Book::Modes.

export mode -> i32 [
  ret 0640.
].

Fix: write the number without leading zeros, or use a tagged value such as "0640"#mode when the digits are a file mode.

CAP-LEX-STR

unterminated string literal: a string has no closing " before the end of the line or file. Fix: close it.

CAP-LEX-ESC

unknown escape sequence in string literal, with the help valid escapes are \\ \" \n \t \r \0. The set of escapes is closed.

Refused by the checker: CAP-LEX-ESC
module Book::Fields.

export separator -> Text [
  ret "\x1f".
].

Fix: use one of the six escapes.

CAP-LEX-JSON

Inside a JSON literal, #{ ... }, a token JSON does not have: a comment, an escape such as \0 or \x41, an unpaired surrogate escape, a raw control character in a string, a number with a leading zero, a +, a unit or a suffix, NaN, whitespace other than space, tab, CR and LF, or a Captain expression not in parentheses. The help says what to write.

Refused by the checker: CAP-LEX-JSON
module Book::Report.

export report n: i32 -> i32 [
  doc := #{ "next": n + 1 }.
  ret 0.
].

Fix: #{ "next": (n + 1) }. See Writing JSON.

CAP-PARSE-EXPECT

The parser expected a particular token and found another: expected `.` after the module path, found identifier `f`, expected `[` to open a block, found identifier `x`. The message names both. Fix: add or correct the token it names; often a missing . or :.

CAP-PARSE-USE

`use` declarations must appear before all other declarations. Fix: move every use to the top of the file, after module.

CAP-PARSE-DECL

A top-level item that is not a declaration: expected a declaration (cluster, fleet, effect, struct, procedure, ...), or expected a declaration after `export`. Captain has no loose statements at the top level: code lives in procedures and in the bodies of declarations. Fix: put the statement inside a procedure.

CAP-PARSE-REQUIRES

A requires declaration with the wrong selectors: expected `versionAtLeast:`, found `atLeast:`. The form is requires tool: "curl"#path versionAtLeast: "7.68.0"#semver.

CAP-PARSE-CLAUSE

clause `capacity` needs `selector: value` pairs or a `[ ... ]` body: a clause in a declaration has neither arguments nor a body. Fix: give it its arguments, or its body.

CAP-PARSE-EFFECT

an effect needs at least one selector: Type parameter. An effect is always called with keyword arguments. Fix: add a parameter.

CAP-PARSE-ENUM

enum `Colour` needs at least one variant. Fix: add a variant.

CAP-PARSE-PROTOCOL

protocol `Show` needs at least one requirement. Fix: add a requirement.

CAP-PARSE-SEP

expected `.` to end the statement, found .... Two common causes have their own help:

  • A unary message sent without parentheses. Captain has no bare postfix sends: a member or unary message is read in parentheses, (name size).
  • A comma used to join values, or a list written in brackets. Text joins with append:, and a list is a shape: #( "a", "b" ).
Refused by the checker: CAP-PARSE-SEP
module Book::Order.

export outOfOrder a: i32 b: i32 -> bool [
  ret (a < b) not.
].

The help says to write ((a < b) not).

CAP-PARSE-BLOCKVALUE

a block is not a value; blocks appear only as call heads or keyword arguments. A block cannot be stored in a variable or returned.

Refused by the checker: CAP-PARSE-BLOCKVALUE
module Book::Handlers.

export handler -> i32 [
  h := [ ret 1 ].
  ret 1.
].

Fix: pass the block directly as the keyword argument that takes it, or make the code a procedure.

CAP-PARSE-CMPCHAIN

comparisons do not chain, with the help write (a < b) & (b < c).

Refused by the checker: CAP-PARSE-CMPCHAIN
module Book::Range.

export within low: i32 x: i32 high: i32 -> bool [
  ret low < x < high.
].

CAP-PARSE-EXPR

expected an expression, found `)` (or end of file). Fix: complete the expression; a missing ] at the end of a file often shows up as this.

CAP-PARSE-JSON

A JSON literal whose structure is wrong: a key that is not quoted, a trailing comma, a missing : or ,, or no value where one belongs.

Refused by the checker: CAP-PARSE-JSON
module Book::Report.

export report -> i32 [
  doc := #{ "a": 1, }.
  ret 0.
].

Fix: JSON has no trailing comma; remove it.

CAP-MODULE-001

source `a.capt` is admitted more than once: the same source file was given to one module session twice. The command line removes duplicate paths before this point, so it is rare; it means a tool built a session with the same file listed twice.

CAP-MODULE-002

`net gross:` is declared more than once in value namespace of module `Shop::Prices`: two files of the same module declare the same name. A module may be split across files, but each name belongs to one of them. Fix: remove or rename one declaration. The checker also reports CAP-RESOLVE-004 for the same declaration.

CAP-MODULE-003

imports `Shop::Text` and `Std::Text` both bind module name `Text`. Procedures from a source module are called through the last segment of its name (Text::shout t: ...), so two imports with the same last segment would be ambiguous. Fix: import only one of them in this file, or rename one module.

CAP-MODULE-CYCLE

module import cycle reaches Loop::A: modules import each other in a circle. Fix: move what both need into a third module that imports neither. This and CAP-CHECK-READ are reported without a source position, and the human-readable output prints them as error: ...; the code appears in the --json document. These two files are one example, checked together in the session that follows them:

Fragment of a.capt
module Loop::A.

use Loop::B.

export one -> i32 [
  ret 1.
].
Fragment of b.capt
module Loop::B.

use Loop::A.

export two -> i32 [
  ret 2.
].
Terminal
$ captain check a.capt b.capt
error: module import cycle reaches `Loop::A`
$ captain check a.capt b.capt --json
{"captain":"[..]","diagnostics":[{"code":"CAP-MODULE-CYCLE","help":null,"message":"module import cycle reaches `Loop::A`",[..]

CAP-CHECK-READ

cannot read bad.capt: stream did not contain valid UTF-8: a file given to captain check exists but cannot be read as UTF-8 text. Fix: check the file's encoding and permissions.

CAP-RESOLVE-001

A name that is not bound: `prices` is not bound here inside a body, or `Total` is not defined. When a visible name is close, the help suggests it.

Refused by the checker: CAP-RESOLVE-001
module Book::Tax.

export withTax price: Decimal -> Decimal [
  ret prices + 1.00.
].

The help says did you mean `price`?.

CAP-RESOLVE-002

A call that resolves to nothing. It has several forms:

  • Decimal has no method `roundTo:` — the receiver has no such method;
  • `frobnicate count:` does not resolve to a procedure, effect, or intrinsic;
  • procedure `twice n:` requires `n:` — a procedure called with the wrong selectors;
  • no `twice n:retries:` in scope; nearest is `twice n:` — a selector that is not a parameter;
  • `Utc::leap years:` is not exported by the imported module — a qualified call to a procedure the imported module doesn't export.

When a habit from another language explains the mistake, the help says Captain's spelling. Rounding is one:

Refused by the checker: CAP-RESOLVE-002
module Book::Prices.

export rounded amount: Decimal -> Decimal [
  ret amount roundTo: 2.
].

The help says every rounding names its scale and mode: (x scale: 2 rounding: #HalfEven).

CAP-RESOLVE-003

unknown module `Std::Missing` or duplicate `use Std::Text`. Fix: correct the module path; give library source files to check and build with the program (captain check app.capt lib/std/utc.capt, or -I lib/std for build); remove the duplicate use.

CAP-RESOLVE-004

A name declared twice: `Point` is declared more than once (or collides with a prelude type), `f` is declared more than once with the same selector spelling, a protocol declared twice, or an enum variant that collides with another variant in scope. Fix: rename one of them.

CAP-RESOLVE-005

An unknown type (unknown type `Pointt`), an unknown protocol in an instance, or `Shape` is not a struct or enum variant that can be constructed. Fix: correct the spelling, or import the module that declares the type.

CAP-RESOLVE-006

The wrong number of type arguments: wrong number of type arguments for `List` (expected 1), `i32` takes no type arguments, or an instance supplying a different number of type arguments than its protocol takes.

CAP-RESOLVE-007

A block parameter that reuses a name already in scope: `line` shadows a binding already in scope. Captain has no shadowing, so a name means one thing throughout a body.

Refused by the checker: CAP-RESOLVE-007
module Book::Lines.

export firstLine lines: List[Text] -> Text [
  line := "first".
  lines forEach: [ :line |
    x := line.
  ].
  ret line.
].

Fix: give the block parameter its own name.

CAP-RESOLVE-008

A member the value doesn't have: Point has no member `z`. As with CAP-RESOLVE-002, the help gives Captain's word when the name comes from another language:

Refused by the checker: CAP-RESOLVE-008
module Book::Names.

export howMany names: List[Text] -> i32 [
  ret (names size).
].

The help says a list's length is `(xs count)`.

CAP-RESOLVE-009

`ret` is not legal here — phase bodies do not return values: a ret inside a declaration's phase body, such as bootstrap [ ... ]. Fix: remove it; a phase body runs its statements and produces no value.

CAP-TYPE-010

A value of the wrong type, or the wrong kind of argument. The most common form is expected Text, found i32; when a number or a bool is given where text is wanted, the help says make text of it with `Text from: value`.

Refused by the checker: CAP-TYPE-010
module Book::Labels.

export label count: i32 -> Text [
  ret count.
].

Other forms of the same code:

  • `and: ` takes a value, not a block, with the help write `a and: (b)`; the argument is evaluated only when it decides the answer. Captain's and: and or: already skip their argument when the receiver decides;
  • `do:` takes a block, `whileTrue:` takes a block;
  • a `whileTrue:` condition must be a bool, found i32 — the last statement of the head block is the loop's condition;
  • this body must return Decimal, but ret carries no value, or this body returns no value, but ret carries one;
  • `x` cannot be bound to a void expression;
  • this block takes 1 parameter(s), but 2 are declared;
  • `body: ` needs portable data, found ... — an argument that must be plain data (no blocks, frontiers or type values);
  • Secret[Opaque] has no canonical text rendering — Text from: on a value that has no text form;
  • expected i32 or i64, found Decimal, expected i32, i64 or Decimal, found Text;
  • `as: ` takes a type (03 §5.5), found Text;
  • `bearer: ` takes a Secret handle, found Text;
  • Block[...] may only appear in parameter position — a struct field of block type.

CAP-TYPE-011

Operands that cannot be compared or combined:

  • dimensions differ: Bytes + Duration — quantities of different dimensions;
  • quantity × quantity has no dimension in v0.1;
  • `<`, `<=`, `>` and `>=` compare two numbers of one type, two quantities of one dimension, or two texts; found Text and i32;
  • `=`/`!=` operands must have the same type: i32 vs i64;
  • `=`/`!=` equality is not defined for Point; compare its fields or elements explicitly;
  • currencies differ: USD and EUR — two money literals, or arithmetic on them, in different currencies;
  • a Rate has no operators; found Rate and Rate — a Rate is an amount and a period, and has no comparison or arithmetic yet.
Refused by the checker: CAP-TYPE-011
module Book::Sizes.

export total -> Bytes [
  ret 8GiB + 5min.
].

Fix: convert explicitly, or compare the parts that have an order or an equality.

CAP-TYPE-012

a shape needs an expected type from its context, with the help pass it to something typed, or construct the concrete type directly. A labelled shape could be any record, so the checker must know which one.

Refused by the checker: CAP-TYPE-012
module Book::Pairs.

export pair -> i32 [
  xs := #( first: 1, second: 2 ).
  ret 1.
].

Fix: return the shape from a procedure with a declared result type, pass it to a typed parameter, or write the struct by name. An unlabelled shape of literals, such as #( 1, 2 ), is a list and needs no context.

CAP-TYPE-013

A shape that doesn't fit the type it is checked against: struct `Point` has no field `z`, missing field `y:`, duplicate label `x:`, a Point shape needs field: labels on every element, List[i32] expects positional elements, not labels, a SymbolSet shape holds symbols only (#Name), or a shape cannot check against i32.

Refused by the checker: CAP-TYPE-013
module Book::Points.

struct Point { x: i32, y: i32 }.

export origin -> Point [
  ret #( x: 0, z: 0 ).
].

CAP-TYPE-014

A struct written by name with the wrong fields: missing field `y:` in `Point { ... }`, `Point` has no field `z`, duplicate field `x:`; or a struct declaration with the same field twice.

Refused by the checker: CAP-TYPE-014
module Book::Points.

struct Point { x: i32, y: i32 }.

export origin -> Point [
  ret Point { x: 0 }.
].

CAP-TYPE-015

Arithmetic or logic on values that don't support it: cannot apply arithmetic to Decimal and i32, or `&`/`|` need bool operands, found bool and i32. Two cases have their own help:

  • A decimal and an integer. Captain never converts one to the other silently. Say so with (n as: Decimal), which is exact. The example at the start of this chapter shows it; the fix is ret price * (quantity as: Decimal).
  • Text. + doesn't join text; append: does, and a number becomes text with Text from: n.
Refused by the checker: CAP-TYPE-015
module Book::Greeting.

export greet name: Text -> Text [
  ret "Hello, " + name.
].

CAP-TYPE-016

unknown unit `GiBx`: a quantity literal with a unit the language doesn't know. Units are a closed registry (spec 03 §3): durations ns, us, ms, s, min, h, d; sizes B, KB, MB, GB, TB, KiB, MiB, GiB, TiB; %; and money as any three capital letters (USD).

Refused by the checker: CAP-TYPE-016
module Book::Sizes.

export limit -> Bytes [
  ret 5GiBx.
].

CAP-TYPE-017

A tagged literal with an unknown tag (unknown tag `#pth`) or an invalid value (invalid `#mode` literal: a mode is 3–4 octal digits). The tags are #path, #url, #mode, #sha256, #cidr, #address, #region and #semver, and the checker validates their values before the program runs.

Refused by the checker: CAP-TYPE-017
module Book::Files.

export mode -> FileMode [
  ret "0999"#mode.
].

CAP-TYPE-018

cannot infer the type arguments of `Option` for bare `None`, with the help give the context an explicit type. A generic enum variant on its own says nothing about its type argument.

Refused by the checker: CAP-TYPE-018
module Book::Maybe.

export nothing -> i32 [
  x := None.
  ret 1.
].

Fix: use it where the type is known, such as a ret from a procedure that declares -> Option[i32].

CAP-TYPE-019

`sign` returns i32, but its body can reach the end without `ret`: a procedure, or an effect that returns data, has a path that falls off the end of its body. There is no implicit return. A path ends at ret, at fail with: in an effect, when both blocks of ifTrue:ifFalse:, ifOk:ifFail: or ifSome:ifNone: end, and in [ true ] whileTrue: [ ... ].

Refused by the checker: CAP-TYPE-019
module Book::Sign.

export sign n: i32 -> i32 [
  (n > 0) ifTrue: [ ret 1 ].
].

Fix: end every path with ret.

CAP-TYPE-030

this computes a value and throws it away, so it does nothing, with the help assign the result: `list := list push: item.`. Values in Captain don't change in place; push: gives a new list, so a statement that ignores the result has no effect.

Refused by the checker: CAP-TYPE-030
module Book::Names.

export names -> List[Text] [
  names := List empty: Text.
  names push: "lost".
  ret names.
].

A collection operation written as a statement is refused the same way, with a help line that says to assign it or to use forEach:, so Smalltalk's do: written as collect: is caught:

Refused by the checker: CAP-TYPE-030
module Book::Shout.

export shout words: Text -> Text [
  (words splitOn: " ") collect: [ :w | w append: "!" ].
  ret words.
].

CAP-TYPE-031

A literal that doesn't fit its type: 4294967295 does not fit in i32, or ... has more digits than a Decimal can hold exactly (38). It is refused, never truncated.

Refused by the checker: CAP-TYPE-031
module Book::Limits.

export biggest -> i32 [
  ret 4294967295.
].

Fix: use a wider type (i64), or a smaller value. A literal converted with as: is read as the type it converts to, so 9223372036854775807 as: Decimal is that number.

CAP-TYPE-032

`#Bankers` is not a rounding mode. A rounding mode written as a literal is checked before the run. The help names the mode you probably meant (#HalfEven for "bankers", #Down for "truncate", #HalfUp for "round"), or lists all seven: #HalfEven, #HalfUp, #HalfDown, #Down, #Up, #Floor, #Ceiling.

Refused by the checker: CAP-TYPE-032
module Book::Prices.

export rounded amount: Decimal -> Decimal [
  ret amount scale: 2 rounding: #Bankers.
].

A mode computed at run time is checked when it is used, and a wrong one is CAP-RUN-RANGE. See Division and rounding.

CAP-TYPE-033

i64 as: i32 is not an exact conversion. Numbers convert with as:, and as: never loses anything, so only the conversions that cannot lose a digit exist: i32 to i64, i32 or i64 to Decimal, and a type to itself. Every other conversion is refused before the program runs. The help says what to do instead:

  • an i64 may not fit an i32: keep it an i64;
  • a Decimal does not become an integer: round it to scale 0 with (x scale: 0 rounding: #Down) and keep it a Decimal;
  • a number becomes text with Text from: n, not as: Text.
Refused by the checker: CAP-TYPE-033
module Book::Counts.

export narrow total: i64 -> i32 [
  ret total as: i32.
].

Text becomes a number with parse:, which gives a Result (Int parse: text). as: on text, or a conversion written the older way, Decimal from: n, is CAP-RESOLVE-002, and its help shows the as: form.

CAP-TYPE-034

`#Constrain` is not an end-of-month rule: the rule of addMonths:endOfMonth: and addYears:endOfMonth:, written as a literal, is #Clamp, #Roll or #Reject, and the help names the one meant. Generation 8 (DR-0035).

CAP-TYPE-035

duplicate key `"a"` in a JSON object: a key appears once in each object of a #{ ... } literal. Keys are compared after their escapes are decoded, so "a" and "\u0061" are the same key. Keys that come from data go through Json object:, which fails with #JsonDuplicateMember instead.

Refused by the checker: CAP-TYPE-035
module Book::Report.

export report -> i32 [
  doc := #{ "id": 1, "\u0069d": 2 }.
  ret 0.
].

CAP-TYPE-036

`size: Bytes` has no JSON encoding: a value in a JSON literal, or given to Json encode:, is of a type with no one JSON form; the message says where it sits, and the help what to write. Quantities have no unit in JSON ((Text from: q) keeps it), Octets no agreed form ((o hex)), enums and Result no agreed tag, and an Option anywhere but a member is written (Json nullable: o). A decode target that holds a Json is refused with the same code.

Refused by the checker: CAP-TYPE-036
module Book::Report.

use Std::Json.

export report wait: Duration -> i32 [
  doc := #{ "wait": wait }.
  ret 0.
].

CAP-TYPE-037

A JSON document where it would cross an effect or an entry: an effect's parameter or result, or the parameter or result of a root module's export, holds a Json. In generation 8 entries and effects take a document's text: Json text: j indent: 0 maxBytes: 1MiB. Effects are refused by captain check; an export when the program is built.

Refused by the checker: CAP-TYPE-037
module Book::Report.

use Std::Json.

effect publish doc: Json -> void.

CAP-TYPE-038

A JSON literal that nests objects and arrays deeper than 128, which Json text: could never write.

CAP-TYPE-039

A block whose value is wanted ends without one (DR-0037): its last statement is an assignment or a ret, it is empty, or its last expression gives nothing. the block of `collect:` must end in the value it gives, or, for a conditional, the `ifTrue:` branch ends without a value, so the conditional gives none. Both branches ending in ret is reported too.

Refused by the checker: CAP-TYPE-039
module Book::Ends.

export doubled text: Text -> Text [
  out := (text splitOn: " ") collect: [ :w | d := w append: w ].
  ret out join: " ".
].

Fix: end the block with the value, [ :w | w append: w ]; or, for a conditional that should only choose what runs, write it as a statement.

CAP-TYPE-040

Two values where one type is needed (DR-0037): the branches of a conditional that gives a value, the branches give different types: `ifTrue:` gives i32, `ifFalse:` gives Text, or an inject:into: block that gives another type than its accumulator. There is no common type and no conversion.

Refused by the checker: CAP-TYPE-040
module Book::Branches.

export label n: i32 -> Text [
  ret (n > 0) ifTrue: [ "positive" ] ifFalse: [ 0 ].
].

Fix: give the same type from both, converting yourself (Text from: 0, (n as: i64)), or end the branch that cannot give it with ret.

CAP-TYPE-041

`ret` cannot leave the block of a collection operation: a ret anywhere inside the block of collect:, select:, reject:, detect:, inject:into: or sortedBy: (DR-0037). ret always leaves the procedure, and these blocks give their last expression instead.

Refused by the checker: CAP-TYPE-041
module Book::Find.

export firstLong words: Text -> Text [
  found := (words splitOn: " ") select: [ :w | ((w size) > 4) ifTrue: [ ret w ]. true ].
  ret "".
].

Fix: detect: stops at the first match; or loop with forEach: and ret from inside it.

CAP-TYPE-042

`n` is outside this collection block and is read-only here: the block of a collection operation assigns a local declared outside it (DR-0037). The block's result is its value; it reads the locals around it but changes none.

Refused by the checker: CAP-TYPE-042
module Book::Count.

export letters text: Text -> i32 [
  n := 0.
  words := (text splitOn: " ") collect: [ :w | n := n + (w size). w ].
  ret n.
].

Fix: fold with inject:into:, (text splitOn: " ") inject: 0 into: [ :n :w | n + (w size) ], or assign in a forEach:.

CAP-TYPE-043

A control form that gives nothing, used as a value (DR-0037): a one-armed conditional gives no value, with the two-branch form as the help, or `forEach:` gives no value for a loop (whileTrue:, forEach:, parallelDo:).

Refused by the checker: CAP-TYPE-043
module Book::Maybe.

export size n: i32 -> Text [
  label := (n > 100) ifTrue: [ "large" ].
  ret label.
].

Fix: give both branches, ifTrue: [ "large" ] ifFalse: [ "small" ]; to build a list, collect: or select: instead of forEach:.

CAP-TYPE-044

a sort key must be a type `<` orders, found bool: the block of sortedBy: gives a key that < does not order (DR-0037). Keys are integers, decimals, Text, quantities of one dimension, instants or dates.

Refused by the checker: CAP-TYPE-044
module Book::Sort.

export ordered text: Text -> Text [
  ret ((text splitOn: " ") sortedBy: [ :w | (w isEmpty) ]) join: " ".
].

Fix: sort by a key that orders, such as (w size). There is no comparator form: sort: [ :a :b | … ] is answered with sortedBy:. To sort by two keys, sort by the minor one first; the sort is stable.

Declarations and clauses

Declarations such as cluster, fleet, volume, lowering, lifecycle and frontier are made of clauses, and each kind of declaration has a fixed set of clauses with fixed selectors (spec 03 §8.7).

CAP-SCHEMA-011

A clause the declaration doesn't have, or a known clause with the wrong selectors: cluster has no clause `capacity minimumServers:burstTo:`, with the help did you mean `capacity minimumServers:burstableTo:`?.

Refused by the checker: CAP-SCHEMA-011
module Book::Forest.

use Provider::Aws.

cluster Forest [
  capacity minimumServers: 1 burstTo: 3.
  provider primary: Aws regions: #( #Singapore ).
].

CAP-SCHEMA-012

duplicate `capacity` clause in cluster `App`: a clause that may appear only once appears twice. Fix: merge them.

CAP-SCHEMA-013

cluster `App` is missing its required `capacity` clause. Fix: add it.

CAP-SCHEMA-014

A clause argument of the wrong kind: `primary: ` expects a provider (e.g. `Aws`), found Text, or `size: ` takes a value, not a block. The expected kinds include a provider, a frontier type, a fleet or lifecycle declared in the module, and a type name. (An argument of an ordinary type, such as an i32, that has the wrong type is CAP-TYPE-010.)

CAP-SCHEMA-015

A clause body where none is allowed (`capacity` does not take a `[ ... ]` body here), or a missing one (`steps` needs a `[ ... ]` phase body).

Frontiers

A frontier is where effects run: the local machine, a cloud account, a host reached over SSH. See Frontiers.

CAP-FRONTIER-020

effect `readFileText path:maxBytes:` is provided by frontier LocalMachine; it is not available here: an effect called outside the frontier that provides it. When the frontier is entered with on host: ... using: ... do:, the help shows how.

Refused by the checker: CAP-FRONTIER-020
module Book::Remote.

use Host::Debian.

export hostname at: Address -> Text [
  server := observe serverAt: at.
  on host: server using: #Ssh do: [
    file := readFileText path: "/etc/hostname"#path maxBytes: 1KiB.
  ].
  ret "done".
].

Inside the block the program is on the SSH host, where readFileText (a local-machine effect) is not available.

The same holds through a procedure: a procedure takes on the place of its caller, so a call is refused where the effects it performs (outside its own frontier blocks) are not available. procedure `firstLine path:` performs effects provided by frontier LocalMachine; it cannot be called in this SshHost block:

Refused by the checker: CAP-FRONTIER-020
module Book::Through.

firstLine path: Path -> Text [
  ret ((readFileText path: path maxBytes: 1KiB) content).
].

export hostname at: Address -> Text [
  server := observe serverAt: at.
  ret on host: server using: #Ssh do: [
    firstLine path: "/etc/hostname"#path.
  ].
].

Fix: call it outside the block and capture its result.

CAP-FRONTIER-021

`status` is captured from outside this frontier block and is read-only here. A frontier block takes copies of the outer values it uses across the boundary; assigning to one inside the block would change nothing outside it, so it is refused.

Refused by the checker: CAP-FRONTIER-021
module Book::Remote.

use Host::Debian.

export restart at: Address -> Text [
  status := "not started".
  server := observe serverAt: at.
  on host: server using: #Ssh do: [
    service name: "app" ensure: #Running.
    status := "started".
  ].
  ret status.
].

Fix: use a new name inside the block, or return what you need from an effect.

CAP-FRONTIER-022

A frontier that cannot be entered as written: no frontier is entered via #Telnet onto Server — check the frontier's entry clauses, or, in an effect declaration, `on:` must name a frontier type, not Text. A host of the wrong type is refused the same way: host: with #Ssh takes a Server, and an address given as Text enters nothing.

Refused by the checker: CAP-FRONTIER-022
module Book::TextHost.

export up at: Text -> Text [
  seen := on host: at using: #Ssh do: [
    r := exec program: "uptime"#path args: #() timeout: 10s.
    (r stdout).
  ].
  ret seen.
].

Fix: make a Server with observe serverAt: from an Address.

CAP-EFFECT-031

An effect called without all its required arguments: effect `wipe disk:backedUpBy:` requires `backedUpBy:`. The case that matters most is a missing receipt: a destructive effect can demand the receipt of an earlier step, and the program cannot call it until it has one.

Refused by the checker: CAP-EFFECT-031
module Book::Disks.

export struct Backup {}.
export struct Wipe {}.

effect backup disk: Text -> Receipt[Backup] [
].

effect wipe disk: Text backedUpBy: Receipt[Backup] -> Receipt[Wipe] [
].

export clean disk: Text [
  wipe disk: disk.
].

The fix is to do the step that produces the receipt and pass it on:

Captain
module Book::Disks.

export struct Backup {}.
export struct Wipe {}.

effect backup disk: Text -> Receipt[Backup] [
].

effect wipe disk: Text backedUpBy: Receipt[Backup] -> Receipt[Wipe] [
].

export clean disk: Text [
  saved := backup disk: disk.
  wipe disk: disk backedUpBy: saved.
].

The same code is reported for any other missing argument of an effect, such as readFileText path: without maxBytes:.

CAP-EFFECT-032

effect `service name:ensure:` cannot run in a check body: an effect called in a place that may not have effects. Check bodies (verify [ ... ] in a cluster, check [ ... ] in a lowering), build and evidence bodies, and tests are effect-free. Fix: move the effect into a phase that allows effects, such as bootstrap.

The blocks of collect: and its family are effect-free too (DR-0037), and frontier forms and fail with: are refused in them as well: effect `listDirectory path:maxEntries:` cannot run in the block of a collection operation, with the help line the blocks of `collect:` and its family are pure (DR-0037): perform effects over a list with `forEach:`, or call the effect before or after and pass its result in.

Refused by the checker: CAP-EFFECT-032
module Book::Cluster.

use Provider::Aws.
use Host::Debian.

cluster App [
  capacity minimumServers: 1 burstableTo: 1.
  provider primary: Aws regions: #( #Singapore ).
  verify [
    service name: "app" ensure: #Running.
  ].
].

CAP-EFFECT-034

effect parameter `machine:` has non-portable type LocalMachine: an effect's parameters must be portable data, because an effect's arguments are recorded and may cross to another machine. A frontier, a module or a type value is not data. (A first parameter on: naming a frontier is different: it says where the effect runs.)

CAP-EFFECT-035

a Receipt-returning effect body produces no explicit value — the runtime mints the receipt on success: a ret with a value in the body of an effect that returns Receipt[...]. Receipts cannot be forged, so the program doesn't make one; the effect's success does. Fix: remove the ret.

CAP-EFFECT-036

procedure `restart path:` performs effects (readFileText path:maxBytes:) and cannot be called in a check body: the procedure version of CAP-EFFECT-032. The checker knows every procedure's effects, so a procedure that has any cannot be called where effects are not allowed, including the block of a collection operation. A procedure with no effects is pure and can be called anywhere.

CAP-SECRET-040

A secret used where it could leak. Secrets live in bindings and in Secret-typed effect arguments only, and move as handles; their bytes appear only inside effect implementations.

  • a Secret value may only be bound to a name or passed to a Secret-typed effect parameter;
  • struct field `password` may not have a Secret type.
Refused by the checker: CAP-SECRET-040
module Book::Login.

use Host::Debian.

deploy conf: Path [
  credential := Secret named: #AwsPrimary.
  copy from: conf to: "/etc/app/app.conf"#path owner: credential mode: "0640"#mode.
].

Here the secret is passed as owner:, which takes text. See Secrets, receipts and grants.

CAP-PROTO-050

An instance that doesn't match its protocol: a missing requirement (instance `Describe[i32] #Plain` is missing requirement `describe value:`), a requirement with the wrong parameter or result type, or a method the protocol doesn't have (`explain` is not a requirement of protocol `Describe` (extra methods are errors)).

CAP-PROTO-051

instance declarations read `name: #sym do: [ ... ]`, found `label: ... do:`.

CAP-TOOL-060

tool `curl` has more than one version requirement: two requires tool: declarations for the same program. Fix: keep one.

CAP-TOOL-061

A requires declaration whose program path or version is invalid, for example expected MAJOR.MINOR.PATCH for "8"#semver.

CAP-BUILD-001

The program checks, but the compiler cannot compile part of it. The message says what: most often `ret` inside a staged block (frontier transition or `parallelDo:`) is not supported in v0.1. A frontier block runs on the other side of a boundary and has no result value. Fix: return after the block. Other forms (captured binding `x` is not a compilable local, ... was not resolved) indicate a compiler limitation; report them.

Run-time errors

A run that fails ends with one line, error[CODE]: message, and exit status 1. The run log records the same code, and a replay reproduces it. These errors are deterministic: the same program, entry and arguments fail the same way every time.

This module has an entry for several of them:

faults.capt
module Book::Faults.

export share total: Decimal ways: Decimal -> Decimal [
  ret total / ways.
].

export fairShare total: Decimal ways: Decimal -> Decimal [
  ret total divide: ways scale: 2 rounding: #HalfEven.
].

export quotient a: i32 b: i32 -> i32 [
  ret a / b.
].

export pick index: i32 -> Text [
  names := #( "ann", "bob", "cy" ).
  ret names at: index.
].

export rounded amount: Decimal places: i32 mode: Symbol -> Decimal [
  ret amount scale: places rounding: mode.
].

export mixed amount: Money -> Money [
  ret (amount + 1.00USD) + 5.00EUR.
].
Terminal
$ captain build faults.capt -o faults.capb
built faults.capb ([..])
$ captain run faults.capb share total=10.00 ways=3
run log: share.runlog
error[CAP-RUN-INEXACT]: 10.00 / 3 has no exact decimal quotient: `/` never drops digits. Say where the quotient is cut and how: `a divide: b scale: 2 rounding: #HalfEven`
$ captain run faults.capb fairShare total=10.00 ways=3
run log: fairShare.runlog
3.33
$ captain run faults.capb quotient a=7 b=0
run log: quotient.runlog
error[CAP-RUN-ARITH]: arithmetic failure (overflow or /0)
$ captain run faults.capb pick index=3
run log: pick.runlog
error[CAP-RUN-LIST]: index 3 out of range (count 3)
$ captain run faults.capb rounded amount=2.345 places=-1 mode=HalfUp
run log: rounded.runlog
error[CAP-RUN-RANGE]: scale -1 is negative; a scale counts decimal places
$ captain run faults.capb rounded amount=2.345 places=2 mode=Bankers
run log: rounded.runlog
error[CAP-RUN-RANGE]: #Bankers is not a rounding mode; the modes are #HalfEven, #HalfUp, #HalfDown, #Down, #Up, #Floor and #Ceiling
$ captain run faults.capb mixed amount=10.00USD
run log: mixed.runlog
error[CAP-RUN-CURRENCY]: currency mismatch: USD vs EUR

CAP-RUN-INEXACT

10.00 / 3 has no exact decimal quotient: `/` never drops digits. / on decimals and quantities is exact or fails. Fix: say where the quotient is cut and how, a divide: b scale: 2 rounding: #HalfEven. See Division and rounding.

CAP-RUN-ARITH

arithmetic failure (overflow or /0), decimal overflow, quantity arithmetic failure, quantity magnitude overflow. Integer arithmetic is checked: an overflow or a division by zero stops the run instead of wrapping. Decimals have 38 digits; a result or a scale that doesn't fit fails the same way. Fix: guard the divisor, or use a wider type.

CAP-RUN-RANGE

A value outside what an operation accepts: a negative scale, a rounding mode computed at run time that is not one of the seven (#Bankers is not a rounding mode; ...), an integer that doesn't fit the octets it is encoded into (300 does not fit in 1 unsigned octets), or a negative value given to leb128:.

CAP-RUN-LIST

index 3 out of range (count 3): at: or at:put: on a list with an index outside 0 to count - 1. Fix: check (xs count) first.

CAP-RUN-INDEX

byte index out of range, byte slice out of range, negative byte index: the same for Octets (at:, sliceFrom:to:).

CAP-RUN-CURRENCY

currency mismatch: USD vs EUR. Money of different currencies has the same type, Money, so unless both amounts are literals (refused by the checker with CAP-TYPE-011), the check happens at run time. Fix: convert explicitly before combining. sortedBy: with Money keys of two currencies fails the same way, before it sorts.

CAP-RUN-TRAP

`sign n:` fell off the end without `ret`: a procedure that returns a value reached the end of its body on a path with no ret. The checker refuses such a procedure (CAP-TYPE-019), so a checked program does not reach this; the virtual machine keeps the check for artifacts built by something else.

CAP-RUN-STACK

call depth limit exceeded: recursion deeper than the call-depth limit (1024 by default). Fix: bound the recursion, or loop instead.

CAP-RUN-EFFECT

effect `readFileText path:maxBytes:` failed: ...: an effect reported failure; the rest of the message is the effect's own reason. The run stops, and the run log records the failure so a replay reproduces it.

CAP-RUN-GRANT

effect `...` demands Grant[...] at `authorizedBy:` but no minted grant is held: an effect that demands a grant was reached without one. Grants are minted only from an approved plan. captain run refuses such an entry before it starts, with error: ... demands Grant[...]: plan it, approve the plan, then run with --plan <approval file>, so this code is the virtual machine's own last check. See Plans and approval.

CAP-RUN-EXEC

entry `...` can start a process (`exec program:args:`); give --allow-exec ...: captain run was not given --allow-exec, and the entry can reach an effect that starts a program the Captain program names: exec, shell or observeProcess, on this machine or another. The run is refused before any effect, with exit status 2, and no run log is written:

clock.capt
module Book::Clock.

export now -> Text [
  r := exec program: "date"#path args: #( "-u" ) timeout: 5s.
  ret ((r stdout) trimmed).
].
Terminal
$ captain build clock.capt -o clock.capb
built clock.capb ([..])
$ captain run clock.capb now
error[CAP-RUN-EXEC]: entry `now` can start a process (`exec program:args:`); give --allow-exec to let it run commands, or --read-only to run only the reporting programs the observation policy lists
$ captain run clock.capb now --allow-exec
run log: now.runlog
[..]

Fix: give --allow-exec if the program may run commands, or --read-only if it only observes through programs that policy lists. The host also refuses such an effect if it is ever reached without consent, as a failed effect (CAP-RUN-EFFECT); the check before the run makes that a last line of defence, not the usual way to meet it. See Host policies.

CAP-RUN-RECEIPT

effect `retire node:fencedBy:` was given a Receipt[Fence] at `fencedBy:` that this program did not mint: every receipt is minted by the virtual machine when its effect completes, and carries an identity derived from the program, the effect and its arguments. A presented receipt whose identity does not match was made up somewhere else, such as by an effect host, and the effect is refused before it runs. A checked program running on a correct host does not reach this.

CAP-RUN-UTF8

characters requires valid UTF-8 Text: (t characters) on text that is not valid UTF-8, which can only come from outside the program.

CAP-RUN-INSTRUCTION-LIMIT, CAP-RUN-TIMEOUT, CAP-RUN-CANCELLED

execution instruction limit exceeded, execution deadline exceeded, execution cancelled: a host that runs programs under a budget (an embedding program, a worker) stopped the run. Fix: raise the limit in the host, or make the program do less.

CAP-RUN-TYPE, CAP-RUN-FIELD, CAP-RUN-DECODE

... on non-..., field access on non-record value, unknown builtin 99, constant out of range. The virtual machine checks every operation, and these codes report a value of the wrong kind, a missing field, or bytecode it cannot decode. A checked program does not reach them; they mean an artifact was damaged or built by something other than the compiler, or a host passed a value of the wrong type.

CAP-PLAN-STALE

An approval is bound to the plan's digest: the program, the entry and its arguments. captain run --plan plans the invocation again and refuses if the digest differs:

release.capt
module Book::Release.

export struct Release {}.

effect announce note: Text authorizedBy: Grant[Release] -> Receipt[Release] [
].

export release note: Text authorizedBy: Grant[Release] -> Text [
  announce note: note authorizedBy: authorizedBy.
  ret "released".
].
Terminal
$ captain build release.capt -o release.capb
built release.capb ([..])
$ captain plan release.capb release note=hello
...
plan file: release.capp
$ captain approve release.capp
approved plan sha256 [..]
minted Grant[Release] (bound to this plan)
approval file: release.capp.approved
$ captain run release.capb release note=goodbye --plan release.capp.approved
error[CAP-PLAN-STALE]: this invocation plans to sha256 [..]
but the approval is for sha256 [..]
(program, entry, or arguments changed since approval — re-plan and re-approve)

Fix: plan and approve again for what you mean to run.

CAP-REPLAY-DIVERGENCE

captain replay runs a program again against its run log, answering every effect from the log. It reports CAP-REPLAY-DIVERGENCE when the run and the log disagree:

  • log was recorded against artifact ..., not this one;
  • run arguments differ from the recorded run;
  • first divergent seq 2 (log has seq 2 ...; run requested ...) — the program asked for a different effect, or the same effect with different arguments or on a different frontier, than the log recorded;
  • seq 3 ... has no log entry, or run finished with 1 recorded effect(s) never requested;
  • the replay ended ..., but the log records ... — every request matched, but the recorded outcomes produce a different result from the one the log's status line records: the outcomes or the status were edited.
Terminal
$ captain replay faults.capb pick.runlog index=3
replay ok (run failed as recorded): [CAP-RUN-LIST] index 3 out of range (count 3)
$ captain replay faults.capb pick.runlog index=2
CAP-REPLAY-DIVERGENCE: run arguments differ from the recorded run

A divergence means the program, its arguments or its log changed since the run. See Determinism, run records and replay.

The Rust SDK

A program that embeds Captain through the Rust SDK gets SdkError values and outcome diagnostics with these codes. See Embedding Captain in Rust and the SDK's pure profile, spec/sdk/CAPTAIN_RUST_SDK_PURE_V1.md. A run that fails inside the virtual machine reports its CAP-RUN-* code as the outcome (failed:CAP-RUN-INEXACT, for example).

Loading an artifact:

Code Meaning
CAP-SDK-LIMITS A configured limit is zero or above its hard maximum.
CAP-SDK-ARTIFACT-LIMIT The artifact is larger than the configured limit.
CAP-SDK-ARTIFACT The bytes are not a valid .capb artifact (bad magic, damaged, wrong format version).
CAP-SDK-VERIFY The artifact fails verification, or needs a newer VM generation than the SDK runs (the artifact needs VM generation N; this SDK runs generation M). Which generation each release runs is in Versions and VM generations.

Planning a pure run:

Code Meaning
CAP-SDK-ENTRY-NOT-FOUND The artifact has no entry point with that exact name.
CAP-SDK-ENTRY-NOT-EXPORTED The entry exists but is not exported.
CAP-SDK-SECRETS-UNSUPPORTED The artifact refers to secrets; the pure profile admits none.
CAP-SDK-EFFECTS-UNSUPPORTED The entry has effects; only pure entries are admitted.
CAP-SDK-ARGUMENT-CARDINALITY The wrong number of arguments.
CAP-SDK-ARGUMENT-NAME An argument missing, given twice, or not a parameter of the entry.
CAP-SDK-ARGUMENT-TYPE An argument is not of the parameter's type; the message names the place (item 1, a field). Nothing is coerced.
CAP-SDK-INPUT-LIMIT The arguments exceed their item, depth or byte limits. Nothing is truncated.

Outcomes of a run that could not produce a valid result:

Code Meaning
CAP-SDK-PURE-EFFECT The run tried to dispatch an effect, which the pure profile never does.
CAP-SDK-PURE-UNKNOWN The run reported an effect with an unknown outcome.
CAP-SDK-PURE-DEFERRED The run was deferred, which a pure run never is.
CAP-SDK-RESULT-TYPE The result cannot cross to the host as an output value.
CAP-SDK-FROZEN-ARGUMENTS The plan's frozen arguments no longer convert.

Verifying a run record:

Code Meaning
CAP-SDK-RUN-RECORD The record is malformed.
CAP-SDK-RUN-RECORD-BINDING The record does not bind this implementation and plan.
CAP-SDK-RUN-RECORD-LIMIT The record exceeds the plan's instruction, result or size limit.
CAP-SDK-RUN-RECORD-MISMATCH Re-executing the plan gives a different record.

Host-specific codes

Some hosts add codes of their own. They are documented with the host, and listed here only so a reader can tell where a code comes from.

  • Forge, Bosun, Gate, Fleet and Mate report their own errors under their own names. When one of them compiles a Captain program, the program's diagnostics keep their CAP-* codes.