Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set a custom message for failing assertions #49

Open
NoraCodes opened this issue Apr 26, 2022 · 0 comments
Open

Set a custom message for failing assertions #49

NoraCodes opened this issue Apr 26, 2022 · 0 comments

Comments

@NoraCodes
Copy link

I'm not sure if this is possible on the MSRV of 1.37, but on 1.57 we can do something like this:

macro_rules! const_assert {
    ($x:expr $(,)?) => {
        const_assert!($x, "const assertion failed",);
    };
    ($x:expr, $es:expr $(,)?) => {
        const _: () = {
            const fn assert_internal () {
                if !$x {
                    core::panic!($es);
                }
            }
            const _: () = assert_internal();
        };
    };
}

And you can call that like so:

const_assert!(BUFFER_LEN < 1024, "BUFFER_LEN > 1024 will overrun PROGMEM");

And get a message like this:

error[E0080]: evaluation of constant value failed
 --> src/const_assert.rs:55:1
  |
5 | const_assert!(BUFFER_LEN < 1024, "BUFFER_LEN > 1024 will overrun PROGMEM");
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  | |
  | the evaluated program panicked at 'BUFFER_LEN > 1024 will overrun PROGMEM', src/const_assert.rs:5:1
  | inside `assert_internal` at /rustc/8f36334ca939a67cce3f37f24953ff6f2d3f3d33/library/core/src/panic.rs:28:9
  | inside `_::_` at /home/nora/src/noracodes/static-assertions-rs/src/const_assert.rs:71:27
  |
  = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info)

Obviously this won't work for any other macros here, because of their variadics, but it would be lovely if we could get custom messages at least for const_assert. Perhaps it could be opt-in through a Cargo feature?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant