Resilient LL(1) parser generator for Rust
Lelwel (Language for Extended LL(1) parsing With Error resilience and Lossless syntax trees) generates recursive descent parsers for Rust using LL(1) grammars with extensions for direct left recursion, operator precedence, semantic predicates (which also enable arbitrary lookahead), semantic actions (which allow to deal with semantic context sensitivity, e.g. type / variable name ambiguity in C), and a restricted ordered choice (which allows for backtracking).
The parser creates a homogeneous, lossless, concrete syntax tree (CST) that can be used to construct an abstract syntax tree (AST). Special node rename, elision, marker, and creation operators allow fine-grained control over how the CST is built for certain parses.
The error recovery and tree construction is inspired by Alex Kladov's (matklad) Resilient LL Parsing Tutorial. Lelwel uses a (to my knowledge) novel heuristic to automatically calculate the recovery sets, by using the follow sets of the dominators in the directed graph induced by the grammar.
Lelwel is written as a library.
It is used by the CLI tool llw, the language server lelwel-ls, and can be included as a build dependency in order to be called from a build.rs file.
There is a plugin for Neovim that uses the language server.
By default the generated parser uses Logos for lexing and Codespan for diagnostics, however this is not mandatory.
The following example shows the difference between Lelwel and Tree-sitter, a GLR parser generator with sophisticated error recovery, when parsing certain incomplete C source code.
void f() {
g(1,
int x = 2 +
}Lelwel syntax tree
…Tree-sitter syntax tree
…[!NOTE] Tree-sitter is an excellent tool for its intended purpose, which is mainly syntax highlighting. This comparison only demonstrates the possible syntax tree quality of an error resilient parser.
The parser for lelwel grammar files (*.llw) is itself generated by Lelwel. There are also examples for C without a preprocessor (actually resolves ambiguity with semantic context information, unlike examples for ANTLR4 and Tree-sitter), Lua, WGSL, Python 2.7, arithmetic expressions, JSON, TOML, and Oberon-0.
You can try out examples in the Lelwel Playground.
The following example shows a grammar for the toy language "L" introduced by the Resilient LL Parsing Tutorial.
…src directory of your crate.
Optionally you can install the CLI or language server to validate your grammar file: cargo install --features=cli,lsp lelwel.Cargo.toml and build.rs files.[dependencies]
logos = "0.16"
codespan-reporting = "0.13"
[build-dependencies]
lelwel = "0.10"fn main() {
lelwel::build("src/your_grammar.llw");
}lexer.rs and a parser.rs file next to your grammar file.
The lexer.rs and parser.rs files are supposed to be manually edited to implement the lexer and the parser callbacks. The actual parser generated.rs is included in parser.rs and written to the Cargo OUT_DIR.
If you change the grammar after the lexer.rs and parser.rs files have been generated, it may be required to manually update the Token enum or the ParserCallbacks implementation.lexer and parser modules with the following minimal main.rs file for printing the CST and diagnostics.…The lexer may emit an Error token which will always be skipped by the parser. This can be used for some kinds of lexical errors, where there is no other appropriate token.
[!TIP] Usually it makes more sense to generate an error in the lexer and still emit a valid token for the parser. For example you should still emit a string token if your string contains invalid escape sequences, as this will result in a better syntax tree.
The parser tries to parse rules in their entirety. If the parser encounters an invalid token an error is reported via the create_diagnostic method of the ParserCallbacks trait. To avoid cascading errors there is an active error state where no new errors are reported until the next valid token has been consumed.
There are multiple possibilities for the parser to continue after an error, depending on the context in which it occurs.
error node in the CST. This is used inside of loops (* or +), optionals, and alternations with predicates to ensure that the parser makes progress.Lelwel grammars are based on the formalism of context free grammars (CFG) and more specifically LL(1) grammars. There are certain extensions to the classical grammar syntax such as constructs similar to those from EBNF.
A grammar file consists of top level definitions which are independent of their order.
C-style and C++-style comments can be used.
Example
// this is a single-line comment /* this is a multi-line comment */
Documentation comments can be used before top level definitions.
Example
/// this is a doc-comment token A B C;
[!TIP] Documentation comments are shown by the language server on hover.
A token list definition introduces a list of tokens (terminals) to the grammar.
It starts with the token keyword, ends with a ; and contains a list of token names and corresponding token symbols.
A token name must start with a capital letter. The token symbol is optional and delimited by single quotation marks. In a regex a token can be referenced by its name or symbol.
[!TIP] The token symbol is used in error messages and the generator of the
lexer.rsfile. If the token symbol string starts with ``, the token is interpreted as a class of tokens for which the symbol is only a description. This influences how error messages and lexer rules are generated by default inlexer.rs.
Example
token MyKeyword='my_keyword' Int='' True='true' False='false';
A skip definition allows to specify a list of tokens, which are ignored by the parser.
These tokens will however still be part of the syntax tree.
Example
skip Whitespace Comment;
A right definition allows to specify a list of tokens, which are handled as right associative operators in left recursive rules.
Example
right '^' '=';
A start definition specifies the start rule of the grammar.
There must be exactly one start definition in a grammar.
The start rule must not be referenced in a regex.
Example
start translation_unit;
A grammar rule must start with a lower case letter. A regular expression is used to specify the right hand side of the rule.
Example
translation_unit: declaration*;
Regular expressions are built from the following syntactic constructs.
(...)rule_name or TokenName'token symbol'A B which is A followed by BA | B which is either A or BA / B which is A or else B[A] which is either A or nothingA* which is a repetition of 0 or more AA+ which is a repetition of 1 or more A?1 which is the semantic predicate number 1#1 which is the semantic action number 1!1 which is the semantic assertion number 1@new_node_name renames the rule syntax tree node^ prevents creation of the rule syntax tree nodenew_node_name insert node at position of marker with index 1~ commits to a parse in an ordered choice& returns to the parent rule if there is an active errorThe ordered choice operator / has a precedence between alternation and concatenation. Unlike in the PEG formalism, the operator is restricted, such that only one ordered choice can be active at a time.
[!WARNING] This restriction avoids the worst case exponential time complexity of recursive descent PEG implementations without the use of memoization. Due to the unlimited lookahead it is still possible to co
No open issues yet, or sync has not completed.