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

Enable outer and inner attributes on enum with all unit variants. #35

Merged
merged 1 commit into from
Jan 26, 2025

Conversation

TonyWu20
Copy link
Contributor

@TonyWu20 TonyWu20 commented Jan 22, 2025

This is a quick and dirty hack. I was attempting to get the pest-at derive works on my enums with all variants are unit type. The enum is like this:

MyEnum {
  A,
  B,
  C,
}

And the formatted output and input to be parsed are in the same format like: MyEnum : A, and it is case-insensitive.
So I wrote my .pest grammar as follows:

my_enum = { ^"myenum" ~ ":" ~ my_enum_vars }
my_enum_vars = { ^"A" | ^"B"| ^"C"}

To achieve the conversion from &str to MyEnum, I use my own proc-macro derive crate to generate code like this:

impl MyEnum {
    fn from_str(input: &str) -> Self {
        let lowercase = input.to_lowercase();
        match lowercase.as_str() {
            "a" => Self::A,
            "b" => Self::B,
            "c" => Self::C,
        }
}

and then I added attributes to each variants first.

#[pest_ast(inner(
rule(Rule::my_enum_vars),
with(span_to_str),
with(MyEnum::from_str),
with(Option::unwrap)
))]

The original pest-ast codebase does not apply the conversion on unit variant, as I found in derive/src/from_pest/field.rs. The reason is the convert function accepts (name: &Path, fields: Fields) and Fields is not available for unit variant in enum, provided by the dependency syn crate. However, one can still access to the attributes macros on unit variants by variant.attrs.
Therefore, I edited the convert function in field.rs to accept parameter variant: &Variant for enum case, and leave the original version to be used for struct case. This makes me pass all the existing tests in ast by cargo test.

Still, I don't have the time and knowledge to fully test this with more potential error-prone cases. In my current usage, it seems my mod only need and only can recognise one #[pest_ast] outer or inner attribute. For my intended purpose this is workable enough, since all variants share the same rule and same method to convert to the enum. However, it could be not powerful enough to handle cases with more customisation needed. Finally, as I have zero experience with the development of pest and pest-ast, I believe this kind of mod is of low quality. I was also surprised to see why it seems nobody cares about using pest-ast, this incredible crate, on enum with unit variants. Hopefully, experienced developers of pest can see my efforts and discuss if we can make a better version for this demand. Thank you.

Summary by CodeRabbit

  • Refactor

    • Enhanced attribute handling for derive macro
    • Improved field conversion logic for structs and enums
    • Updated conversion methods to support more complex attribute parsing
  • New Features

    • Added specialized conversion functions for struct and enum fields
    • Introduced more granular attribute processing capabilities

Copy link

coderabbitai bot commented Jan 22, 2025

Walkthrough

The changes introduce a more sophisticated attribute handling system for the FromPest derive macro in Rust. The modifications focus on enhancing attribute parsing and representation by adding new structs and enums in the attributes.rs file. Correspondingly, the field.rs and mod.rs files have been updated to support these new attribute structures, with separate conversion methods for struct and enum fields. The changes aim to provide more granular control over attribute processing during derive macro generation.

Changes

File Change Summary
derive/src/attributes.rs - Added pub(crate) enum FieldAttribute with Outer and Inner variants
- Added pub(crate) struct OuterAttribute
- Added pub(crate) struct InnerAttribute
- Added pub(crate) struct WithAttribute
derive/src/from_pest/field.rs - Renamed convert to enum_convert with updated signature
- Added new struct_convert function
- Enhanced field processing logic for Named, Unnamed, and Unit fields
derive/src/from_pest/mod.rs - Updated function calls from field::convert to field::struct_convert and field::enum_convert

Sequence Diagram

sequenceDiagram
    participant Macro as FromPest Derive Macro
    participant Attributes as Attribute Handlers
    participant FieldConverter as Field Converter
    
    Macro->>Attributes: Parse Field Attributes
    Attributes-->>Macro: Attribute Structures
    Macro->>FieldConverter: Convert Fields
    alt Struct Fields
        FieldConverter->>Macro: struct_convert
    else Enum Variants
        FieldConverter->>Macro: enum_convert
    end
Loading

Poem

🐰 Attributes dance, a Rust ballet so fine,
Structs and enums now parse with design!
Conversion flows with elegance and grace,
From outer to inner, each attribute finds its place
A macro's magic, coded with rabbit's might! 🔧


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (2)
derive/src/from_pest/field.rs (1)

Line range hint 141-170: Reduce code duplication between enum_convert and struct_convert

Both enum_convert and struct_convert functions share similar logic when handling Fields::Named and Fields::Unnamed. Duplicated code can lead to maintenance issues.

Consider extracting the common logic into a helper function that can be utilized by both conversion functions. This will improve code reuse and maintainability.

derive/src/from_pest/mod.rs (1)

Line range hint 180-193: Ensure correct variant name usage in derive_for_enum

