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

Custom error messages for trait-related assertions #24

Open
nvzqz opened this issue Oct 18, 2019 · 0 comments
Open

Custom error messages for trait-related assertions #24

nvzqz opened this issue Oct 18, 2019 · 0 comments

Comments

@nvzqz
Copy link
Owner

nvzqz commented Oct 18, 2019

By using on_unimplemented (tracking issue: rust-lang/rust#29628), custom error messages like the following can be emitted on assertion failure:

error[E0277]: static assertion failed
  --> tests/messages.rs:14:1
   |
14 | assert_impl_one!(Foo: A, B, C);
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   | |
   | `Foo` must implement exactly one of the given traits
   | required by `_::{{closure}}#0::AmbiguousIfMoreThanOne::some_item`
   |
   = help: the trait `_::{{closure}}#0::AmbiguousIfMoreThanOne<_>` is not implemented for `Foo`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

This can be done like so (behind a nightly feature flag):

macro_rules! assert_impl_one {
    ($x:ty: $($t:path),+ $(,)?) => {
        const _: fn() = || {
            #[cfg_attr(
                feature = "nightly",
                rustc_on_unimplemented(
                    message = "static assertion failed",
                    label = "`{Self}` must implement exactly one of the given traits",
                )
            )]
            trait AmbiguousIfMoreThanOne<A> {
                // ...
            }
            // ...
        }
    };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant