This chapter is the grammar of Captain source, rule by rule. It is derived
from the specification's grammar, spec/02-grammar.peg, and checked
against the parser the toolchain uses. Where the two differ, this chapter
gives what the parser accepts, and the differences are listed at the end.
Part 3 explains what each construct
means; this chapter says only how it is written.
Notation
The grammar is a parsing expression grammar (PEG):
| Notation | Meaning |
|---|---|
A <- e |
rule A is e |
e1 / e2 |
e1 if it matches, otherwise e2: the first match wins |
e* e+ e? |
zero or more, one or more, optional |
&e !e |
followed by e, not followed by e (consumes nothing) |
'x' |
the literal characters |
[a-z] |
one character from a class |
UPPER |
a token, defined in Tokens |
Ordered choice makes the grammar unambiguous by construction: every input has at most one parse. The parser is a direct transcription, one function per rule, and stops at the first error in a file.
Program structure
Program <- MODULE ModulePath DOT UseDecl* TopDecl* EOF
UseDecl <- USE ModulePath DOT
ModulePath <- TypeIdent (PATHSEP TypeIdent)*
TopDecl <- InfraDecl / ToolRequirement / TestDecl
/ EXPORT? ( EffectDecl / TypeAliasDecl / StructDecl
/ EnumDecl / ProtocolDecl / InstanceDecl / ProcDecl )Every use comes before every declaration (CAP-PARSE-USE). There are no
statements at the top level: code lives in procedures, effects and the
bodies of declarations.
Procedures and effects
ProcDecl <- Ident Param* (ARROW TypeRef)? Block DOT
Param <- Selector TypeRef
EffectDecl <- EFFECT Ident Param+ ARROW TypeRef Block? DOTA procedure may have no parameters, which makes it an entry point only
(nothing can call it from Captain code). An effect has at least one
parameter (CAP-PARSE-EFFECT) and always a result type. An effect without
a body declares one that the runtime or another module implements.
module Example::Forms.
export area width: i32 height: i32 -> i32 [
ret width * height.
].
export greet name: Text [
ret.
].Type declarations
TypeAliasDecl <- TYPE TypeIdent ASSIGN TypeRef DOT
StructDecl <- STRUCT TypeIdent TypeParams? LBRACE FieldList? RBRACE DOT
FieldList <- FieldDecl (COMMA FieldDecl)* COMMA?
FieldDecl <- Selector TypeRef
EnumDecl <- ENUM TypeIdent TypeParams? LBRACK EnumVariant+ RBRACK DOT
EnumVariant <- TypeIdent LPAREN FieldList? RPAREN DOT
/ TypeIdent DOT
ProtocolDecl <- PROTOCOL TypeIdent TypeParams? LBRACK ProtoReq+ RBRACK DOT
ProtoReq <- Ident Param* ARROW TypeRef DOT
InstanceDecl <- INSTANCE TypeIdent TypeArgs Selector Symbol Selector
LBRACK InstanceProc* RBRACK DOT
InstanceProc <- Ident Param* (ARROW TypeRef)? Block DOTA field is written name: Type; the lexer makes name: one selector
token. An enum has at least one variant (CAP-PARSE-ENUM) and a protocol
at least one requirement (CAP-PARSE-PROTOCOL). An instance's two
selectors must be name: and do:, which the checker enforces
(CAP-PROTO-051).
module Example::Types.
type Label := Text.
struct Point { x: i32, y: i32, }.
struct Marker {}.
struct Box[T] { value: T }.
enum Outcome [ Done(at: i64). Pending. ].
protocol Describe[T] [
describe value: T -> Text.
].
instance Describe[Point] name: #plain do: [
describe value: Point -> Text [ ret Text from: (value x). ].
].Declarations with clause bodies
InfraDecl <- InfraKw TypeIdent Param* DeclBody DOT
InfraKw <- CLUSTER / FLEET / VOLUME / LOWERING / LIFECYCLE / FRONTIER
TestDecl <- 'test' String DeclBody DOT
ToolRequirement <- 'requires' 'tool:' StringLit '#path'
'versionAtLeast:' StringLit '#semver' DOT
DeclBody <- LBRACK (Clause (DOT Clause)* DOT?)? RBRACK
Clause <- Ident ClausePair* Block
/ Ident ClausePair+
ClausePair <- Selector KwArgA clause is a verb with keyword pairs, a block, or both; a verb alone is
CAP-PARSE-CLAUSE. Which verbs and selectors a declaration accepts is
decided by the checker against the declaration's clause schema, not by the
grammar (CAP-SCHEMA-*). test and requires are not reserved: they
begin these forms only at the top level, followed by a string and by
tool: respectively.
Blocks and statements
Block <- LBRACK BlockParams? Stmts? RBRACK
BlockParams <- (COLON Ident)+ BAR?
Stmts <- Stmt (DOT Stmt)* DOT?
Stmt <- RET Expr?
/ Ident ASSIGN Expr
/ Exprret with no expression is allowed when it is followed by . or ]. An
assignment is recognised by an identifier followed by :=.
Block is not an alternative of Primary: a block cannot be assigned,
returned or used as an operand. It appears only as a keyword argument and as
the head of a keyword call. Where the call that runs a block wants a value,
the block's value is its last Stmt, which must be an Expr
(Blocks and control); that
is a rule of the checker, not of the grammar.
Expressions
Expr <- KeywordCall
KeywordCall <- Block (Selector KwArg)+
/ OrExpr (Selector KwArg)*
KwArg <- Block / OrExpr
OrExpr <- AndExpr (BAR AndExpr)*
AndExpr <- CmpExpr (AMP CmpExpr)*
CmpExpr <- AddExpr (CmpOp AddExpr)?
CmpOp <- LTE / GTE / NEQ / EQ / LT / GT
AddExpr <- MulExpr ((PLUS / MINUS) MulExpr)*
MulExpr <- Primary ((STAR / SLASH) Primary)*A keyword argument is an operator expression or a block, never an
unparenthesized keyword call. That one rule fixes where every call ends:
f x: g y: z is a single call with selectors x:y:.
A comparison has at most one operator. A second is a targeted error,
CAP-PARSE-CMPCHAIN, not a different parse.
The control forms (ifTrue:, whileTrue:, forEach:, ifOk:ifFail:) and
the frontier form on host:using:do: are ordinary keyword calls in the
grammar. The checker recognises them by their receiver and selectors. The
only block-headed call it accepts is whileTrue:.
Precedence
From tightest to loosest:
| Level | Forms | Associativity |
|---|---|---|
| 1 | primaries: literals, names, ( ), shapes, records |
|
| 2 | * / |
left |
| 3 | + - |
left |
| 4 | = != < <= > >= |
none: at most one per expression |
| 5 | & |
left, short-circuit |
| 6 | \| |
left, short-circuit |
| 7 | keyword call | one call takes every following selector |
ensure that: (metric value) > 85% ;; ensure that: ((metric value) > 85%)
f x: a + b ;; f x: (a + b)
a f: b g: c ;; one call, selector f:g:
(a f: b) g: c ;; two calls
a + f x: b ;; (a + f) x: b, almost always an error
low <= x & x <= high ;; (low <= x) & (x <= high)Each line is an expression, shown with its reading in the comment.
Primaries
Primary <- Quantity / Number
/ TaggedString / String
/ Shape / JsonLiteral / Symbol
/ TRUE / FALSE
/ I32 / I64 / BOOL
/ RecordCtor
/ NameExpr
/ ParenForm
RecordCtor <- TypeIdent TypeArgs? LBRACE (FieldInit (COMMA FieldInit)* COMMA?)? RBRACE
FieldInit <- Selector Expr
Shape <- SHAPE_OPEN (ShapeItem (COMMA ShapeItem)* COMMA?)? RPAREN
ShapeItem <- Selector Expr / Expr
JsonLiteral <- JSON_OPEN JsonMembers? RBRACE
JsonMembers <- JsonString COLON JsonValue (COMMA JsonString COLON JsonValue)*
JsonValue <- LBRACE JsonMembers? RBRACE
/ LBRACK (JsonValue (COMMA JsonValue)*)? RBRACK
/ JsonString / JsonNumber / TRUE / FALSE / NULL
/ Ident / ParenForm
NameExpr <- Ident
/ TypeIdent (PATHSEP (TypeIdent / Ident))* TypeArgs?
ParenForm <- LPAREN Primary Ident+ RPAREN
/ LPAREN Expr RPARENNotes:
i32,i64andboolare primaries so that a type can be passed as an argument, as inList empty: i32. They cannot be names of anything else.- A record names its type with one capitalized name, plus type arguments.
Module::Type { ... }does not parse. - The value of a record field or a shape item is a whole expression,
keyword calls included: the comma or closing bracket ends it.
#( Text from: 1, "b" )is a list of two texts. - A name path may end in a lowercase name. That is how a qualified call's
head is written:
Utc::leap year: y. - Inside
#{ ... }the tokens are JSON's (generation 8): JSON strings and numbers,true,false,null, JSON's whitespace and no comments or trailing commas. A Captain value is a local's name or in parentheses, where Captain's tokens resume. See Writing JSON. - In parentheses, a primary followed by one or more identifiers is member
access, read left to right:
(o sha256 hex). Anything else in parentheses is grouping. The member form is tried first, so(x)is grouping and(x size)is a member.
Types
TypeRef <- I32 / I64 / BOOL / VOID
/ TypePath TypeArgs?
TypePath <- TypeIdent (PATHSEP TypeIdent)*
TypeArgs <- LBRACK TypeRef (COMMA TypeRef)* RBRACK
TypeParams <- LBRACK TypeIdent (COMMA TypeIdent)* RBRACKSquare brackets after a type name are type arguments when they parse as
types; otherwise the [ is left for what follows, such as a procedure
body. So -> Box[i32] [ ... ] has a result type Box[i32] and then a body.
Tokens
The lexical rules in full are in Lexical structure. In grammar form:
Trivia <- ([ \t\r\n] / ';;' (!'\n' .)*)*
TypeIdent <- [A-Z] [A-Za-z0-9_]*
Ident <- !Reserved [a-z_] [A-Za-z0-9_]*
Selector <- [A-Za-z_] [A-Za-z0-9_]* ':' !(':' / '=')
Int <- '0' ![0-9] / [1-9] [0-9]*
Number <- Int ('.' [0-9]+)? ![A-Za-z%_]
Quantity <- Int ('.' [0-9]+)? ('%' / [A-Za-z] [A-Za-z0-9_]*)
StringLit <- '"' (Escape / ![\\"\n] .)* '"'
Escape <- '\\' [\\"ntr0]
String <- StringLit !('#' [A-Za-z_])
TaggedString <- StringLit '#' [A-Za-z_] [A-Za-z0-9_]*
Symbol <- '#' [A-Za-z_] [A-Za-z0-9_]*
SHAPE_OPEN <- '#('
JSON_OPEN <- '#{'Inside a JSON literal, until its matching }:
Trivia <- [ \t\r\n]*
JsonString <- '"' (JsonEscape / !["\\] [^\x00-\x1F])* '"'
JsonEscape <- '\\' (["\\/bfnrt] / 'u' Hex4) ;; a high surrogate pairs with a low
JsonNumber <- '-'? ('0' / [1-9] [0-9]*) ('.' [0-9]+)? ([eE] [+-]? [0-9]+)?
NULL <- 'null'Reserved words, each also requiring that no identifier character follows:
module use export struct enum type protocol instance
cluster fleet volume lowering lifecycle frontier effect
ret i32 i64 bool void true falsePunctuation, longest match first:
PATHSEP '::' ASSIGN ':=' ARROW '->'
LTE '<=' GTE '>=' NEQ '!=' EQ '=' LT '<' GT '>'
PLUS '+' MINUS '-' STAR '*' SLASH '/'
AMP '&' BAR '|' DOT '.' COMMA ',' COLON ':'
LPAREN '(' RPAREN ')' LBRACK '[' RBRACK ']' LBRACE '{' RBRACE '}'Outside strings and comments only ASCII is allowed (CAP-LEX-CHAR). A
leading zero (0640), a point with no digit before it (.5) and _ after
a number are CAP-LEX-NUM. An escape outside the set is CAP-LEX-ESC, and
a string that reaches the end of its line is CAP-LEX-STR.
Deliberate non-features
Some things other languages have are left out on purpose, and writing them is an error with its own message. Each keeps one obvious way to write a thing, or keeps a parse from depending on what the reader knows.
| Written | Error | Write instead |
|---|---|---|
t trimmed |
CAP-PARSE-SEP: no bare postfix sends |
(t trimmed) |
x := [ ... ], ret [ ... ] |
CAP-PARSE-BLOCKVALUE: blocks are not values |
pass the block where it is used |
a < b < c |
CAP-PARSE-CMPCHAIN |
(a < b) & (b < c) |
-x |
CAP-PARSE-EXPR: no unary minus |
0 - x |
n % 2 |
CAP-LEX-CHAR: no remainder operator |
arithmetic with /, * and - |
0640 |
CAP-LEX-NUM: no leading zeros |
"0640"#mode |
[ "a", "b" ] |
CAP-PARSE-SEP: blocks are not lists |
#( "a", "b" ) |
"a", "b" to join |
CAP-PARSE-SEP |
"a" append: "b" |
!flag |
CAP-LEX-CHAR |
(flag not) |
Not an error, but a common misreading: f x: g y: z is one call with
selector x:y: and arguments g and z. Nest with parentheses:
f x: (g y: z).
module Example::Range.
export within low: i32 x: i32 high: i32 -> bool [
ret low < x < high.
].module Example::Blocks.
export later -> i32 [
ret [ 1 ].
].Where the parser and spec/02-grammar.peg differ
The parser is the reference for this chapter. It differs from the specification's grammar in these places:
- Numbers. The parser refuses
.5and a_after a number with their own messages; the PEG simply fails to match them. - Protocol requirements. The parser accepts a requirement with no parameters; the PEG requires at least one.
- Non-ASCII. The parser accepts any UTF-8 inside comments and strings
and refuses it elsewhere, as
spec/01-lexical.mdsays; the PEG's.is any character.