How can I suppress a Clippy warning originating from a macro?

4.1k views Asked by At

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.

1

There are 1 answers

0
Shiqi Cao On

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