Cargo rustc -- -Zunpretty=expanded

#![allow(clippy::unwrap_used)]

fn f() {}

When I use cargo rustc -- -Zunpretty=expanded to expand the code above. Output is

#![feature(prelude_import)]
#![allow(clippy :: unwrap_used)]
#[prelude_import]
use std::prelude::rust_2021::*;
#[macro_use]
extern crate std;

fn f() {}

Why #![allow(clippy::unwrap_used)] became to #![allow(clippy :: unwrap_used)]. There are some blanks around ::.

TLDR: Because the compiler doesn't care, and it doesn't change the meaning.

I don't know the exact path this is taking through the compiler, but I suspect this is because values in attributes (like the clippy::unwrap_used part of #![allow(clippy::unwrap_used)]) don't really have any syntax. From the compiler's perspective, they're just an undifferentiated lump of tokens.

When the compiler prints out the result of macro expansion (which is what I think this is), it's actually just mostly imposing it's own formatting on the code. It's not exactly replicating what you gave it.

My guess is that values in meta items just put spaces around everything to avoid a situation where, for example, allow(a b c) accidentally becomes allow(abc), thus changing the code's meaning. Adding spaces around tokens (to my knowledge) doesn't ever change the code's meaning, so easy and safe to avoid any potential problems.

Here's a more extreme example:

  fn        f (

)  {

        }

This, when run through the compiler the same way (via godbolt) produces the following output:

use std::prelude::rust_2021::*;
extern crate std;
fn f() 
    {
}

It's not entirely insensitive to the original formatting, but it also doesn't really care about trying to match it.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.