|
| 1 | +- Feature Name: compile\_error\_macro |
| 2 | +- Start Date: 2016-08-01 |
| 3 | +- RFC PR: (leave this empty) |
| 4 | +- Rust Issue: (leave this empty) |
| 5 | + |
| 6 | +# Summary |
| 7 | +[summary]: #summary |
| 8 | + |
| 9 | +This RFC proposes adding a new macro to `libstd`, `compile_error!` which will |
| 10 | +unconditionally cause compilation to fail with the given error message when |
| 11 | +encountered. |
| 12 | + |
| 13 | +# Motivation |
| 14 | +[motivation]: #motivation |
| 15 | + |
| 16 | +Crates which work with macros or annotations such as `cfg` have no tools to |
| 17 | +communicate error cases in a meaningful way on stable. For example, given the |
| 18 | +following macro: |
| 19 | + |
| 20 | +```rust |
| 21 | +macro_rules! give_me_foo_or_bar { |
| 22 | + (foo) => {}; |
| 23 | + (bar) => {}; |
| 24 | +} |
| 25 | +``` |
| 26 | + |
| 27 | +when invoked with `baz`, the error message will be `error: no rules expected the |
| 28 | +token baz`. In a real world scenario, this error may actually occur deep in a |
| 29 | +stack of macro calls, with an even more confusing error message. With this RFC, |
| 30 | +the macro author could provide the following: |
| 31 | + |
| 32 | +```rust |
| 33 | +macro_rules! give_me_foo_or_bar { |
| 34 | + (foo) => {}; |
| 35 | + (bar) => {}; |
| 36 | + ($x:ident) => { |
| 37 | + compile_error!("This macro only accepts `foo` or `bar`"); |
| 38 | + } |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +When combined with attributes, this also provides a way for authors to validate |
| 43 | +combinations of features. |
| 44 | + |
| 45 | +```rust |
| 46 | +#[cfg(not(any(feature = "postgresql", feature = "sqlite")))] |
| 47 | +compile_error!("At least one backend must be used with this crate. \ |
| 48 | + Please specify `features = ["postgresql"]` or `features = ["sqlite"]`") |
| 49 | +``` |
| 50 | + |
| 51 | +# Detailed design |
| 52 | +[design]: #detailed-design |
| 53 | + |
| 54 | +The span given for the failure should be the invocation of the `compile_error!` |
| 55 | +macro. The macro must take exactly one argument, which is a string literal. The |
| 56 | +macro will then call `span_err` with the provided message on the expansion |
| 57 | +context, and will not expand to any further code. |
| 58 | + |
| 59 | +# Drawbacks |
| 60 | +[drawbacks]: #drawbacks |
| 61 | + |
| 62 | +None |
| 63 | + |
| 64 | +# Alternatives |
| 65 | +[alternatives]: #alternatives |
| 66 | + |
| 67 | +Wait for the stabilization of procedural macros, at which point a crate could |
| 68 | +provide this functionality. |
| 69 | + |
| 70 | +# Unresolved questions |
| 71 | +[unresolved]: #unresolved-questions |
| 72 | + |
| 73 | +None |
0 commit comments