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

support trailing commas in macros #273

Merged
merged 2 commits into from Dec 28, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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());
}