This chapter describes the tokens a Captain source file is made of: which characters are allowed, how comments, names, numbers, quantities, strings, symbols and shapes are written, and how the lexer settles the few spellings that could be read two ways. The grammar that puts tokens together is in Grammar.
Captain's lexical rules are small and strict. Each kind of value has one spelling, and a spelling that could mean two things is refused instead of guessed. That matters more than usual because Captain programs are often written by a machine and read by a person: the reader should never have to wonder which of two readings the compiler chose.
Characters
A source file is UTF-8 text. Outside string literals and comments it may use only ASCII. Inside a string or a comment any Unicode text is allowed.
module Example::Characters.
;; Comments may say anything: café, naïve, ±.
export greeting -> Text [
ret "Grüß dich".
].A non-ASCII character anywhere else is a lexical error, CAP-LEX-CHAR:
module Example::Characters.
export café -> Text [
ret "coffee".
].Space, tab, carriage return and newline separate tokens and mean nothing else. Captain has no significant indentation and no line-sensitive rules: a statement may run over several lines, and several statements may share one.
Comments
A comment starts with ;; and runs to the end of the line. There are no
block comments.
total := price * count. ;; a comment after code is fineThat line belongs inside a procedure body.
Names
There are two kinds of name, told apart by their first letter:
| Kind | Pattern | Used for |
|---|---|---|
| type identifier | [A-Z][A-Za-z0-9_]* |
module path segments, types, struct and enum names, enum variants |
| identifier | [a-z_][A-Za-z0-9_]*, not a reserved word |
locals, parameters, procedure names, field names |
So Point is always a type or a variant, and point is always a value or a
procedure. A reader can tell which without looking anything up.
Reserved words
These words cannot be identifiers:
module use export
struct enum type protocol instance
cluster fleet volume lowering lifecycle frontier effect
ret
i32 i64 bool void
true falseTwo words are special only in one position. At the top level of a file,
test followed by a string begins a test declaration, and
requires tool: begins a tool requirement. Anywhere else test and
requires are ordinary names.
A reserved word may still be spelled as a selector, so a call such as
metric type: "memory" is legal. But a procedure's parameter takes the name
of its selector (see
Procedures and keyword selectors), so a
procedure declared with a type: parameter cannot read it. Choose another
selector for your own procedures.
Selectors
A selector is an identifier immediately followed by a colon:
url:, ifTrue:, from:. It is one token. The colon must touch the word;
url : is a name followed by a stray colon.
Two spellings that start the same way are not selectors:
x:= 1isx,:=,1. A colon followed by=is always assignment.Utc::leapisUtc,::,leap. A colon followed by a colon is always the path separator.
Punctuation and operators
| Token | Meaning |
|---|---|
. |
ends a top-level form; separates statements |
:: |
separates module path segments |
:= |
assignment |
: |
introduces a block parameter ([ :line \| ... ]) |
\| |
logical or; also ends a block's parameter list |
& |
logical and |
= != < <= > >= |
comparison |
+ - * / |
arithmetic |
-> |
introduces a result type |
( ) |
grouping and member access |
[ ] |
blocks and declaration bodies; type arguments |
{ } |
struct bodies and record construction |
, |
separates items in shapes, records and type lists |
# |
starts a symbol, a shape #(, a JSON literal #{, or a tag |
The lexer takes the longest match, so <= is one token and so is ->.
There are no other operators. In particular:
%is not an operator. It is the percent unit (85%).- There is no unary minus. Write
0 - x. !appears only in!=. "Not" is(b not).
module Example::Remainder.
export odd n: i32 -> bool [
ret n % 2 = 1.
].Numbers
An integer is 0 or a digit 1 to 9 followed by digits. A decimal is an
integer, a point and at least one digit: 2.50, 0.001.
- No leading zeros.
0640is refused withCAP-LEX-NUM. In many languages a leading zero means octal; Captain refuses to guess, and a file mode is written as the tagged string"0640"#mode. - A digit before the point.
.5is refused; write0.5. - A digit after the point.
x := 1.is the integer1followed by the statement's., so there is no ambiguity at the end of a statement. - No separators or other bases.
1_000is refused, and there are no hexadecimal or exponent forms. - No negative literals.
-1is not a literal; write0 - 1.
module Example::Half.
export half -> Decimal [
ret .5.
].An integer literal is an i32 unless its context asks for an i64, and a
decimal literal is a Decimal. A literal too large for its type is refused
when the program is checked (CAP-TYPE-031), never wrapped or truncated.
Integers, booleans and conversion has the rules.
Quantities
A number immediately followed by a unit is a single quantity token:
module Example::Quantities.
export timeout -> Duration [ ret 30s. ].
export disk -> Bytes [ ret 1.5GiB. ].
export threshold -> Percent [ ret 99.9%. ].
export price -> Money [ ret 49.99EUR. ].The unit must touch the number. 8 GiB is the integer 8 followed by the
type identifier GiB, which is a parse error in an expression:
module Example::Quantities.
export disk -> Bytes [
ret 8 GiB.
].The lexer accepts any unit spelling; the checker then looks it up. An
unknown unit is CAP-TYPE-016:
module Example::Quantities.
export disk -> Bytes [
ret 8Gib.
].The units, their dimensions and their arithmetic are in Symbols, quantities and tagged values.
Strings
A string is written in double quotes, on one line. Its value is Text.
The escapes are a closed set:
| Escape | Character |
|---|---|
\\ |
backslash |
\" |
double quote |
\n |
newline |
\t |
tab |
\r |
carriage return |
\0 |
NUL |
Any other backslash sequence is CAP-LEX-ESC, and a newline inside the
quotes is CAP-LEX-STR (an unterminated string). Write \n instead.
module Example::Strings.
export twoLines -> Text [
ret "first
second".
].module Example::Strings.
export twoLines -> Text [
ret "first\nsecond".
].
export quoted -> Text [
ret "say \"hi\"\t(tab)".
].
export length -> i32 [
ret ("Grüß dich" size).
].captain run prints a text result as a string literal, escapes included.
The length of a text counts characters, not bytes:
$ captain build strings.capt -o strings.capb
built strings.capb ([..] bytes, sha256 [..])
$ captain run strings.capb twoLines
run log: twoLines.runlog
"first\nsecond"
$ captain run strings.capb quoted
run log: quoted.runlog
"say \"hi\"\t(tab)"
$ captain run strings.capb length
run log: length.runlog
9Tagged strings
A string immediately followed by # and a tag is a tagged string, one
token. The tag selects a checked type, and the checker validates the
content before the program runs:
module Example::Tags.
export config -> Path [ ret "/etc/app.conf"#path. ].
export network -> Cidr [ ret "10.40.0.0/16"#cidr. ].
export mode -> FileMode [ ret "0640"#mode. ].The # must touch the closing quote. "/etc" #path is a string followed by
the symbol #path. The tags and their checks are in
Symbols, quantities and tagged values.
Symbols
A symbol is # followed by a name: #Running, #HalfEven, #month. It
is a name used as a value, of type Symbol. #( never starts a symbol: it
opens a shape.
Shapes
#( ... ) is a shape: a list of items separated by commas, each item
optionally labelled with a selector. A trailing comma is allowed.
#( "ca-certificates", "curl" ) ;; positional
#( x: 1, y: 2 ) ;; labelled
#( #( 1, 2 ), #( 3 ) ) ;; nested
#() ;; emptyThose are expressions, not statements; each would appear inside a procedure where its type is known. A shape has no type of its own: it is checked against the type its context expects, a list or a struct. Lists and shapes explains how.
JSON literals
#{ ... } is a JSON document written out, with Captain values in it: #{
"count": (files count), "name": name }. Between #{ and its closing }
the lexer reads JSON, strictly: quoted keys, JSON's strings and numbers,
true, false, null, no comments and no trailing commas. A Captain value
is a local's name or is in parentheses, where Captain's own tokens resume.
It needs VM generation 8;
Writing JSON
explains it.
Record construction
A type name followed by braces builds a struct or an enum variant, with each field given once:
Point { x: 1, y: 2 }
Box[i32] { value: 42 }
Some { v: 3 }Structs and enums has the rules.
Ending forms and statements
Every top-level form ends with .: the module line, each use, and each
declaration, including the . after a procedure's closing ]. Inside a
block, . separates statements, and the . after the last statement is
optional.
module Example::Dots.
export one -> i32 [ ret 1 ].
export two -> i32 [ ret 2. ].Reading ambiguous spellings
| Written | Lexes as | Because |
|---|---|---|
8GiB |
a quantity | the unit touches the number |
8 GiB |
integer, type identifier | white space ends the number |
1.5 |
a decimal | a digit follows the point |
1. |
integer, . |
no digit follows the point |
.5 |
error | a decimal needs a digit before the point |
0640 |
error | no leading zeros |
x:= 1 |
x, :=, 1 |
a colon before = is assignment |
x: 1 |
selector x:, 1 |
the colon touches the word |
A::b |
A, ::, b |
a colon before a colon is the path separator |
"a"#path |
a tagged string | # touches the quote |
"a" #path |
string, symbol | white space |
#( 1 ) |
a shape | #( wins over a symbol |
#name |
a symbol | a letter follows # |
a<=b |
a, <=, b |
longest match |
a - -1 |
error | there is no unary minus |