rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

rustfmt removes inner attributes from inline const blocks

Open matthieu-m opened this issue 1 year ago • 2 comments

Clippy unfortunately warns about asserts whose conditions can be evaluated at compile-time even in inline const blocks. It's a known issue, it'll hopefully be solved at some point.

In the meantime, if one wishes to perform such compile-time asserts without disabling the lint globally, one can simply allow the offending lint:

fn main() {
    const {
        #![allow(clippy::assertions_on_constants)]

        assert!(1 < 2);
    }
}

Unfortunately, running rustfmt on the above will simply remove the attribute (try it on the playground), resulting in:

fn main() {
    const {
        assert!(1 < 2);
    }
}

And then Clippy nags at us again :'(

With inline const blocks due to being stabilized for 1.79 (in 6 weeks), it would be nice to fix rustfmt to not eat their code away.

Meta

rustfmt version:

1.7.0-nightly (2024-05-03 d2d24e3)

matthieu-m avatar May 04 '24 12:05 matthieu-m

I think the issue here is that the inner attributes are stored on the outer ast::Expr node with the kind of ast::ExprKind::ConstBlock(AnonConst). Internally the ast::AnonConst holds a reference to an ast::ExprKind::Block expression that we want to rewrite, but it doesn't hold a reference to the attributes.

We can probably solve this by matching on the AnonConst's inner expression kind and calling rewrite_block if it's an ast::ExprKind::Block:

https://github.com/rust-lang/rustfmt/blob/d5f1200ed6a8e375f963e0c59a8bee45c0018c55/src/expr.rs#L141-L143

ytmimi avatar May 06 '24 16:05 ytmimi

@rustbot claim

WeiTheShinobi avatar May 21 '24 15:05 WeiTheShinobi