chumsky icon indicating copy to clipboard operation
chumsky copied to clipboard

Add example of `Label` improving error messages.

Open nathan-at-least opened this issue 2 years ago • 0 comments

The doc-string for Parser::labelled shows asserting that error values have a label, but I have not found a way for these to influence error output.

For example, I expect this code to say something about "expected just bar" or "expected ignored bar", but the error message just says expecting 'b'. I also tried feeding parse errors to the json example, after seeing it used labelled, but it also only produced low level next-character expectations in error messages.

How can I use labels to provide parser users high-level error messages, ie: "unexpected '%', expecting expression"?

use chumsky::prelude::*;

type Error = Simple<char>;

fn main() {
    if let Some(errors) = my_parser().parse("foo").err() {
        for (i, e) in errors.into_iter().enumerate() {
            println!("[{}]\n{}\n", i, e); 
        }   
    }   
}

fn my_parser() -> impl Parser<char, (), Error = Error> {
    just("bar")
        .labelled("just bar")
        .ignored()
        .labelled("ignored bar")
        .map_err(|e: Error| {
            assert!(e.label().is_some());
            e   
        })  
}

nathan-at-least avatar May 23 '22 17:05 nathan-at-least