Enable backtrace support for >= 1.65 stable compilers
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The `std::backtrace` APIs relevant for this crate were stabilized in 1.65. This commit makes anyhow use those API if possible. `std::backtrace` is preferred over the `backtrace` crate, so for 1.65+ compilers, enabling the `backtrace` crate feature does nothing essentially. Previously, when a nightly compiler was used, use of `std::backtrace` as well as the Provider API was enabled. This commit separates those two APIs such that `std::backtrace` is used for nightly OR 1.65+ stable compilers; and the Provider API is used for nightly compilers only.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+47 added−43 removed
- other:+47 added−43 removed
Provenance
- Commit
49eeec1- Tree
02bab16- Author
Lukas Kalbertodt <lukas.kalbertodt@gmail.com>- Committer
Lukas Kalbertodt <lukas.kalbertodt@gmail.com>- Parent
0a45d76
7 files changed+47 added−43 removed
modified:src/backtrace.rs+2 added-2 removed
33 unmodified lines34 None35 };36 }37 38-#[cfg(backtrace)]38+#[cfg(provide_api)]39 macro_rules! backtrace_if_absent {40 ($err:expr) => {41 match ($err as &dyn std::error::Error).request_ref::<std::backtrace::Backtrace>() {42 Some(_) => None,1 unmodified line44 }45 };46 }47 48-#[cfg(all(feature = "std", not(backtrace), feature = "backtrace"))]48+#[cfg(all(feature = "std", not(provide_api), any(backtrace, feature = "backtrace")))]49 macro_rules! backtrace_if_absent {50 ($err:expr) => {51 backtrace!()52 };349 unmodified linesmodified:src/context.rs+3 added-3 removed
1 unmodified line2 use crate::{Context, Error, StdError};3 use core::convert::Infallible;4 use core::fmt::{self, Debug, Display, Write};5 6-#[cfg(backtrace)]6+#[cfg(provide_api)]7 use std::any::{Demand, Provider};8 9 mod ext {10 use super::*;131 unmodified lines142 fn source(&self) -> Option<&(dyn StdError + 'static)> {143 Some(&self.error)144 }145 146- #[cfg(backtrace)]146+ #[cfg(provide_api)]147 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {148 StdError::provide(&self.error, demand);149 }150 }5 unmodified lines156 fn source(&self) -> Option<&(dyn StdError + 'static)> {157 Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) })158 }159 160- #[cfg(backtrace)]160+ #[cfg(provide_api)]161 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {162 Provider::provide(&self.error, demand);163 }164 }29 unmodified linesmodified:src/error.rs+17 added-19 removed
3 unmodified lines4 use crate::ptr::Mut;5 use crate::ptr::{Own, Ref};6 use crate::{Error, StdError};7 use alloc::boxed::Box;8-#[cfg(backtrace)]8+#[cfg(provide_api)]9 use core::any::Demand;10 use core::any::TypeId;11 use core::fmt::{self, Debug, Display};12 use core::mem::ManuallyDrop;85 unmodified lines98 object_downcast: object_downcast::<E>,99 #[cfg(anyhow_no_ptr_addr_of)]100 object_downcast_mut: object_downcast_mut::<E>,101 object_drop_rest: object_drop_front::<E>,102- #[cfg(all(not(backtrace), feature = "backtrace"))]102+ #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]103 object_backtrace: no_backtrace,104 };105 106 // Safety: passing vtable that operates on the right type E.16 unmodified lines123 object_downcast: object_downcast::<M>,124 #[cfg(anyhow_no_ptr_addr_of)]125 object_downcast_mut: object_downcast_mut::<M>,126 object_drop_rest: object_drop_front::<M>,127- #[cfg(all(not(backtrace), feature = "backtrace"))]127+ #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]128 object_backtrace: no_backtrace,129 };130 131 // Safety: MessageError is repr(transparent) so it is okay for the17 unmodified lines149 object_downcast: object_downcast::<M>,150 #[cfg(anyhow_no_ptr_addr_of)]151 object_downcast_mut: object_downcast_mut::<M>,152 object_drop_rest: object_drop_front::<M>,153- #[cfg(all(not(backtrace), feature = "backtrace"))]153+ #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]154 object_backtrace: no_backtrace,155 };156 157 // Safety: DisplayError is repr(transparent) so it is okay for the19 unmodified lines177 object_downcast: context_downcast::<C, E>,178 #[cfg(anyhow_no_ptr_addr_of)]179 object_downcast_mut: context_downcast_mut::<C, E>,180 object_drop_rest: context_drop_rest::<C, E>,181- #[cfg(all(not(backtrace), feature = "backtrace"))]181+ #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]182 object_backtrace: no_backtrace,183 };184 185 // Safety: passing vtable that operates on the right type.17 unmodified lines203 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,204 #[cfg(anyhow_no_ptr_addr_of)]205 object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,206 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,207- #[cfg(all(not(backtrace), feature = "backtrace"))]207+ #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]208 object_backtrace: no_backtrace,209 };210 211 // Safety: BoxedError is repr(transparent) so it is okay for the vtable104 unmodified lines316 object_downcast: context_chain_downcast::<C>,317 #[cfg(anyhow_no_ptr_addr_of)]318 object_downcast_mut: context_chain_downcast_mut::<C>,319 object_drop_rest: context_chain_drop_rest::<C>,320- #[cfg(all(not(backtrace), feature = "backtrace"))]320+ #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]321 object_backtrace: context_backtrace::<C>,322 };323 324 // As the cause is anyhow::Error, we already have a backtrace for it.19 unmodified lines344 /// `RUST_LIB_BACKTRACE=0`.345 ///346 /// # Stability347 ///348- /// Standard library backtraces are only available on the nightly channel.349- /// Tracking issue: [rust-lang/rust#53487][tracking].350- ///351- /// On stable compilers, this function is only available if the crate's348+ /// Standard library backtraces are only available when using Rust ≥ 1.65.349+ /// On older compilers, this function is only available if the crate's350 /// "backtrace" feature is enabled, and will use the `backtrace` crate as351 /// the underlying backtrace implementation.352 ///353 /// ```toml167 unmodified lines521 }522 }523 }524 527-#[cfg(backtrace)]525+#[cfg(provide_api)]526 impl std::any::Provider for Error {527 // Called by thiserror when you have `#[source] anyhow::Error`. This provide528 // implementation includes the anyhow::Error's Backtrace if any, unlike529 // deref'ing to dyn Error where the provide implementation would include65 unmodified lines595 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,596 #[cfg(anyhow_no_ptr_addr_of)]597 object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,598 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),601- #[cfg(all(not(backtrace), feature = "backtrace"))]599+ #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]600 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,601 }602 603 // Safety: requires layout of *e to match ErrorImpl<E>.93 unmodified lines697 None698 }699 }700 703-#[cfg(all(not(backtrace), feature = "backtrace"))]701+#[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]702 fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {703 let _ = e;704 None705 }113 unmodified lines819 }820 }821 822 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.825-#[cfg(all(not(backtrace), feature = "backtrace"))]823+#[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]824 #[allow(clippy::unnecessary_wraps)]825 unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>826 where827 C: 'static,68 unmodified lines896 this.deref()897 .backtrace898 .as_ref()899 .or_else(|| {902- #[cfg(backtrace)]900+ #[cfg(provide_api)]901 return Self::error(this).request_ref::<Backtrace>();904- #[cfg(not(backtrace))]902+ #[cfg(not(provide_api))]903 return (vtable(this.ptr).object_backtrace)(this);904 })905 .expect("backtrace capture failed")906 }907 910- #[cfg(backtrace)]908+ #[cfg(provide_api)]909 unsafe fn provide<'a>(this: Ref<'a, Self>, demand: &mut Demand<'a>) {910 if let Some(backtrace) = &this.deref().backtrace {911 demand.provide_ref(backtrace);912 }13 unmodified lines926 fn source(&self) -> Option<&(dyn StdError + 'static)> {927 unsafe { ErrorImpl::error(self.erase()).source() }928 }929 932- #[cfg(backtrace)]930+ #[cfg(provide_api)]931 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {932 unsafe { ErrorImpl::provide(self.erase(), demand) }933 }934 }56 unmodified linesmodified:src/lib.rs+5 added-9 removed
126 unmodified lines127 //! }128 //! # ;129 //! ```130 //!131-//! - If using the nightly channel, or stable with `features = ["backtrace"]`, a132-//! backtrace is captured and printed with the error if the underlying error133-//! type does not already provide its own. In order to see backtraces, they134-//! must be enabled through the environment variables described in135-//! [`std::backtrace`]:131+//! - If using Rust ≥ 1.65 or `features = ["backtrace"]`, a backtrace is captured132+//! and printed with the error if the underlying error type does not already133+//! provide its own. In order to see backtraces, they must be enabled through the134+//! environment variables described in [`std::backtrace`]:135 //!136 //! - If you want panics and errors to both have backtraces, set137 //! `RUST_BACKTRACE=1`;138 //! - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`;139 //! - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and140 //! `RUST_LIB_BACKTRACE=0`.141 //!143-//! The tracking issue for this feature is [rust-lang/rust#53487].144-//!142 //! [`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables146-//! [rust-lang/rust#53487]: https://github.com/rust-lang/rust/issues/53487143 //!144 //! - Anyhow works with any error type that has an impl of `std::error::Error`,145 //! including ones defined in your crate. We do not bundle a `derive(Error)`146 //! macro but you can write the impls yourself or use a standalone macro like59 unmodified lines206 //! will require an explicit `.map_err(Error::msg)` when working with a207 //! non-Anyhow error type inside a function that returns Anyhow's error type.208 209 #![doc(html_root_url = "https://docs.rs/anyhow/1.0.68")]214-#![cfg_attr(backtrace, feature(error_generic_member_access, provide_any))]210+#![cfg_attr(provide_api, feature(error_generic_member_access, provide_any))]211 #![cfg_attr(doc_cfg, feature(doc_cfg))]212 #![cfg_attr(not(feature = "std"), no_std)]213 #![deny(dead_code, unused_imports, unused_mut)]214 #![allow(462 unmodified linesmodified:src/wrapper.rs+2 added-2 removed
1 use crate::StdError;2 use core::fmt::{self, Debug, Display};3 4-#[cfg(backtrace)]4+#[cfg(provide_api)]5 use std::any::Demand;6 7 #[repr(transparent)]8 pub struct MessageError<M>(pub M);64 unmodified lines73 fn source(&self) -> Option<&(dyn StdError + 'static)> {74 self.0.source()75 }76 77- #[cfg(backtrace)]77+ #[cfg(provide_api)]78 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {79 self.0.provide(demand);80 }81 }modified:build.rs+14 added-1 removed
55 unmodified lines56 const _: fn(&dyn Error) -> Option<&Backtrace> = |err| err.request_ref::<Backtrace>();57 "#;58 59 fn main() {60+ // If the compile probe succeeds, i.e. if a nightly compiler is used and the61+ // provide API exists, then `std::backtrace` is also usable. So `cfg62+ // (provide_api)` implies `cfg(backtrace)`. We do set `cfg(backtrace)` in63+ // this script explicitly anyway to make the `cfg()` attributes in the main64+ // code less complex.65+ let mut nightly_backtrace_support = false;66 if cfg!(feature = "std") {67 match compile_probe() {62- Some(status) if status.success() => println!("cargo:rustc-cfg=backtrace"),68+ Some(status) if status.success() => {69+ println!("cargo:rustc-cfg=provide_api");70+ nightly_backtrace_support = true;71+ }72 _ => {}73 }74 }75 8 unmodified lines84 85 if rustc < 52 {86 println!("cargo:rustc-cfg=anyhow_no_fmt_arguments_as_str");87 }88+89+ if nightly_backtrace_support || (cfg!(feature = "std") && rustc >= 65) {90+ println!("cargo:rustc-cfg=backtrace");91+ }92 }93 94 fn compile_probe() -> Option<ExitStatus> {95 let rustc = env::var_os("RUSTC")?;49 unmodified linesmodified:README.md+4 added-7 removed
73 unmodified lines74757677787980817879808182838485868788899089929091929386 unmodified lines73 unmodified lines None => Err(error), } ```
- If using the nightly channel, or stable with `features = ["backtrace"]`, a backtrace is captured and printed with the error if the underlying error type does not already provide its own. In order to see backtraces, they must be enabled through the environment variables described in [`std::backtrace`]:- If using Rust ≥ 1.65 or `features = ["backtrace"]`, a backtrace is captured and printed with the error if the underlying error type does not already provide its own. In order to see backtraces, they must be enabled through the environment variables described in [`std::backtrace`]:
- If you want panics and errors to both have backtraces, set `RUST_BACKTRACE=1`; - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`; - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and `RUST_LIB_BACKTRACE=0`.
The tracking issue for this feature is [rust-lang/rust#53487].
[`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables [rust-lang/rust#53487]: https://github.com/rust-lang/rust/issues/53487
- Anyhow works with any error type that has an impl of `std::error::Error`, including ones defined in your crate. We do not bundle a `derive(Error)` macro but you can write the impls yourself or use a standalone macro like86 unmodified lines