rfcs/text/1695-add-error-macro.md

2.1 KiB

Summary

This RFC proposes adding a new macro to libcore, compile_error! which will unconditionally cause compilation to fail with the given error message when encountered.

Motivation

Crates which work with macros or annotations such as cfg have no tools to communicate error cases in a meaningful way on stable. For example, given the following macro:

macro_rules! give_me_foo_or_bar {
    (foo) => {};
    (bar) => {};
}

when invoked with baz, the error message will be error: no rules expected the token baz. In a real world scenario, this error may actually occur deep in a stack of macro calls, with an even more confusing error message. With this RFC, the macro author could provide the following:

macro_rules! give_me_foo_or_bar {
    (foo) => {};
    (bar) => {};
    ($x:ident) => {
        compile_error!("This macro only accepts `foo` or `bar`");
    }
}

When combined with attributes, this also provides a way for authors to validate combinations of features.

#[cfg(not(any(feature = "postgresql", feature = "sqlite")))]
compile_error!("At least one backend must be used with this crate. \
    Please specify `features = ["postgresql"]` or `features = ["sqlite"]`")

Detailed design

The span given for the failure should be the invocation of the compile_error! macro. The macro must take exactly one argument, which is a string literal. The macro will then call span_err with the provided message on the expansion context, and will not expand to any further code.

Drawbacks

None

Alternatives

Wait for the stabilization of procedural macros, at which point a crate could provide this functionality.

Unresolved questions

None