Grammars
A [grammar] section gives Kami the full syntax of a language. With it, Kami reads a file the way a compiler would and gives the same kind of answers that its C reader gives: whether the file is valid and, if not, the line where it stops being valid; every definition with its scope and body; each use linked to the definition it refers to; members found by the type of what they are taken from; and the blocks that fold. This page explains how to write a grammar, and the [language] keys that only a grammar uses.
1. How a grammar is read
A grammar is a parsing expression grammar over Kami's tokens, not over characters: the lexer has already found the strings, comments and names. language_parse() compiles the section after it has read the rest of the file, and language_symbols_build() runs it on a file through language_grammar_build(). The grammar does not see comments, the tokens of directive lines, or the body of a heredoc.
The grammar is compiled once, with the language. Each file is read from its first token, by the rule named file.
The section has its own rules of form:
- Each rule is one line
name = expression. A rule name may hold letters, digits,_and-, and starts at the very beginning of its line. - A line that starts with a space or a tab continues the rule above it, so a long rule can span lines.
- A line whose first character (after any spaces) is
;is a comment, and blank lines are ignored. A#does not start a comment here. - The rule named
fileis where reading starts, and every grammar must have one. A rule may refer to rules written below it. - The section ends at the next line that starts with
[.
2. Terms
| Term | Matches |
|---|---|
"if" or 'if' |
A token with exactly this text (in any case when the language is not case-sensitive). A literal never matches a string or a character token, nor any part of one. A literal may take part of a longer token only when that token is in split-operators and the part ends within its first 3 characters (the > of >>), or when it is the prefix of an attribute ("@" NAME reads @name). |
NAME |
A name that is not a keyword (a word in soft-keywords is allowed). |
WORD |
Any name, keywords included. |
LOWER |
A NAME that starts with a small letter or _ (Rust's bindings, as opposed to None). |
NUMBER, STRING, CHAR |
A number, a string (not a regex), a character constant. |
REGEX, VARIABLE |
A regex literal; a variable written with its sigil ($x). |
OP |
Any operator, but not a bracket, ; or , (write those as literals). |
ANY |
Any one token. |
END |
The end of the file. |
NEWLINE, INDENT, DEDENT |
The end of a line, a deeper line, and the end of a deeper part. These exist only with a layout (see Layout). |
SAMELINE |
Takes nothing: succeeds when the next token is on the line where the last one ended. |
JOINED |
Takes nothing: succeeds when the next token touches the last one, with no space between (one shell word). |
NOTHING |
Takes nothing and always succeeds. With :close-tag, it stands for an end tag that may be left out (HTML's <p>). |
<style> |
A token of that style: <tag>, <heading>, <attribute> (see Styles). |
rule |
Another rule, by its name. |
Combining terms
| Written | Means |
|---|---|
a b |
a then b. |
a / b |
a, or if that fails, b. The first alternative that matches without skipping a broken statement is taken. The last alternative is taken whenever it matches, skips or not; only when it does not match is the first alternative that matched with a skip taken. A choice can have up to 64 alternatives. |
( ... ) |
A group. |
a?, a*, a+ |
a at most once, any number of times, at least once. A repetition stops when a no longer moves forward. |
&a, !a |
Look ahead without taking anything: succeeds if a would match, or would not. |
3. Annotations: what a name means
A term that matches one token can carry an annotation after a colon, such as NAME:function. An annotation on a longer term is not allowed, and an unknown annotation is a fault. The annotations are logged while the file is read, the log of an alternative that fails is dropped, and at the end the log becomes the model's symbols, scopes and uses.
| Annotation | The token is | Symbol kind |
|---|---|---|
:function, :method |
The name of a function being defined. | SEMANTIC_FUNCTION |
:class, :struct, :namespace, :module |
The name of a type that holds members. | SEMANTIC_TAG |
:type |
The name of a type (an alias, a typedef). | SEMANTIC_TYPEDEF |
:variable |
A variable defined in the scope it is in. | SEMANTIC_VARIABLE |
:var |
A variable of the nearest scope that is a definition's body (a function's or a class's), or of the file; not of an @scope or @block it is in: JavaScript's var. A second var of the same name there is a use of the first. |
SEMANTIC_VARIABLE |
:constant, :enumerator |
A constant, an enumerator. | SEMANTIC_ENUMERATOR |
:field |
A member defined in a type. | SEMANTIC_MEMBER |
:parameter |
A parameter, defined in the scope it is in: write the parameter list inside the function's @body(...), as the Tiny example of Language Files does. A parameter written before @body would itself be the last definition and take the body; for a parameter written before the body, use :receiver. |
SEMANTIC_PARAMETER |
:label, :macro |
A label, a macro. | SEMANTIC_LABEL, SEMANTIC_MACRO |
:import |
A name brought in by an import; it counts as a variable. | SEMANTIC_VARIABLE |
:assign |
An assignment: defines a variable, unless a symbol of that name is already visible (then it is a use), whatever its kind; only a member of another scope does not count. With assign-scope = local, it defines in its own scope unless :global said otherwise. |
SEMANTIC_VARIABLE |
:assign-file |
A variable of the file, unless a visible one has the name (the shell's x=1). |
SEMANTIC_VARIABLE |
:global |
A name that later assignments in this scope send to the outer name (Python's global and nonlocal). |
|
:use |
A use of a name, linked to its definition through the scopes around it. | |
:member |
A name after ., found by the type of what stands before it. A name right after a . that has no annotation is found the same way. |
|
:member-assign |
self.x = ...: defines a member of the class around it, when what stands before the dot is one of the self-words, there is a class around it, and the class has no member of that name yet. Otherwise the name is a use of a member. |
SEMANTIC_MEMBER |
:property |
A member of the class around it, written elsewhere: TypeScript's constructor(private x). |
SEMANTIC_MEMBER |
:typeref |
The type of the last definition (so that its members can be found later). | |
:returns |
The return type of the function whose body this is. | |
:receiver |
A parameter of the next body: Go's s in func (s T) M(). |
SEMANTIC_PARAMETER |
:method-of |
The type that the next function belongs to: Go's T in func (s T) M(). |
|
:owner |
The type that the next body belongs to: Rust's impl T. |
|
:open-tag, :close-tag |
An element's name, and a closing name that must be the name of the nearest open element (markup). | |
:ignore |
Not a name of the code: a keyword argument's name. |
4. Scopes, bodies, blocks and recovery
| Construct | Means |
|---|---|
@scope(e) |
What e matches is a scope of its own: names defined inside are not visible outside (a lambda, a comprehension). |
@body(e) |
A scope that is the body of the last definition before it, when that definition has no body yet: a function's parameters and statements, a class's members. It is the symbol's body. After an :owner name, the body is that type's instead (when a type of that name is found). |
@block(e) |
A block that defines nothing of its own (Python's if): a scope with block_only set. Like every scope of the model, it can be folded. |
@many(e) |
e repeated until the end of the enclosing group (the end of the file, a DEDENT or a closing bracket). A statement that does not parse is noted as a fault and skipped (to after its ; or line end, or to the closer it is inside), so the rest of the file is still read and its definitions still found. |
@many(e, stop) |
The same, stopping where stop would match (it is not taken) or at the end of the file: @many(statement, "end"). Closing brackets do not stop it, so ) and ] may be text (LaTeX). |
When a file is not valid, the model's problem names the first fault with its line, in one of these forms: "line 12: 'else' was not expected here", "line 3: what starts here is never closed", "line 5: the statement ends too soon", "line 9: the file ends too soon", or "line 4: a string with no end" (or a comment). A string or comment with no end makes the file invalid even where the grammar took it (loose-strings excuses a string, never a comment); it is the problem named when the open token comes before the first statement that was skipped. The definitions are still found in the parts that parse.
Kami remembers where rules failed and most of where they matched, so it seldom reads a rule twice at one place. Even so, a file has a budget of steps: 400,000 and 3,000 more for each token. A grammar that would take more on some file gives up on it, language_grammar_build() returns -1, and language_symbols_build() uses the [symbols] patterns for that file instead. Rules nested more than 4,000 deep at one place also stop the match: that file is then not valid, but the grammar's model is kept.
A name that is not annotated is a use, found through the scopes around it; a keyword is never one, unless it is annotated (with :use, for example). A rule's name is kept to its first 47 characters. When two rules have the same name, the first is the one used. An empty alternative (a / ) matches nothing, and always matches.
Faults in a grammar
A grammar with a fault is not used at all: language.grammar stays NULL, language.grammar_problem says what is wrong, and the patterns take over for every file. These are faults: a literal with no end, or an empty one (""); an unknown rule (an upper-case word that is no class is looked up as a rule: "no rule X"), style or annotation; a missing file rule; text after a rule's end; a ( or @...( with no ); an @ word other than scope, body, block or many; more than 64 alternatives; a term out of place, such as an annotation on a group; a <style> with no >, or with a name of 32 characters or more; and a line that starts at the left edge without being a rule, such as a # line.
5. Layout: lines and indentation
Many languages end statements at the end of a line, or make blocks by indentation. The layout key, in [language], gives the grammar NEWLINE, INDENT and DEDENT tokens for that (LanguageLayout):
| Value | The grammar gets |
|---|---|
| (none) | Only the tokens. Line ends do not count. |
lines |
A NEWLINE at the end of each line that has tokens, and one at the end of the file. |
indent |
NEWLINEs, and an INDENT when a line is deeper than the line before and a DEDENT for each level a line goes back (Python). |
offside |
Haskell's offside rule: after a word in layout-open, a block opens at the column of the next token. When that column is not deeper than the block around it, the block is empty (an INDENT and at once a DEDENT). |
These [language] keys adjust the layout and the grammar's view of the tokens:
| Key | What it does |
|---|---|
layout-ignore-in |
Brackets inside which a line end is not a NEWLINE: ( [ {. The innermost bracket decides, so a block in braces inside a call's parentheses still has its NEWLINEs. The #{ ... } and ${ ... } of a string also hide line ends, so interpolated code can take several lines. A list. |
layout-continue-after |
A line that ends with one of these continues on the next line (Go's +, Ruby's ,). The marker <operator> stands for every operator except : = ; :: *. Such a word does not join a line that dedents (the last value of an enum, with its comma). |
layout-continue-before |
A line that starts with one of these continues the line above (a leading .). The marker <attribute> stands for a line that starts with an attribute and is deeper than its block, after a token that is not : or = (Nim's pragma under its proc's header). |
layout-block-after |
Only with layout = indent. A line that ends with one of these, followed by a deeper line, opens a block. Inside brackets that hide line ends, this lets Nim pass a proc ... = or a do: as an argument; the block closes when a line dedents under it or at the closing bracket. Outside brackets it applies to a word that also continues a line (Scala 3: def f =), so a one-line body and a many-line body both give NEWLINE, INDENT and DEDENT. |
layout-open |
For the offside layout: the words after which a block opens at the next token's column (Haskell: where let do of). |
layout-restart |
Words that no expression continues with: a line inside brackets that starts with one, no deeper than the innermost bracket's line, closes every open bracket, inside brackets that hide line ends (Python's def, class, return). This keeps one unclosed bracket from swallowing the rest of the file. |
operator-characters |
Any run of these characters is one operator, listed or not (Haskell: <$ >=> .:). This one changes the lexer, in any language. |
underscore-operators |
true: a name that ends in _ goes on with a run of the operator characters (Scala: unary_!), but not after a lone _. Lexer. |
dotted-operators |
true: a dot, letters and a dot are one operator (Fortran: .det.); a word of [words] such as .true. keeps its own style. Lexer. |
digit-names |
true: digits followed by letters that make no number are a name, as Vala reads 3DES_CBC. Lexer. |
continuation-in-strings |
true: the line-continuation character at the end of a line inside a string continues the string, and the same character at the start of the next line is skipped (Fortran). Lexer. |
soft-keywords |
Keywords that count as a NAME where the grammar wants a name (Python's match, case, type, _). They keep the keyword style. |
split-operators |
Tokens that a literal may take apart: >>, so Vec<Vec<T>> closes two type argument lists. A list. |
self-words |
Words for the object itself: self this. self.x is then a member of the class around it. A list. |
class-scope |
hidden: a method sees its class's names only through self (Python). Otherwise they are visible directly. |
assign-scope |
local: an assignment defines a variable in its own scope (Python, unless global or nonlocal says otherwise). Otherwise an assignment reaches a visible name outside. |
sigil-free-names |
true: $x and ${x} refer to the variable that x=1 defines (shell). |
loose-strings |
true: a string with no end is no fault, so the file can still be valid (INI values). |
More rules of the indent layout:
- A lone
line-continuationcharacter at the end of a line (in every layout butoffside) joins the lines and is not a token for the grammar. - A line that dedents to a column between two levels opens a level of its own.
- A bracket that keeps its line ends closes the blocks that opened in it.
The offside layout follows GHC's rules:
incloses the block of itslet(the lastletthat has noinyet) and the blocks that opened in it. When the layout already closed that block,incloses nothing more.- A bracket of
layout-ignore-in(Haskell:{) has no layout inside it, except for the blocks that open in it. - A line that starts with
|at the column of a block closes the block, and so does a line that starts withwhere; awherealso closes an opendoblock. - A
,inside the brackets around a block closes the blocks that opened in those brackets. Outside brackets, a,closes only aletblock. A,between a|and its->or=is part of the guard and closes nothing. - Inside brackets, a
|after the->of an alternative closes its block. recopens a block only at the start of a statement.- A file that does not begin with
moduleis one block. - After a
layout-openword, a{opens an explicit block with no layout. \caseopens a block of alternatives.
6. Code the grammar does not read
The grammar sees only the code that counts. The lines from #if 0 to its #endif (or to an #else or #elif at the same level), the later branches of conditional code (see conditional-words on Language Files), and the body of a FreeBASIC #macro ... #endmacro are hidden from it. A conditional mark at the start of a directive line hides its whole line. The lexer still gives these lines their tokens and styles, and brace pairing still sees them.
7. Writing a grammar
- Start with
file = @many(statement) ENDand a few kinds of statement, and grow the grammar rule by rule. Use the language's reference grammar as a guide. - Choose a
layoutif line ends or indentation matter, and setlayout-ignore-infor the brackets inside which they do not. - Annotate the names that define things, put each function's parameters and statements inside
@body(...), and annotate uses with:useand members with:member. - Keep the
[symbols]patterns: they are the fallback for a file on which the grammar gives up. - Check the result on real files: a valid file that the model calls invalid points to a missing rule, and
problemgives its line. After every change, checkgrammar_problemafterlanguage_parse(): a grammar with a fault has no effect at all.
Kami API
The whole library
Reading C and C++
Braces
Any language
