Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example with spans #43

Open
NicEastvillage opened this issue Nov 8, 2020 · 2 comments
Open

Example with spans #43

NicEastvillage opened this issue Nov 8, 2020 · 2 comments

Comments

@NicEastvillage
Copy link

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
Copy link
Owner

J-F-Liu commented Nov 8, 2020

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

@NicEastvillage
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants