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

Can ItemImpl::parse not consume attrs in syn::parse::ParseStream of a free-standing function? #1845

Open
CNCSMonster opened this issue Jan 21, 2025 · 0 comments

Comments

@CNCSMonster
Copy link

code example

write below to src/main.rs

use quote::quote;
use syn::{ItemFn, ItemImpl};

pub enum ItemImplOrFn {
    Fn(ItemFn),
    Impl(ItemImpl),
}

impl syn::parse::Parse for ItemImplOrFn {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        println!("parse {}", input);
        ItemImpl::parse(input).map(Self::Impl).or_else(|_| {
            println!("or parse {}", input);
            ItemFn::parse(input).map(Self::Fn)
        })
    }
}

fn main() {
    let code = quote! {
        /// Hello
        fn hello(){}
    };
    let func: ItemFn = syn::parse2(code.clone()).unwrap();
    assert!(!func.attrs.is_empty());

    let ItemImplOrFn::Fn(func) = syn::parse2(code).unwrap() else {
        unreachable!()
    };
    assert!(func.attrs.is_empty());
}

the Cargo.toml dependencies for this code:

[dependencies]
quote = "1.0.38"
syn = { version = "2.0.96", features = ["full"] }

cargo run , then you will see:

parse # [doc = r" Hello"] fn hello () { }
or parse fn hello () { }

which means the parse of the ItemImpl will consume the attrs in its input ParseStream.
which cause if i want to use parse_macro_input! to get my own ItemImplOrFn, i will loss func attrs.
which also not match below declaration in official docs:

Image

Expected: Stop Consuming attrsr

ItemImpl::parse not consume attrs ,then below can be pass

    let code = quote! {
        /// Hello
        fn hello(){}
    };
    let ItemImplOrFn::Fn(func) = syn::parse2(code).unwrap() else {
        unreachable!()
    };
    assert!(!func.attrs.is_empty());
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

1 participant