SchrodingerZhu/paguroidea

Error Implementation

SchrodingerZhu opened this issue · 0 comments

fn generate_error() -> TokenStream {
    quote! {
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        pub struct Error {
            pub active_rule: Tag,
            pub expecting: &'static [&'static str],
            pub offset: usize,
        }

        impl core::fmt::Display for Error {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                let expectation = if self.expecting.len() == 1 {
                    self.expecting[0].to_string()
                } else {
                    format!(
                        "{} or {}",
                        self.expecting[0..self.expecting.len() - 1].join(", "),
                        self.expecting[self.expecting.len() - 1]
                    )
                };
                write!(
                    f,
                    "expecting {expectation} for {} at offset {}",
                    self.active_rule, self.offset
                )
            }
        }

        impl core::error::Error for Error {}
    }
}

I want to have something like this in our generated parser and replace the unimplemented!("error message is not implemented"); branch.

@CyanPineapple can you do this?

To get expecting, see how the fusion_lexer function enumerates all the lexical rules. You can construct all the literals as
const EXPECTING : [&str; N] = [...] for each function that may fail.

To get active_rule, you can use tree.tag or parent.tag for active or inactive parser function respectively.