rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
93.93k stars 12.09k forks source link

Unexpected comment position after macro expansion #125239

Closed thomasyonug closed 2 weeks ago

thomasyonug commented 2 weeks ago

I tried this code:

// macro by example
#[macro_export]
macro_rules! mdriver {
    ($f:ident) => {
        #[no_mangle]
        pub fn lookup_inc(buf: &[u8; 5], $f: Bar) -> u8 {
            buf[$f as usize + 1]
        }
    };
}

// macro call 
#[derive(Clone, Copy)]
enum Bar { A, B, C, D, E }

mdriver!(A);

mod test_module {
    use super::*;
    mdriver!(B); // Reusing in a module for diversity
}

I expected to see this happen:

#[prelude_import]
use ::std::prelude::rust_2015::*;
#[macro_use]
extern crate std;
extern crate mbe_1080819556052783730;
use mbe_1080819556052783730::mdriver;

enum Bar { A, B, C, D, E, }
#[automatically_derived]
impl ::core::clone::Clone for Bar {
    #[inline]
    fn clone<'_>(self: &'_ Self) -> Bar { *self }
}
#[automatically_derived]
impl ::core::marker::Copy for Bar { }

#[no_mangle]
fn lookup_inc<'_>(buf: &'_ [u8; 5], A: Bar) -> u8 { buf[A as usize + 1] }
mod test_module {
    use super::*;
    // Reusing in a module for diversity
    #[no_mangle]
    fn lookup_inc<'_>(buf: &'_ [u8; 5], B: Bar) -> u8 { buf[B as usize + 1] }
}

Instead, this happened:

#[prelude_import]
use ::std::prelude::rust_2015::*;
#[macro_use]
extern crate std;
extern crate mbe_1080819556052783730;
use mbe_1080819556052783730::mdriver;

enum Bar { A, B, C, D, E, }
#[automatically_derived]
impl ::core::clone::Clone for Bar {
    #[inline]
    fn clone<'_>(self: &'_ Self) -> Bar { *self }
}
#[automatically_derived]
impl ::core::marker::Copy for Bar { }

// Reusing in a module for diversity
#[no_mangle]
fn lookup_inc<'_>(buf: &'_ [u8; 5], A: Bar) -> u8 { buf[A as usize + 1] }
mod test_module {
    use super::*;
    #[no_mangle]
    fn lookup_inc<'_>(buf: &'_ [u8; 5], B: Bar) -> u8 { buf[B as usize + 1] }
}

Meta

rustc --version --verbose:

rustc 1.80.0-nightly (ef0027897 2024-05-12)
binary: rustc
commit-hash: ef0027897d2e9014766fb47dce9ddbb925d2f540
commit-date: 2024-05-12
host: x86_64-unknown-linux-gnu
release: 1.80.0-nightly
LLVM version: 18.1.4
Backtrace

``` ```

bjorn3 commented 2 weeks ago

Comments are not preserved in the AST. -Zunpretty=expanded and similar try to preserve comments by guessing where they should be placed. As you noticed this is always accurate. This is not a bug as comment preservation is best effort.