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

[Feature Requst] Methods for converting strings to nodes and tokens #49

Open
duskmoon314 opened this issue Feb 26, 2022 · 0 comments
Open

Comments

@duskmoon314
Copy link

Hi. I'm trying to implement a parser for a mini-language in the way that rust-analyzer's syntax crate does. To be more specific, the language is a kind of subset of C. Thus there are no trailing commas. When I want to generate code for a list like (Node (',' Node)*), I find there are no ways to convert a string to a token that presents a comma.

Am I missing any APIs? If not, is it possible to add two methods to convert strings to nodes or tokens?

I did a little bit of simple experimentation and this may work:

impl Grammar {
    ...

    /// Returns a node with given name
    pub fn get_node(&self, name: &str) -> Option<Node> {
        self.nodes.iter().position(|n| n.name == name).map(Node)
    }

    /// Returns a token with given name
    pub fn get_token(&self, name: &str) -> Option<Token> {
        self.tokens.iter().position(|t| t.name == name).map(Token)
    }
}

And an example working on ungrammar.ungram:

let n = grammar.get_node("Rule");
println!("Get n {:?}", n);

let t = grammar.get_token(":");
println!("Get t {:?}", t);
Get n Some(Node(2))
Get t Some(Token(8))

I'm not sure whether this is appropriate. If it is appropriate, I can submit a PR.

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

No branches or pull requests

1 participant