pom icon indicating copy to clipboard operation
pom copied to clipboard

Example with spans

Open NicEastvillage opened this issue 3 years ago • 2 comments

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?

NicEastvillage avatar Nov 08 '20 09:11 NicEastvillage

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

J-F-Liu avatar Nov 08 '20 16:11 J-F-Liu

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))
    }
}

NicEastvillage avatar Nov 08 '20 18:11 NicEastvillage