Skip to main content

chumsky_pass

Function chumsky_pass 

Source
pub fn chumsky_pass<F, C>(f: F) -> ChumskyPass<F>
where F: for<'a> Fn(&'a str) -> ParseResult<ChumChildren<C>, Rich<'a, char>>,
Expand description

Creates a pass from a closure that parses a slice into ChumChildren.

chumsky 0.10’s [Parser] trait is tied to the input lifetime, so parsers are built per call (they are cheap) by a small factory function; the closure builds one and runs it against the slice:

use chumsky::prelude::*;
use increparse::{Outcome, Pass, Span};
use increparse_chumsky::{chumsky_pass, ChumChildren};

#[derive(Clone, Debug, PartialEq)]
enum Ctx {
    Ident,
}

// The factory ties the parser to the input lifetime...
fn idents<'a>() -> impl Parser<'a, &'a str, ChumChildren<Ctx>, extra::Err<Rich<'a, char>>> {
    text::ident()
        .map_with(|_name, e| vec![(e.span(), Ctx::Ident)])
        .then_ignore(any().repeated())
}

// ...and the closure is the pass body.
fn idents_pass(slice: &str) -> ParseResult<ChumChildren<Ctx>, Rich<'_, char>> {
    idents().parse(slice)
}

let pass = chumsky_pass(idents_pass);
let source = "one two";
assert!(matches!(pass.parse(source, Span::new(0, source.len(), 0), &Ctx::Ident),
    Outcome::Expand(_)));
Examples found in repository?
examples/mini_lang_chumsky.rs (line 83)
79    fn parse(&self, source: &str, span: Span, ctx: &LangCtx) -> Outcome<LangCtx> {
80        if !matches!(ctx, LangCtx::File) {
81            return Outcome::Failed;
82        }
83        chumsky_pass(|slice: &str| functions_parser().parse(slice)).parse(source, span, ctx)
84    }