How can I suppress a Clippy warning originating from a macro?
Asked Answered
H

2

15

I have macro with return statement like this:

macro_rules! return_fail {
    ( $res:expr ) => {
        match $res {
            Ok(val) => val,
            Err(e) => {
                eprintln!(
                    "An error: on {}:{} {}; aborting current function.",
                    file!(),
                    line!(),
                    e
                );
                return;
            }
        }
    };
}

fn bad(flag: bool) -> Result<(), String> {
    if flag {
        Ok(())
    } else {
        Err("u r idiot".to_string())
    }
}

fn main() {
    return_fail!(bad(true));
    return_fail!(bad(false));
}

Rust playground

This macro works fine when I use it in the middle of a function, but when I use it at the end of the function I get a warning from Clippy:

warning: unneeded `return` statement
  --> src/main.rs:12:17
   |
12 |                 return;
   |                 ^^^^^^^ help: remove `return`
...
28 |     return_fail!(bad(false));
   |     ------------------------- in this macro invocation
   |
   = note: `#[warn(clippy::needless_return)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_return
   = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

How I can suppress this warning? I tried adding #[allow(clippy::needless_return)] to the upper line of macro definition but it did not work.

Hypha answered 8/9, 2020 at 17:34 Comment(6)
This is most likely a bug in clippy, as it's supposed to know that the code comes from a macro and disable certain lints.Ilana
did you try #![allow(clippy::needless_return)]Alaska
@Alaska that would disable it everywhere, not just one location. Seems excessive.Ilana
This no longer happens with that playground example. It seems that the version of clippy running there now doesn't mind the return from the macro.Jargonize
Have you find a solution? thanksMcginnis
@Mcginnis the solution here is to upgrade the toolchain; the bug in Clippy has been fixed.Malinda
W
1

This questions has already been answered in the comments:

the solution here is to upgrade the toolchain; the bug in Clippy has been fixed.

Whitebook answered 12/6 at 8:58 Comment(0)
S
-10

If you expand the macro the last return statement isn't necessary.

Springclean answered 24/10, 2020 at 7:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.