Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

lelwel

> 编程语言
Open source

Resilient LL(1) parser generator for Rust

197 stars0 likes1 views
WebsiteGitHub

About

Resilient LL(1) parser generator for Rust

lelwel

Table of Contents

  • Introduction
  • Error Resilience
  • Grammar Examples
  • Quickstart
  • Error Recovery
  • Grammar Specification
  • License

Introduction

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.

Why Yet Another Parser Generator?

  • Error Resilience: The generated parser may provide similar error resilience as handwritten parsers.
  • Lossless Syntax Tree: Language tooling such as language servers or formatters require all the information about the source code including whitespaces and comments.
  • Language Server: Get instant feedback when your grammar contains conflicts or errors.
  • Easy to Debug: The generated parser is easy to understand and can be debugged with standard tools, as the code is not generated by a procedural macro.

Why LL(1) and not a more general CFL or PEG parser?

  • Error Resilience: It seems to be the case that LL parsers are better suited than LR parsers for generating meaningful syntax trees from incomplete source code.
  • Runtime Complexity: More general parsers such as GLR/GLL or ALL(*) can have a runtime complexity of $O(n^3)$ or $O(n^4)$ respectively for certain grammars. With LL(1) parsers you are guaranteed to have linear runtime complexity as long as your semantic actions and predicates have a constant runtime complexity.
  • Ambiguity: The decision problem of whether an arbitrary context free grammar is ambiguous is undecidable. Warnings of a general parser generator therefore may contain false positives. In the worst case ambiguities may be found at runtime. The PEG formalism just defines ambiguity away, which may cause the parser to parse a different language than you think.

Error Resilience

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.

c
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.

Grammar Examples

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.

…

Quickstart

  1. Write a grammar file and place it in the 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.
  2. Add the following to your Cargo.toml and build.rs files.
    toml
    [dependencies]
    logos = "0.16"
    codespan-reporting = "0.13"
    
    [build-dependencies]
    lelwel = "0.10"
    rust
    fn main() {
       lelwel::build("src/your_grammar.llw");
    }
  3. Start a build. This will create a 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.
  4. Use the lexer and parser modules with the following minimal main.rs file for printing the CST and diagnostics.
…

Error Recovery

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.

  1. The parser skips the expected token in the grammar and tries to match the current input token with the next expected token.
  2. The parser skips the expected token in the grammar and advances to the next input token. The consumed token is put inside of an error node in the CST. This is used inside of loops (* or +), optionals, and alternations with predicates to ensure that the parser makes progress.
  3. If an error occurs inside of a loop and the token is in the recovery set, the loop breaks and parsing continues after the loop.

Grammar Specification

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.

Comments

C-style and C++-style comments can be used.

Example

antlr
// this is a single-line comment
/*
this is a
multi-line comment
*/

Documentation comments can be used before top level definitions.

Example

antlr
/// this is a doc-comment
token A B C;

[!TIP] Documentation comments are shown by the language server on hover.

Token List

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.rs file. 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 in lexer.rs.

Example

antlr
token MyKeyword='my_keyword' Int='' True='true' False='false';

Skip

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

antlr
skip Whitespace Comment;

Right

A right definition allows to specify a list of tokens, which are handled as right associative operators in left recursive rules.

Example

antlr
right '^' '=';

Start

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

antlr
start translation_unit;

Rule

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

antlr
translation_unit: declaration*;

Regular Expressions

Regular expressions are built from the following syntactic constructs.

  • Grouping: (...)
  • Identifier: rule_name or TokenName
  • Symbol: 'token symbol'
  • Concatenation: A B which is A followed by B
  • Alternation: A | B which is either A or B
  • Ordered Choice: A / B which is A or else B
  • Optional: [A] which is either A or nothing
  • Star Repetition: A* which is a repetition of 0 or more A
  • Plus Repetition: A+ which is a repetition of 1 or more A
  • Semantic Predicate: ?1 which is the semantic predicate number 1
  • Semantic Action: #1 which is the semantic action number 1
  • Semantic Assertion: !1 which is the semantic assertion number 1
  • Node Rename: @new_node_name renames the rule syntax tree node
  • Node Elision: ^ prevents creation of the rule syntax tree node
  • Node Marker: new_node_name insert node at position of marker with index 1
  • Commit: ~ commits to a parse in an ordered choice
  • Return: & returns to the parent rule if there is an active error

Ordered Choice

The 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

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustgrammarparserparser-generatorparsing

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言