Skip to content
This repository has been archived by the owner on Aug 16, 2021. It is now read-only.

Commit

Permalink
support trailing commas in macros (#273)
Browse files Browse the repository at this point in the history
  • Loading branch information
ExpHP authored and mitsuhiko committed Dec 28, 2018
1 parent 26fc6eb commit 22bfd31
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/macros.rs
Expand Up @@ -11,8 +11,8 @@ macro_rules! bail {
($e:expr) => {
return Err($crate::err_msg($e));
};
($fmt:expr, $($arg:tt)+) => {
return Err($crate::err_msg(format!($fmt, $($arg)+)));
($fmt:expr, $($arg:tt)*) => {
return Err($crate::err_msg(format!($fmt, $($arg)*)));
};
}

Expand All @@ -28,9 +28,9 @@ macro_rules! ensure {
bail!($e);
}
};
($cond:expr, $fmt:expr, $($arg:tt)+) => {
($cond:expr, $fmt:expr, $($arg:tt)*) => {
if !($cond) {
bail!($fmt, $($arg)+);
bail!($fmt, $($arg)*);
}
};
}
Expand Down
54 changes: 54 additions & 0 deletions tests/macro_trailing_comma.rs
@@ -0,0 +1,54 @@
#[macro_use]
extern crate failure;

// NOTE:
//
// This test is in a separate file due to the fact that ensure! cannot be used
// from within failure.
//
// (you get: 'macro-expanded `macro_export` macros from the current crate cannot
// be referred to by absolute paths')

// Encloses an early-returning macro in an IIFE so that we
// can treat it as a Result-returning function.
macro_rules! wrap_early_return {
($expr:expr) => {{
fn func() -> Result<(), failure::Error> {
let _ = $expr;

#[allow(unreachable_code)]
Ok(())
}
func().map_err(|e| e.to_string())
}};
}

#[test]
fn bail() {
assert_eq!(
wrap_early_return!(bail!("test")),
wrap_early_return!(bail!("test",)));
assert_eq!(
wrap_early_return!(bail!("test {}", 4)),
wrap_early_return!(bail!("test {}", 4,)));
}

#[test]
fn ensure() {
assert_eq!(
wrap_early_return!(ensure!(false, "test")),
wrap_early_return!(ensure!(false, "test",)));
assert_eq!(
wrap_early_return!(ensure!(false, "test {}", 4)),
wrap_early_return!(ensure!(false, "test {}", 4,)));
}

#[test]
fn format_err() {
assert_eq!(
format_err!("test").to_string(),
format_err!("test",).to_string());
assert_eq!(
format_err!("test {}", 4).to_string(),
format_err!("test {}", 4,).to_string());
}

0 comments on commit 22bfd31

Please sign in to comment.