Available on crate feature
unstable only.Expand description
Traits and types that allow parsers to be cached between invocations.
§Example
#![feature(lazy_cell)]
use std::sync::{LazyLock, Arc};
use chumsky::{prelude::*, cache::{Cache, Cached}};
#[derive(Debug, PartialEq)]
enum Token<'a> { Ident(&'a str), Int(u64) }
#[derive(Default)]
struct TokenParser;
impl Cached for TokenParser {
type Parser<'a> = Arc<dyn Parser<'a, &'a str, Token<'a>, extra::Default> + Send + Sync + 'a>;
fn make_parser<'a>(self) -> Self::Parser<'a> {
let ident = text::ident().map(Token::Ident);
let num = text::int(10).from_str().unwrapped().map(Token::Int);
Arc::new(ident.or(num))
}
}
// The parser cache doesn't have a lifetime and so can be stored pretty much anywhere:
static PARSER: LazyLock<Cache<TokenParser>> = LazyLock::new(Cache::default);
// The parser can be used from any context simply by calling `.get()` on the cache
assert_eq!(PARSER.get().parse("42").into_result(), Ok(Token::Int(42)));
assert_eq!(PARSER.get().parse("hello").into_result(), Ok(Token::Ident("hello")));Structs§
- Cache
- Allows a parser to be cached for reuse with inputs and outputs of different lifetimes.
Traits§
- Cached
- Implementing this trait allows you to cache parsers for use with inputs of different lifetimes, avoiding the need to recreate the parser for each input lifetime.