Macro changes

Minimum Rust version: 1.31

macro_rules! style macros

In Rust 2018, you can import specific macros from external crates via usestatements, rather than the old #[macro_use] attribute.

For example, consider a bar crate that implements a baz! macro. Insrc/lib.rs:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. #[macro_export]
  4. macro_rules! baz {
  5. () => ()
  6. }
  7. }

In your crate, you would have written

  1. // Rust 2015
  2. #[macro_use]
  3. extern crate bar;
  4. fn main() {
  5. baz!();
  6. }

Now, you write:

  1. // Rust 2018
  2. use bar::baz;
  3. fn main() {
  4. baz!();
  5. }

This moves macro_rules macros to be a bit closer to other kinds of items.

Note that you'll still need #[macro_use] to use macros you've definedin your own crate; this feature only works for importing macros fromexternal crates.

Procedural macros

When using procedural macros to derive traits, you will have to name the macrothat provides the custom derive. This generally matches the name of the trait,but check with the documentation of the crate providing the derives to be sure.

For example, with Serde you would have written

  1. // Rust 2015
  2. extern crate serde;
  3. #[macro_use] extern crate serde_derive;
  4. #[derive(Serialize, Deserialize)]
  5. struct Bar;

Now, you write instead:

  1. // Rust 2018
  2. use serde_derive::{Serialize, Deserialize};
  3. #[derive(Serialize, Deserialize)]
  4. struct Bar;

More details

This only works for macros defined in external crates.For macros defined locally, #[macro_use] mod foo; is still required, as it was in Rust 2015.

Local helper macros

Sometimes it is helpful or necessary to have helper macros inside your module. This can makesupporting both versions of rust more complicated.

For example, let's make a simplified (and slightly contrived) version of the log crate in 2015edition style:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. use std::fmt;
  4. /// How important/severe the log message is.
  5. #[derive(Copy, Clone)]
  6. pub enum LogLevel {
  7. Warn,
  8. Error
  9. }
  10. impl fmt::Display for LogLevel {
  11. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  12. match self {
  13. LogLevel::Warn => write!(f, "warning"),
  14. LogLevel::Error => write!(f, "error"),
  15. }
  16. }
  17. }
  18. // A helper macro to log the message.
  19. #[doc(hidden)]
  20. #[macro_export]
  21. macro_rules! __impl_log {
  22. ($level:expr, $msg:expr) => {{
  23. println!("{}: {}", $level, $msg)
  24. }}
  25. }
  26. /// Warn level log message
  27. #[macro_export]
  28. macro_rules! warn {
  29. ($($args:tt)*) => {
  30. __impl_log!($crate::LogLevel::Warn, format_args!($($args)*))
  31. }
  32. }
  33. /// Error level log message
  34. #[macro_export]
  35. macro_rules! error {
  36. ($($args:tt)*) => {
  37. __impl_log!($crate::LogLevel::Error, format_args!($($args)*))
  38. }
  39. }
  40. }

Our __impl_log! macro is private to our module, but needs to be exported as it is called by othermacros, and in 2015 edition all used macros must be exported.

Now, in 2018 this example will not compile:

  1. use log::error;
  2. fn main() {
  3. error!("error message");
  4. }

will give an error message about not finding the __impl_log! macro. This is because unlike in the 2015 edition, macros are namespaced and we must import them. We could do

  1. use log::{__impl_log, error};

which would make our code compile, but __impl_log is meant to be an implementation detail!

Macros with $crate:: prefix.

The cleanest way to handle this situation is to use the $crate:: prefix for macros, the same asyou would for any other path. Versions of the compiler >= 1.30 will handle this in both editions:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. macro_rules! warn {
  4. ($($args:tt)*) => {
  5. $crate::__impl_log!($crate::LogLevel::Warn, format_args!($($args)*))
  6. }
  7. }
  8. // ...
  9. }

However, this will not work for older versions of the compiler that don't understand the$crate:: prefix for macros.

Macros using local_inner_macros

We also have the local_inner_macros modifier that we can add to our #[macro_export] attribute.This has the advantage of working with older rustc versions (older versions just ignore the extramodifier). The downside is that it's a bit messier:

  1. #[macro_export(local_inner_macros)]
  2. macro_rules! warn {
  3. ($($args:tt)*) => {
  4. __impl_log!($crate::LogLevel::Warn, format_args!($($args)*))
  5. }
  6. }

So the code knows to look for any macros used locally. But wait - this won't compile, because weuse the format_args! macro that isn't in our local crate (hence the convoluted example). Thesolution is to add a level of indirection: we create a macro that wraps format_args, but is local to our crate. That way everything works in both editions (sadly we have to pollute the globalnamespace a bit, but that's ok).

  1. #![allow(unused_variables)]
  2. fn main() {
  3. // I've used the pattern `_<my crate name>__<macro name>` to name this macro, hopefully avoiding
  4. // name clashes.
  5. #[doc(hidden)]
  6. #[macro_export]
  7. macro_rules! _log__format_args {
  8. ($($inner:tt)*) => {
  9. format_args! { $($inner)* }
  10. }
  11. }
  12. }

Here we're using the most general macro pattern possible, a list of token trees. We just passwhatever tokens we get to the inner macro, and rely on it to report errors.

So the full 2015/2018 working example would be:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. use std::fmt;
  4. /// How important/severe the log message is.
  5. #[derive(Debug, Copy, Clone)]
  6. pub enum LogLevel {
  7. Warn,
  8. Error
  9. }
  10. impl fmt::Display for LogLevel {
  11. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  12. match self {
  13. LogLevel::Warn => write!(f, "warning"),
  14. LogLevel::Error => write!(f, "error"),
  15. }
  16. }
  17. }
  18. // A helper macro to log the message.
  19. #[doc(hidden)]
  20. #[macro_export]
  21. macro_rules! __impl_log {
  22. ($level:expr, $msg:expr) => {{
  23. println!("{}: {}", $level, $msg)
  24. }}
  25. }
  26. /// Warn level log message
  27. #[macro_export(local_inner_macros)]
  28. macro_rules! warn {
  29. ($($args:tt)*) => {
  30. __impl_log!($crate::LogLevel::Warn, _log__format_args!($($args)*))
  31. }
  32. }
  33. /// Error level log message
  34. #[macro_export(local_inner_macros)]
  35. macro_rules! error {
  36. ($($args:tt)*) => {
  37. __impl_log!($crate::LogLevel::Error, _log__format_args!($($args)*))
  38. }
  39. }
  40. #[doc(hidden)]
  41. #[macro_export]
  42. macro_rules! _log__format_args {
  43. ($($inner:tt)*) => {
  44. format_args! { $($inner)* }
  45. }
  46. }
  47. }

Once everyone is using a rustc version >= 1.30, we can all just use the $crate:: method (2015crates are guaranteed to carry on compiling fine with later versions of the compiler). We need towait for package managers and larger organisations to update their compilers before this happens,so in the mean time we can use the local_inner_macros method to support everybody. :)