Crates.io | chumsky |
lib.rs | chumsky |
version | |
source | src |
created_at | 2021-07-10 20:58:08.605571+00 |
updated_at | 2025-04-13 11:02:32.971767+00 |
description | A parser library for humans with powerful error recovery |
homepage | |
repository | https://github.com/zesterer/chumsky |
max_upload_size | |
id | 421197 |
Cargo.toml error: | TOML parse error at line 27, column 1 | 27 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
Chumsky is a parser library for Rust that makes writing expressive, high-performance parsers easy.
Note: Error diagnostic rendering in this example is performed by Ariadne
Although chumsky is designed primarily for user-fancing parsers such as compilers, chumsky is just as much at home
parsing binary protocols at the networking layer, configuration files, or any other form of complex input validation
that you may need. It also has no_std
support, making it suitable for embedded environments.
&[u8]
and &str
)See examples/brainfuck.rs
for a full
Brainfuck interpreter
(cargo run --example brainfuck -- examples/sample.bf
).
use chumsky::prelude::*;
/// An AST (Abstract Syntax Tree) for Brainfuck instructions
#[derive(Clone)]
enum Instr {
Left, Right,
Incr, Decr,
Read, Write,
Loop(Vec<Self>), // In Brainfuck, `[...]` loop instructions contain any number of instructions
}
/// A function that generates a Brainfuck parser
fn brainfuck<'a>() -> impl Parser<'a, &'a str, Vec<Instr>> {
// Brainfuck syntax is recursive: each instruction can contain many sub-instructions (via `[...]` loops)
recursive(|bf| choice((
// All of the basic instructions are just single characters
just('<').to(Instr::Left),
just('>').to(Instr::Right),
just('+').to(Instr::Incr),
just('-').to(Instr::Decr),
just(',').to(Instr::Read),
just('.').to(Instr::Write),
// Loops are strings of Brainfuck instructions, delimited by square brackets
bf.delimited_by(just('['), just(']')).map(Instr::Loop),
))
// Brainfuck instructions appear sequentially, so parse as many as we need
.repeated()
.collect())
}
// Parse some Brainfuck with our parser
brainfuck().parse("--[>--->->->++>-<<<<<-------]>--.>---------.>--..+++.>----.>+++++++++.<<.+++.------.<-.>>+.")
You can find more examples here.
Chumsky has an extensive guide that walks you through the library: all the way from setting up and basic theory to advanced uses of the crate. It includes technical details of chumsky's behaviour, examples of uses, a handy index for all of the combinators, technical details about the crate, and even a tutorial that leads you through the development of a fully-functioning interpreter for a simple programming language.
The crate docs should also be similarly useful: most important functions include at least one contextually-relevant example, and all crate items are fully documented.
In addition, chumsky comes with a suite of fully-fledged example projects. These include:
logos
impl Read
ers, and zero-copy, zero-alloc parsing.Chumsky contains several optional features that extend the crate's functionality.
bytes
: adds support for parsing types from the bytes
crate.
either
: implements Parser
for either::Either
, allowing dynamic configuration of parsers at run-time
extension
: enables the extension API, allowing you to write your own first-class combinators that integrate with
and extend chumsky
lexical-numbers
: Enables use of the Number
parser for parsing various numeric formats
memoization
: enables memoization features
nightly
: enable support for features only supported by the nightly Rust compiler
pratt
: enables the pratt parsing
combinator
regex
: enables the regex combinator
serde
: enables serde
(de)serialization support for several types
stacker
(enabled by default): avoid stack overflows by spilling stack data to the heap via the stacker
crate
std
(enabled by default): support for standard library features
unstable
: enables experimental chumsky features (API features enabled by unstable
are NOT considered to fall
under the semver guarantees of chumsky!)
Parser combinators are a technique for implementing parsers by defining them in terms of other parsers. The resulting
parsers use a recursive descent strategy to transform a stream
of tokens into an output. Using parser combinators to define parsers is roughly analogous to using Rust's
Iterator
trait to define iterative algorithms: the
type-driven API of Iterator
makes it more difficult to make mistakes and easier to encode complicated iteration logic
than if one were to write the same code by hand. The same is true of parser combinators.
Writing parsers with good error recovery is conceptually difficult and time-consuming. It requires understanding the intricacies of the recursive descent algorithm, and then implementing recovery strategies on top of it. If you're developing a programming language, you'll almost certainly change your mind about syntax in the process, leading to some slow and painful parser refactoring. Parser combinators solve both problems by providing an ergonomic API that allows for rapidly iterating upon a syntax.
Parser combinators are also a great fit for domain-specific languages for which an existing parser does not exist. Writing a reliable, fault-tolerant parser for such situations can go from being a multi-day task to a half-hour task with the help of a decent parser combinator library.
Chumsky's parsers are recursive descent parsers and are capable of parsing parsing expression grammars (PEGs), which includes all known context-free languages. However, chumsky doesn't stop there: it also supports context-sensitive grammars via a set of dedicated combinators that integrate cleanly with the rest of the library. This allows it to additionally parse a number of context-sensitive syntaxes like Rust-style raw strings, Python-style semantic indentation, and much more.
Chumsky has support for error recovery, meaning that it can encounter a syntax error, report the error, and then attempt to recover itself into a state in which it can continue parsing so that multiple errors can be produced at once and a partial AST can still be generated from the input for future compilation stages to consume.
Chumsky allows you to choose your priorities. When needed, it can be configured for high-quality parser errors. It can also be configured for performance.
It's difficult to produce general benchmark results for parser libraries. By their nature, the performance of a parser is intimately tied to exactly how the grammar they implement has been specified. That said, here are some numbers for a fairly routine JSON parsing benchmark implemented idiomatically in various libraries. As you can see, chumsky ranks quite well!
Ranking | Library | Time (smaller is better) | Throughput |
---|---|---|---|
1 | chumsky (check-only) |
140.77 ยตs | 797 MB/s |
2 | winnow |
178.91 ยตs | 627 MB/s |
3 | chumsky |
210.43 ยตs | 533 MB/s |
4 | sn (hand-written) |
237.94 ยตs | 472 MB/s |
5 | serde_json |
477.41 ยตs | 235 MB/s |
6 | nom |
526.52 ยตs | 213 MB/s |
7 | pest |
1.9706 ms | 57 MB/s |
8 | pom |
13.730 ms | 8 MB/s |
What should you take from this? It's difficult to say. 'Chumsky is faster than X' or 'chumsky is slower than Y' is too strong a statement: this is just one particular benchmark with one particular set of implementations and one particular workload.
That said, there is something you can take: chumsky isn't going to be your bottleneck. In this benchmark, chumsky is within 20% of the performance of the 'pack leader' and has performance comparable to a hand-written parser. The performance standards for Rust libraries are already far above most language ecosystems, so you can be sure that chumsky will keep pace with your use-case.
Benchmarks were performed on a 16-core AMD Ryzen 7 3700x.
My apologies to Noam for choosing such an absurd name.
Chumsky is licensed under the MIT license (see LICENSE
in the main repository).