Grammar
The whole syntax of jihoo, as the parser (compiler/parse.jh) reads
it. Syntax explains it with examples; this page is
the precise version, for checking what parses.
Notation
Section titled “Notation”x y x, then yx | y x or y[ x ] x, or nothing{ x } x any number of times, maybe none"fn" the token itselfname an identifier: a letter or `_`, then letters, digits and `_`sep a `,`, a `;`, or a newline before the next elementTokens
Section titled “Tokens”-
Whitespace is spaces, tabs,
\rand newlines. The lexer records whether a newline came before each token; that is all the parser knows of lines. -
// ...to the end of the line;/* ... */nests. -
Integers:
123,1_000,0xff,0b1010,0o17. Floats:1.5,2e10,1.5e-3(decimal only;1.and.5are not floats). After a., digits are always an integer, sot.0.1is two tuple fields. -
'a'is one byte (u8);'가'is an error, since it is more than one byte."..."is a string, on one line. Escapes in both:\n \t \r \0 \\ \' \" \xNN. -
The keywords:
as break comptime const continue else enum export extern false fn for ifimpl import in inout let loop match move pub ref return sink static structtrait true type unsafe var whileself,Self,null,fnptr,int,never,inline(beforefororif),dyn(before a name orfn) and the primitive types are ordinary names that the compiler gives a meaning to;_is a name too, except in patterns. So arerequires,ensuresandinvariant, which start contract clauses only where a clause can stand, andresultandold, which are special only inside them. -
Some tokens are made of others:
..=is..then=, which is how range patterns take either spelling.
module = { "#![" name "]" } { item | ";" }item = { attr } [ "pub" ] ( import | fn | struct | enum | impl | trait | const | static | alias | family )attr = "#[" name [ "(" name { "," name } ")" ] "]"
import = "import" name { "." name } [ "as" name ]fn = [ "unsafe" ] [ "extern" | "export" ] "fn" name params [ "->" [ "ref" | "inout" ] type ] { clause } [ block ]clause = ( "requires" | "ensures" ) condparams = "(" [ param { "," param } [ "," ] ] ")"param = "..." (last; `extern fn` only) | [ "inout" | "sink" | "comptime" ] name [ ":" type { "+" type } ]struct = "struct" name [ params ] { invariant } "{" { [ "pub" ] name ":" type sep } "}"enum = "enum" name [ params ] "{" { name [ "(" type { "," type } ")" ] sep } "}"impl = "impl" [ params ] type [ "for" type ] "{" { item | ";" } "}"trait = "trait" name [ params ] [ ":" type { "+" type } ] "{" { item | ";" } "}"const = "const" name [ ":" type ] "=" exprstatic = "static" name [ ":" type ] "=" expralias = "type" name [ params ] [ "=" type ]family = "type" name "{" equation { sep equation } [ sep ] "}"equation = type_pat "=>" typetype_pat = "_" | "let" name | path [ "(" [ type_pat { "," type_pat } [ "," ] ] ")" ] | "(" [ type_pat { "," type_pat } [ "," ] ] ")" | "[" type_pat [ ";" type_pat ] "]" | ( "*" | "ref" | "inout" ) type_pat | [ "-" ] integer | "true" | "false" | "type"#![...]attributes come first in the file.#![freestanding]and#![uefi]select runtime profiles; experimental#![dependent_core]selects a restricted source subset using contextualerased(P),if_lt,if_eq,index,decide_lt,refl,transport,induct,fold,lt_add,lt_cancel,lt_le,sub,zero_le,refine,pack,witnessandproofforms, andenumdeclarations, with u64 parameters, andmatchfor data types, andbuffer,alloc,load,storeandfreefor owned buffers; a recursiveenumis heap data, and owned values a scope does not use are freed where it ends;ref Tparameters andletstatements borrow, andinduct(fn(t, a: A) { T }, ...)(a)andabsurd(p)give results that depend on a borrow, in the existing grammar.Lt(i, n)andEq(a, b)are its built-in propositions; in it, atraitwithu64parameters and bodiless functions declares an inductive proposition and its constructors. Induction cases can use contextualfn(...) { ... }proof lambdas. Item attributes are#[view],#[derive(...)](derive),#[interior](unsafe code) and, on functions,#[literal_check(param, check)](compile-time evaluation)#[test](tests) and#[panic_handler](panic handlers).- A parameter’s type may be left out only for
self. A function without a block is a declaration: anextern fn, or a trait function without a default body. Items do not nest inside function bodies. - The parameters of a
struct,enumortraitare compile-time ones whether or not they saycomptime:struct Pair(T: type). Those of animplare written the same way:impl(T: Ord) Ord for Vec(T). type Itemwithout= Tdeclares an associated type in a trait. Parameterized aliases, such astype Mem(n: u64) = buffer(n), are supported only in#![dependent_core]modules, with erasedu64parameters and a required body. See dependent type aliases.- A family is a module item.
Name(T)applies its equations to one concrete type. A tuple supplies several inputs as one type. A single parenthesized pattern groups its contents. Closed type families
type = path [ "(" expr { sep expr } ")" ] Vec(i64), std.map.Map(K, V) | "*" type raw pointer | "[" type "]" slice | "[" type ";" expr "]" array | "(" ")" | "(" type ")" unit; parentheses | "(" type "," [ type { "," type } ] ")" tuple | "fn" fn_ty | "fnptr" fnptr_ty closure; function pointer | "dyn" path | "dyn" "fn" fn_ty owned trait value; owning closure | "impl" path | "impl" "fn" fn_ty a type known while compiling | ( "ref" | "inout" ) type a borrow, as a type argument | "type" the type of typespath = name { "." name }fn_ty = "(" [ fn_ty_param { "," fn_ty_param } ] ")" [ "->" type ]fn_ty_param = [ "inout" | "sink" ] [ name ":" ] typefnptr_ty = "(" [ [ "inout" | "sink" ] type { "," [ "inout" | "sink" ] type } [ "," "..." ] | "..." ] ")" [ "->" type ]... in a function pointer requires a C-compatible value signature.
Named function-type parameters are supported only by fn types in
#![dependent_core] modules. For example, fn(n: u64, buffer(n)) -> i64
names the first argument so the second argument’s type can refer to it.
The name is in scope in later domains and the result, not in its own domain;
unnamed domains remain supported. The dependent subset requires at least one
parameter and an explicit result, uses erased(T) for erased domains, and
rejects inout and sink in function types. Named domains do not extend
fnptr, dyn fn, impl fn, or ordinary code. See
functions in dependent code and the
indexed callback example.
Type arguments are expressions, so a number can be one ([T; N],
Matrix(f64, 3)). The ( of type arguments, and the -> of a function
type, must be on the same line as what comes before.
Blocks and statements
Section titled “Blocks and statements”block = "{" { stmt end } [ expr ] "}"end = ";" | newline | before "}"stmt = ( "let" | "var" | "inout" ) pattern [ ":" type ] "=" expr [ "else" block ] | expr "=" expr | expr opassign expr | expropassign = "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "+%=" | "-%=" | "*%="A block whose last statement is an expression with no ; after it has that
expression’s value. The = or op= of an assignment must be on the same
line as its left side, and the else of a let on the same line as the
end of its value.
Expressions
Section titled “Expressions”expr = range | binaryrange = [ binary ] ".." [ binary ] only as a whole expressionbinary = unary { binop unary } by precedence, below | binary "as" typeunary = ( "-" | "!" | "*" | "&" | "move" ) unary | primary { postfix }postfix = "(" [ expr { sep expr } ] ")" call | "[" expr "]" index or slice | "." name | "." integer field, method, tuple field | "?" early return on None / Err | "{" [ field { sep field } ] "}" struct literal, after a pathfield = name [ ":" expr ]
primary = literal | name | "(" ")" | "(" expr ")" | "(" expr "," [ expr { "," expr } ] ")" tuple | "[" [ expr { sep expr } ] "]" array | "[" expr ";" expr "]" array of copies | block | "unsafe" block | "comptime" unary | "if" cond block [ "else" ( if | block ) ] | "match" cond "{" { pattern [ "if" expr ] "=>" stmt sep } "}" | "while" cond { invariant } block | "loop" { invariant } block | "for" [ name "," ] pattern "in" cond { invariant } block | "inline" "for" name "in" cond block unrolled at compile time | "inline" "if" cond block [ "else" ( "if" cond block ... | block ) ] | "fn" "(" [ cparam { "," cparam } ] ")" [ "->" type ] block closure | "fn" fn_ty | "fnptr" fn_ty | "dyn" type | ( "ref" | "inout" ) type a type | "return" [ expr ] | "break" | "continue"cparam = name [ ":" type ]cond = expr, where a struct literal cannot start (write `(P { x: 1 })`)invariant = "invariant" condA clause’s expression is a cond, so the { of the body ends it; the
contracts page says which
expressions a clause may be.
Precedence
Section titled “Precedence”From loosest to tightest. Binary operators are left-associative.
| level | operators |
|---|---|
| 0 | a..b (a whole expression only) |
| 1 | || |
| 2 | && |
| 3 | == != < <= > >= (they do not chain: a < b < c is an error) |
| 4 | | |
| 5 | ^ |
| 6 | & |
| 7 | << >> |
| 8 | + - +% -% |
| 9 | * / % *% |
| 10 | e as T, which applies to the operand just before it |
| 11 | prefix - ! * & move |
| 12 | postfix f(x) a[i] a.b t.0 e? P { ... } |
So c as i64 * 2 is (c as i64) * 2 and -x as u64 is (-x) as u64.
Unlike C, the bitwise operators are tighter than comparisons, as in Rust:
a & mask == 0 is (a & mask) == 0. Shifts are looser than +:
1 << 2 + 1 is 1 << 3.
A statement ends at a newline, unless the expression cannot end there. The rules:
- A binary operator continues the expression only at the end of a line,
not at the start of the next one.
a\n+ bisa, then the statement+ b, which is an error. - A
.continues the expression from either line, so method chains may start each line with.method(). (,[and?at the start of a line do not apply to what came before:f\n(x)isf, then(x).as,..,=andop=must be on the line of their left side.returntakes a value only on its own line:return\nxreturns nothing.- Inside
( ),[ ]and{ }lists (arguments, arrays, struct fields, enum variants,matcharms), a newline separates elements like a comma.
Closures and types
Section titled “Closures and types”fn(...) starts a closure when a block follows, and is a type otherwise:
fn(x, y: i64) { ... } is a closure (parameter types are optional),
fn(i64) -> bool is a type, written where a value is expected only as a
compile-time argument. move fn(x) { ... } is a closure that owns what
it captures. impl fn(A) -> R and impl Trait are types only as the bound
of a compile-time type parameter (comptime F: impl fn(i64) -> i64) and
as a function’s result (-> impl Iterator).
Struct literals
Section titled “Struct literals”After a path (P, m.P, Pair(i64)), a { on the same line starts a
struct literal if it is followed by }, by name:, by name, or by
name }. In the head of if, while, match and for it never does, so
the { there is the body; put a struct literal there in parentheses.
Patterns
Section titled “Patterns”pattern = single { "|" single }single = "_" | [ "-" ] integer | char a literal | lit ".." [ "=" ] lit a range, both ends included | "true" | "false" | string | name binds, or a variant without payload | "var" name a binding that can change | "(" pattern { "," pattern } ")" tuple | path "(" [ pattern { "," pattern } ] ")" variant with payload | path "{" { name [ ":" pattern ] sep } [ ".." ] "}" structlit = [ "-" ] integer | char- A range pattern includes both ends whichever way it is written:
0..9and0..=9both match 9. (A range expression,0..9in aforloop or a slice, leaves out its end.) - A single name is a variant if the matched type has a variant of that name
without payload (
Stop,None); otherwise it binds. - The alternatives of
A | Bbind the same names, with the same types andvar-ness; the first that matches binds them. A|may also appear inside other patterns:(Some(x), None) | (None, Some(x)).