J-F-Liu / pom

PEG parser combinators using operator overloading without macros.
MIT License
496 stars 30 forks source link

Example with spans #43

Open NicEastvillage opened 3 years ago

NicEastvillage commented 3 years ago

This seems like a very neat library, but I am struggling with one thing. I want my AST nodes with have a Span that van point to the characters that resulting in that node:

struct Span {
    begin: usize,
    end: usize,
}

I assume I can use the pos() function to built this. However, I can't see how I would do this. Do you have any examples?

J-F-Liu commented 3 years ago

Use empty().pos() before and after, to get begin and end positions.

NicEastvillage commented 3 years ago

Got it! Even made myself a little helper function. Thanks!

struct Span {
    begin: usize,
    end: usize,
}

trait WithSpan<'a, I, O: 'a> {
    fn with_span(self) -> Parser<'a, I, (Span, O)>;
}

impl<'a, I, O: 'a> WithSpan<'a, I, O> for Parser<'a, I, O> {
    fn with_span(self) -> Parser<'a, I, (Span, O)> {
        (empty().pos() + self + empty().pos())
            .map(|((begin, item), end)| (Span { begin, end }, item))
    }
}