The variant_name variable is introduced to represent &variant.ident. However, in the quote! macro, stringify!(#variant_name) may not correctly interpolate the variant name as intended.

Adjust the usage to ensure that the variant name is correctly expanded:

 let variant_name = &variant.ident;
 let construct_variant = field::enum_convert(&parse_quote!(#name::#variant_name), &variant)?;
 let extraneous = crate::trace(quote! {
-    "when converting {}, found extraneous {:?}", stringify!(#name), stringify!(#variant_name)
+    concat!("when converting ", stringify!(#name), "::", stringify!(#variant_name), ", found extraneous")
 });
🧹 Nitpick comments (3)
derive/src/from_pest/field.rs (2)

Line range hint 35-49: Simplify the ConversionStrategy::from_attrs matching logic

The current implementation of ConversionStrategy::from_attrs uses a match statement that could be simplified for better readability and maintainability. Specifically, handling the case where multiple attributes are provided can be made clearer.

Apply this diff to refactor the matching logic:

 fn from_attrs(attrs: Vec<FieldAttribute>) -> Result<Self> {
     let mut attrs = attrs.into_iter();
-    Ok(match (attrs.next(), attrs.next()) {
-        (Some(_), Some(attr)) => Err(Error::new(
-            attr.span(),
-            "only a single field attribute allowed",
-        ))?,
-        (None, None) => ConversionStrategy::FromPest,
-        (Some(FieldAttribute::Outer(attr)), None) => ConversionStrategy::Outer(
-            attr.span(),
-            attr.with.into_iter().map(|attr| attr.path).collect(),
-        ),
-        (Some(FieldAttribute::Inner(attr)), None) => ConversionStrategy::Inner(
-            attr.span(),
-            attr.with.into_iter().map(|attr| attr.path).collect(),
-            attr.rule.map(|attr| {
-                let path = attr.path;
-                let variant = attr.variant;
-                parse_quote!(#path::#variant)
-            }),
-        ),
-        _ => unreachable!(),
-    })
+    match (attrs.next(), attrs.next()) {
+        (Some(attr), Some(_)) => Err(Error::new(
+            attr.span(),
+            "only a single field attribute allowed",
+        )),
+        (None, None) => Ok(ConversionStrategy::FromPest),
+        (Some(FieldAttribute::Outer(attr)), None) => Ok(ConversionStrategy::Outer(
+            attr.span(),
+            attr.with.into_iter().map(|attr| attr.path).collect(),
+        )),
+        (Some(FieldAttribute::Inner(attr)), None) => Ok(ConversionStrategy::Inner(
+            attr.span(),
+            attr.with.into_iter().map(|attr| attr.path).collect(),
+            attr.rule.map(|attr| {
+                let path = attr.path;
+                let variant = attr.variant;
+                parse_quote!(#path::#variant)
+            }),
+        )),
+        _ => unreachable!(),
+    }
 }

133-137: Handle unit variants without using a placeholder member

In the Fields::Unit case within enum_convert, the code applies the conversion strategy to a Member::Unnamed(Index::from(0)), which doesn't conceptually represent anything for unit variants. This could be misleading.

Consider adjusting the implementation to apply the conversion strategy without using a placeholder member:

 Fields::Unit => {
     let attrs = FieldAttribute::from_attributes(variant.attrs.clone())?;
-    let real_name =
-        ConversionStrategy::from_attrs(attrs)?.apply(Member::Unnamed(Index::from(0)));
-    quote!(#real_name)
+    let strategy = ConversionStrategy::from_attrs(attrs)?;
+    match strategy {
+        ConversionStrategy::FromPest => quote!(#name),
+        _ => strategy.apply(Member::Named(variant.ident.clone())),
+    }
 }
derive/src/attributes.rs (1)

Line range hint 35-49: Add documentation for the new FieldAttribute enum variants

The FieldAttribute enum has been introduced with Outer and Inner variants, but lacks comprehensive documentation explaining their usage and significance.

Consider adding Rust doc comments to describe the purpose and usage of FieldAttribute, OuterAttribute, and InnerAttribute.

 /// `#[pest_ast(..)]` for fields in `#[derive(FromPest)]`
 #[derive(Debug)]
+/// Represents field-level attributes for the `FromPest` derive macro.
+/// 
+/// Variants:
+/// - `Outer`: Denotes that the field should be parsed from an outer rule.
+/// - `Inner`: Indicates that the field should be parsed from an inner rule, potentially with a specific rule and additional attributes.
 pub(crate) enum FieldAttribute {
     /// `outer(with(path::to),*)`
     Outer(OuterAttribute),
     /// `inner(rule(path::to), with(path::to),*)`
     Inner(InnerAttribute),
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb04129 and 26ab519.

📒 Files selected for processing (3)
  • derive/src/attributes.rs (3 hunks)
  • derive/src/from_pest/field.rs (3 hunks)
  • derive/src/from_pest/mod.rs (2 hunks)
🔇 Additional comments (3)
derive/src/from_pest/mod.rs (1)

Line range hint 136-154: Verify the handling of generated lifetimes

In the derive function, when synthesizing a new lifetime 'unique_lifetime_name, it is essential to ensure that this does not conflict with existing lifetimes or cause unintended behavior.

Please confirm that introducing the 'unique_lifetime_name lifetime does not introduce any conflicts in the generated code, especially when dealing with complex generics or existing lifetimes.

derive/src/attributes.rs (2)

51-58: Ensure proper parsing of OuterAttribute and InnerAttribute

The parsing implementations for OuterAttribute and InnerAttribute should handle edge cases, such as empty lists or unexpected tokens.

Please review the parse implementations for these structs to ensure they correctly handle all possible inputs and provide meaningful error messages.


67-69: Implement Parse and ToTokens for WithAttribute

While WithAttribute is defined, ensure that its Parse and ToTokens traits are properly implemented to integrate seamlessly with the syn and quote crates.

The implementations for Parse and ToTokens for WithAttribute are correctly provided, enabling it to be used in attribute parsing.

Copy link
Contributor

@tomtau tomtau left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TonyWu20 thanks for your contribution. pest-ast is passively maintained and not that widely used (at least among OSS projects), so it's a bit hard to tell whether this change breaks any existing behaviour off the top of my head, but it looks it should hopefully be all right.
One way to improve it is perhaps to abstract the duplicate common code between convert_struct and convert_enum, but ok to merge it as it is

@tomtau tomtau merged commit 624e338 into pest-parser:master Jan 26, 2025
3 checks passed
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

Successfully merging this pull request may close these issues.

2 participants