rust-lang / rust-analyzer

A Rust compiler front-end for IDEs
https://rust-analyzer.github.io/
Apache License 2.0
14.2k stars 1.6k forks source link

Support macro expansion inside attribute #8092

Open edwin0cheng opened 3 years ago

edwin0cheng commented 3 years ago

e.g :

#[doc = concat!("Hello", " world")]
struct Bar;

It is unstable feature and it is used in rustc master already.

jonas-schievink commented 3 years ago

cc https://github.com/rust-analyzer/rust-analyzer/issues/7779

jonas-schievink commented 3 years ago

I guess this is related to https://github.com/rust-analyzer/rust-analyzer/pull/7049

mvforell commented 2 years ago

This would be very useful for generating doc attributs in macros, e.g. like described at https://stackoverflow.com/a/43353854:

macro_rules! impl_foo {
    ($name:ident, $sname:expr) => {
        #[doc = "Returns a new `"]
        #[doc = $sname]
        #[doc = "`."]
        pub fn myfoo() -> $name {
            42
        }
    };

    ($name:tt) => {
        impl_foo!($name, stringify!($name));
    };
}

impl_foo!(u32);

Currently, the above doc gets rendered as

Returns a new ``.

instead of

Returns a new u32.

sanbox-irl commented 1 year ago

To add to this discussion -- since the std uses this macro, many examples in the std do not read correctly right now:

peter-lyons-kehl commented 1 year ago

A workaround: Have a proc_macro that generates the string, injects it in #[doc = "..." ] (escaping any backslashes \ into \\ and any quotes " into \\\") and generates your desired item (along with that #[doc = "..." ]).

Tedious, and it requires an extra proc_macro crate (unless you're generating proc macros already). But, chances are that you're already generating your desired code either with macro_rules! or proc macros, so it's not much more science. (The proc macro itself would be simple and is feasible without syn and quote, potentially generating proc_macro::TokenStream with my_generated_code_string.parse().unwrap(), or with proc_macro API, hence lightweight.)

DianaNites commented 3 months ago

Since this is still an issue and I havent seen it mentioned anywhere, this depended on the now stable extended_key_value_attributes, which had a tracking issue on this side which was closed in favor of this issue.

extended_key_value_attributes was stabilized a few months after these issues were opened back in 2021, but when it got stabilized little further seems to have been done beyond newer issues being closed as duplicates of this.

This has been a stable feature for years, std and many other crates rely on it for their documentation, and more continue to as time goes on, and rust-analyzer doesn't render docs using it correctly