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

Provide a way to add #[attributes] and custom derive to the generated Rule enum #566

Open
dlight opened this issue Nov 26, 2021 · 2 comments

Comments

@dlight
Copy link

dlight commented Nov 26, 2021

pest_derive currently generates a Rule enum without a corresponding enum Rule anywhere in the code. That way, there is no natural place for inserting attributes and custom derive.

My suggestion is that instead of

#[derive(Parser)]
#[grammar = "grammar.pest"]
pub struct MyParser;

The code should be like this:

#[derive(Parser)]
#[grammar = "grammar.pest"]
pub enum Rule;

And then, pest would provide a type GenParser<T>, that stands for generated parser (note: maybe think about a better name), such that GenParser<Rule> would be used exactly like MyParser is currently.

I believe this would require minimal changes in the generated code: instead of impl Parser<Rule> for MyParser { .. } it would generate impl Parser<Rule> for GenParser<Rule> { ... }.

As an added bonus, the code wouldn't have a hidden Rule with no definition or import in the source code, improving discoverability: Rule is written in the code itself and GenParser needs to be imported.

@dlight
Copy link
Author

dlight commented Nov 26, 2021

Actually, no, that wouldn't work.. custom derive can't change the defined enum. It would need to be something like this

#[derive_parser(grammar = "grammar.pest")]
pub enum Rule;

@dlight
Copy link
Author

dlight commented Nov 26, 2021

Well, an alternate design is to add both Rule and MyParser to the source code, and add an attribute to make MyParse refer to Rule or vice-versa. Something like this:

#[derive(Parser)]
#[grammar = "grammar.pest"]
pub struct MyParser;

#[pest_rule(parser = "MyParser")]
pub enum Rule;

Or like this

#[pest_rule(grammar = "grammar.pest")]
pub enum Rule;

#[derive(Parser)]
#[pest_rule(rule = "Rule")]
pub struct MyParser;

With it, one could attach custom attributes to both MyParser and Rule.

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

No branches or pull requests

2 participants