Skip to content
Myr

Move macros to their own module

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Now that lib.rs needs to have other things in it.

authored by David Tolnay · committed by David Tolnay · parent 27fcdd4 · Browse files · 2 files+190 added−190 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+190 added−190 removed

  • other:+190 added−190 removed

2 files+190 added−190 removed

modified:src/lib.rs+2 added-190 removed
177 unmodified lines
178mod backtrace;179mod context;180mod error;181mod kind;182mod macros;183184#[cfg(not(feature = "std"))]185compile_error!("no_std support is not implemented yet");186
89 unmodified lines
276/// }277/// ```278pub type Result<T, E = Error> = std::result::Result<T, E>;279279/// Return early with an error.280///281/// This macro is equivalent to `return Err(From::from($err))`.282///283/// # Example284///285/// ```286/// # use anyhow::{bail, Result};287/// #288/// # fn has_permission(user: usize, resource: usize) -> bool {289/// # true290/// # }291/// #292/// # fn main() -> Result<()> {293/// # let user = 0;294/// # let resource = 0;295/// #296/// if !has_permission(user, resource) {297/// bail!("permission denied for accessing {}", resource);298/// }299/// # Ok(())300/// # }301/// ```302///303/// ```304/// # use anyhow::{bail, Result};305/// # use std::fmt::{self, Display};306/// #307/// # #[derive(Debug)]308/// # enum ScienceError {309/// # RecursionLimitExceeded,310/// # }311/// #312/// # impl std::error::Error for ScienceError {}313/// #314/// # impl Display for ScienceError {315/// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {316/// # unimplemented!()317/// # }318/// # }319/// #320/// # const MAX_DEPTH: usize = 1;321/// #322/// # const IGNORE: &str = stringify! {323/// #[derive(Error, Debug)]324/// enum ScienceError {325/// #[error(display = "recursion limit exceeded")]326/// RecursionLimitExceeded,327/// ...328/// }329/// # };330///331/// # fn main() -> Result<()> {332/// # let depth = 0;333/// #334/// if depth > MAX_DEPTH {335/// bail!(ScienceError::RecursionLimitExceeded);336/// }337/// # Ok(())338/// # }339/// ```340#[macro_export]341macro_rules! bail {342 ($msg:literal $(,)?) => {343 return std::result::Result::Err($crate::anyhow!($msg));344 };345 ($err:expr $(,)?) => {346 return std::result::Result::Err($crate::anyhow!($err));347 };348 ($fmt:expr, $($arg:tt)*) => {349 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));350 };351}352353/// Return early with an error if a condition is not satisfied.354///355/// This macro is equivalent to `if !$cond { return Err(From::from($err)); }`.356///357/// Analogously to `assert!`, `ensure!` takes a condition and exits the function358/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`359/// rather than panicking.360///361/// # Example362///363/// ```364/// # use anyhow::{ensure, Result};365/// #366/// # fn main() -> Result<()> {367/// # let user = 0;368/// #369/// ensure!(user == 0, "only user 0 is allowed");370/// # Ok(())371/// # }372/// ```373///374/// ```375/// # use anyhow::{ensure, Result};376/// # use std::fmt::{self, Display};377/// #378/// # #[derive(Debug)]379/// # enum ScienceError {380/// # RecursionLimitExceeded,381/// # }382/// #383/// # impl std::error::Error for ScienceError {}384/// #385/// # impl Display for ScienceError {386/// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {387/// # unimplemented!()388/// # }389/// # }390/// #391/// # const MAX_DEPTH: usize = 1;392/// #393/// # const IGNORE: &str = stringify! {394/// #[derive(Error, Debug)]395/// enum ScienceError {396/// #[error(display = "recursion limit exceeded")]397/// RecursionLimitExceeded,398/// ...399/// }400/// # };401///402/// # fn main() -> Result<()> {403/// # let depth = 0;404/// #405/// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);406/// # Ok(())407/// # }408/// ```409#[macro_export]410macro_rules! ensure {411 ($cond:expr, $msg:literal $(,)?) => {412 if !$cond {413 return std::result::Result::Err($crate::anyhow!($msg));414 }415 };416 ($cond:expr, $err:expr $(,)?) => {417 if !$cond {418 return std::result::Result::Err($crate::anyhow!($err));419 }420 };421 ($cond:expr, $fmt:expr, $($arg:tt)*) => {422 if !$cond {423 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));424 }425 };426}427428/// Construct an ad-hoc error from a string.429///430/// This evaluates to an `Error`. It can take either just a string, or a format431/// string with arguments. It also can take any custom type which implements432/// `Debug` and `Display`.433///434/// # Example435///436/// ```437/// # type V = ();438/// #439/// use anyhow::{anyhow, Result};440///441/// fn lookup(key: &str) -> Result<V> {442/// if key.len() != 16 {443/// return Err(anyhow!("key length must be 16 characters, got {:?}", key));444/// }445/// 446/// // ...447/// # Ok(())448/// }449/// ```450#[macro_export]451macro_rules! anyhow {452 ($msg:literal $(,)?) => {453 // Handle $:literal as a special case to make cargo-expanded code more454 // concise in the common case.455 $crate::private::new_adhoc($msg)456 };457 ($err:expr $(,)?) => ({458 #[allow(unused_imports)]459 use $crate::private::{AdhocKind, TraitKind};460 let error = $err;461 (&error).anyhow_kind().new(error)462 });463 ($fmt:expr, $($arg:tt)*) => {464 $crate::private::new_adhoc(format!($fmt, $($arg)*))465 };466}467280/// Provides the `context` method for `Result`.281///282/// This trait is sealed and cannot be implemented for types outside of283/// `anyhow`.
51 unmodified lines
335 C: Display + Send + Sync + 'static,336 F: FnOnce() -> C;337}338527// Not public API.339// Not public API. Referenced by macro-generated code.340#[doc(hidden)]341pub mod private {342 use crate::Error;343 use std::fmt::{Debug, Display};
13 unmodified lines
added:src/macros.rs+188 added
1/// Return early with an error.2///3/// This macro is equivalent to `return Err(From::from($err))`.4///5/// # Example6///7/// ```8/// # use anyhow::{bail, Result};9/// #10/// # fn has_permission(user: usize, resource: usize) -> bool {11/// # true12/// # }13/// #14/// # fn main() -> Result<()> {15/// # let user = 0;16/// # let resource = 0;17/// #18/// if !has_permission(user, resource) {19/// bail!("permission denied for accessing {}", resource);20/// }21/// # Ok(())22/// # }23/// ```24///25/// ```26/// # use anyhow::{bail, Result};27/// # use std::fmt::{self, Display};28/// #29/// # #[derive(Debug)]30/// # enum ScienceError {31/// # RecursionLimitExceeded,32/// # }33/// #34/// # impl std::error::Error for ScienceError {}35/// #36/// # impl Display for ScienceError {37/// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {38/// # unimplemented!()39/// # }40/// # }41/// #42/// # const MAX_DEPTH: usize = 1;43/// #44/// # const IGNORE: &str = stringify! {45/// #[derive(Error, Debug)]46/// enum ScienceError {47/// #[error(display = "recursion limit exceeded")]48/// RecursionLimitExceeded,49/// ...50/// }51/// # };52///53/// # fn main() -> Result<()> {54/// # let depth = 0;55/// #56/// if depth > MAX_DEPTH {57/// bail!(ScienceError::RecursionLimitExceeded);58/// }59/// # Ok(())60/// # }61/// ```62#[macro_export]63macro_rules! bail {64 ($msg:literal $(,)?) => {65 return std::result::Result::Err($crate::anyhow!($msg));66 };67 ($err:expr $(,)?) => {68 return std::result::Result::Err($crate::anyhow!($err));69 };70 ($fmt:expr, $($arg:tt)*) => {71 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));72 };73}7475/// Return early with an error if a condition is not satisfied.76///77/// This macro is equivalent to `if !$cond { return Err(From::from($err)); }`.78///79/// Analogously to `assert!`, `ensure!` takes a condition and exits the function80/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`81/// rather than panicking.82///83/// # Example84///85/// ```86/// # use anyhow::{ensure, Result};87/// #88/// # fn main() -> Result<()> {89/// # let user = 0;90/// #91/// ensure!(user == 0, "only user 0 is allowed");92/// # Ok(())93/// # }94/// ```95///96/// ```97/// # use anyhow::{ensure, Result};98/// # use std::fmt::{self, Display};99/// #100/// # #[derive(Debug)]101/// # enum ScienceError {102/// # RecursionLimitExceeded,103/// # }104/// #105/// # impl std::error::Error for ScienceError {}106/// #107/// # impl Display for ScienceError {108/// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {109/// # unimplemented!()110/// # }111/// # }112/// #113/// # const MAX_DEPTH: usize = 1;114/// #115/// # const IGNORE: &str = stringify! {116/// #[derive(Error, Debug)]117/// enum ScienceError {118/// #[error(display = "recursion limit exceeded")]119/// RecursionLimitExceeded,120/// ...121/// }122/// # };123///124/// # fn main() -> Result<()> {125/// # let depth = 0;126/// #127/// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);128/// # Ok(())129/// # }130/// ```131#[macro_export]132macro_rules! ensure {133 ($cond:expr, $msg:literal $(,)?) => {134 if !$cond {135 return std::result::Result::Err($crate::anyhow!($msg));136 }137 };138 ($cond:expr, $err:expr $(,)?) => {139 if !$cond {140 return std::result::Result::Err($crate::anyhow!($err));141 }142 };143 ($cond:expr, $fmt:expr, $($arg:tt)*) => {144 if !$cond {145 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));146 }147 };148}149150/// Construct an ad-hoc error from a string.151///152/// This evaluates to an `Error`. It can take either just a string, or a format153/// string with arguments. It also can take any custom type which implements154/// `Debug` and `Display`.155///156/// # Example157///158/// ```159/// # type V = ();160/// #161/// use anyhow::{anyhow, Result};162///163/// fn lookup(key: &str) -> Result<V> {164/// if key.len() != 16 {165/// return Err(anyhow!("key length must be 16 characters, got {:?}", key));166/// }167///168/// // ...169/// # Ok(())170/// }171/// ```172#[macro_export]173macro_rules! anyhow {174 ($msg:literal $(,)?) => {175 // Handle $:literal as a special case to make cargo-expanded code more176 // concise in the common case.177 $crate::private::new_adhoc($msg)178 };179 ($err:expr $(,)?) => ({180 #[allow(unused_imports)]181 use $crate::private::{AdhocKind, TraitKind};182 let error = $err;183 (&error).anyhow_kind().new(error)184 });185 ($fmt:expr, $($arg:tt)*) => {186 $crate::private::new_adhoc(format!($fmt, $($arg)*))187 };188}