Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add backtrace feature #7

Merged
merged 9 commits into from
Apr 26, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions .github/workflows/check-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,27 @@ env:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- toolchain: "1.77"
features: ""
- toolchain: "nightly-2023-12-26"
features: "--features backtrace"

steps:
- uses: actions/checkout@v3
- name: Override Rust toolchain
run: rustup override set ${{ matrix.toolchain }}
- name: Add Rust components
run: rustup component add rustfmt clippy
- name: Format
run: cargo fmt --check
- name: Build
run: cargo build --all-targets --all-features
run: cargo build --all-targets ${{ matrix.features }}
- name: Clippy
run: cargo clippy --all-targets --all-features
run: cargo clippy ${{ matrix.features }} -- -D warnings
- name: Run tests
run: cargo test
run: cargo test --workspace ${{ matrix.features }}
- name: Generate docs
run: RUSTDOCFLAGS="-Dwarnings --cfg docsrs" cargo doc --no-deps
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"rust-analyzer.cargo.features": "all"
}
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ anyhow = "1"
expect-test = "1"
sealed_test = "1"

[features]
backtrace = ["thiserror-ext-derive/backtrace"]

[workspace]
members = ["derive"]
package.version = "0.1.2"
Expand Down
3 changes: 3 additions & 0 deletions derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ license = { workspace = true }
[lib]
proc-macro = true

[features]
backtrace = []

[dependencies]
either = "1"
proc-macro2 = "1"
Expand Down
16 changes: 14 additions & 2 deletions derive/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,14 @@ fn resolve_meta(input: &DeriveInput) -> Result<DeriveMeta> {
let value = meta.value()?;
new_type = Some(value.parse()?);
} else if meta.path.is_ident("backtrace") {
nt_backtrace = true;
if cfg!(feature = "backtrace") {
nt_backtrace = true;
} else {
return Err(Error::new_spanned(
meta.path,
"enable the `backtrace` feature to use `backtrace` attribute",
));
}
} else {
return Err(Error::new_spanned(meta.path, "unknown attribute"));
}
Expand Down Expand Up @@ -274,6 +281,11 @@ pub fn derive_new_type(input: &DeriveInput, ty: DeriveNewType) -> Result<TokenSt
DeriveNewType::Box => quote!(),
DeriveNewType::Arc => quote!(Clone),
};
let backtrace_attr = if cfg!(feature = "backtrace") {
quote!(#[backtrace])
} else {
quote!()
};

let into_inner = match ty {
DeriveNewType::Box => quote!(
Expand All @@ -291,7 +303,7 @@ pub fn derive_new_type(input: &DeriveInput, ty: DeriveNewType) -> Result<TokenSt
#[error(transparent)]
#vis struct #impl_type(
#[from]
#[backtrace]
#backtrace_attr
thiserror_ext::__private::#new_type<
#input_type,
#backtrace_type_param,
Expand Down
14 changes: 7 additions & 7 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ mod thiserror;
///
/// # Example
///
/// ```no_run
/// ```ignore
/// #[derive(Debug, thiserror::Error, thiserror_ext::Construct)]
/// enum Error {
/// #[error("unsupported feature: {0}")]
Expand Down Expand Up @@ -65,7 +65,7 @@ pub fn derive_construct(input: TokenStream) -> TokenStream {
///
/// # Example
///
/// ```no_run
/// ```ignore
/// #[derive(Debug, thiserror::Error, thiserror_ext::ContextInto)]
/// enum Error {
/// #[error("cannot parse int from `{from}`")]
Expand Down Expand Up @@ -126,7 +126,7 @@ pub fn derive_context_into(input: TokenStream) -> TokenStream {
///
/// ## Example
///
/// ```no_run
/// ```ignore
/// #[derive(Debug, thiserror::Error, thiserror_ext::Macro)]
/// enum Error {
/// #[error("internal error: {msg}")]
Expand All @@ -151,7 +151,7 @@ pub fn derive_context_into(input: TokenStream) -> TokenStream {
///
/// ## Example
///
/// ```no_run
/// ```ignore
/// #[derive(Debug, thiserror::Error, thiserror_ext::Macro)]
/// #[error("not yet implemented: {message}")]
/// struct NotYetImplemented {
Expand Down Expand Up @@ -221,7 +221,7 @@ pub fn derive_macro(input: TokenStream) -> TokenStream {
///
/// ## Example
///
/// ```no_run
/// ```ignore
/// #[derive(Debug, thiserror::Error, thiserror_ext::Box)]
/// #[thiserror_ext(newtype(name = Error))]
/// enum ErrorKind {
Expand Down Expand Up @@ -258,7 +258,7 @@ pub fn derive_macro(input: TokenStream) -> TokenStream {
///
/// ## Example
///
/// ```no_run
/// ```ignore
/// # use std::backtrace::Backtrace;
/// #[derive(Debug, thiserror::Error, thiserror_ext::Box)]
/// #[thiserror_ext(newtype(name = Error, backtrace))]
Expand Down Expand Up @@ -312,7 +312,7 @@ pub fn derive_arc(input: TokenStream) -> TokenStream {
/// chain can be kept in these cases.
///
/// # Example
/// ```no_run
/// ```ignore
/// #[derive(thiserror::Error, thiserror_ext::ReportDebug)]
/// #[error("inner")]
/// struct Inner;
Expand Down
2 changes: 1 addition & 1 deletion examples/context.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! This example demonstrates how to achieve the similar functionality as
//! [`anyhow::Context`] with `thiserror_ext`, in a type-safer manner.

#![feature(error_generic_member_access)]
#![cfg_attr(feature = "backtrace", feature(error_generic_member_access))]

use thiserror::Error;
use thiserror_ext::{AsReport, Box, ContextInto, Macro};
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "nightly-2023-10-21"
channel = "nightly-2023-12-26"
43 changes: 26 additions & 17 deletions src/backtrace.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use std::backtrace::Backtrace;

/// Provides backtrace to the error.
pub trait WithBacktrace {
/// Capture backtrace based on whether the error already has one.
fn capture(inner: &dyn std::error::Error) -> Self;

#[cfg(feature = "backtrace")]
/// Provide the backtrace, if any.
fn provide<'a>(&'a self, request: &mut std::error::Request<'a>);
}
Expand All @@ -13,30 +12,40 @@ pub trait WithBacktrace {
#[derive(Clone, Copy)]
pub struct NoExtraBacktrace;

/// Capture backtrace if the error does not already have one.
pub struct MaybeBacktrace(Option<Backtrace>);

impl WithBacktrace for NoExtraBacktrace {
fn capture(_inner: &dyn std::error::Error) -> Self {
Self
}

#[cfg(feature = "backtrace")]
fn provide<'a>(&'a self, _request: &mut std::error::Request<'a>) {}
}

impl WithBacktrace for MaybeBacktrace {
fn capture(inner: &dyn std::error::Error) -> Self {
let inner = if std::error::request_ref::<Backtrace>(inner).is_none() {
Some(Backtrace::capture())
} else {
None
};
Self(inner)
}
#[cfg(feature = "backtrace")]
mod maybe {
use super::WithBacktrace;
use std::backtrace::Backtrace;

/// Capture backtrace if the error does not already have one.
pub struct MaybeBacktrace(Option<Backtrace>);

impl WithBacktrace for MaybeBacktrace {
fn capture(inner: &dyn std::error::Error) -> Self {
let inner = if std::error::request_ref::<Backtrace>(inner).is_none() {
Some(Backtrace::capture())
} else {
None
};
Self(inner)
}

fn provide<'a>(&'a self, request: &mut std::error::Request<'a>) {
if let Some(backtrace) = &self.0 {
request.provide_ref(backtrace);
fn provide<'a>(&'a self, request: &mut std::error::Request<'a>) {
if let Some(backtrace) = &self.0 {
request.provide_ref(backtrace);
}
}
}
}

#[cfg(feature = "backtrace")]
pub use maybe::MaybeBacktrace;
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
//! wrap an `enum` error type into a new type, reducing the size to improve
//! performance, and automatically capturing backtraces if needed.

#![feature(error_generic_member_access)] // TODO: it's nightly-only
#![cfg_attr(feature = "backtrace", feature(error_generic_member_access))]

mod as_dyn;
mod backtrace;
Expand All @@ -30,7 +30,9 @@ pub use thiserror_ext_derive::*;

#[doc(hidden)]
pub mod __private {
pub use crate::backtrace::{MaybeBacktrace, NoExtraBacktrace};
#[cfg(feature = "backtrace")]
pub use crate::backtrace::MaybeBacktrace;
pub use crate::backtrace::NoExtraBacktrace;
pub use crate::ptr::{ErrorArc, ErrorBox};
pub use thiserror;
}
Expand Down
2 changes: 2 additions & 0 deletions src/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ macro_rules! impl_methods {
}

impl<T, B> $ty<T, B> {
#[cfg_attr(not(feature = "backtrace"), allow(dead_code))]
fn backtrace(&self) -> &B {
&self.0.as_ref().1
}
Expand Down Expand Up @@ -78,6 +79,7 @@ macro_rules! impl_methods {
}

// https://github.com/rust-lang/rust/issues/117432
#[cfg(feature = "backtrace")]
fn provide<'a>(&'a self, request: &mut std::error::Request<'a>) {
self.backtrace().provide(request);
T::provide(self.inner(), request);
Expand Down
42 changes: 22 additions & 20 deletions src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{
backtrace::{Backtrace, BacktraceStatus},
fmt,
};
use std::fmt;

/// Extension trait for [`Error`] that provides a [`Report`] which formats
/// the error and its sources in a cleaned-up way.
Expand All @@ -32,8 +29,8 @@ pub trait AsReport: crate::error_sealed::Sealed {
/// like under different options.
///
/// # Example
/// ```no_run
/// use thiserror::AsReport;
/// ```ignore
/// use thiserror_ext::AsReport;
///
/// let error = fallible_action().unwrap_err();
/// println!("{}", error.as_report());
Expand Down Expand Up @@ -187,23 +184,28 @@ impl<'a> fmt::Display for Report<'a> {

impl<'a> fmt::Debug for Report<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Hack for testing purposes.
// Read the env var could be slow but we short-circuit it in release mode,
// so this should be optimized out in production.
let force_show_backtrace = cfg!(debug_assertions)
&& std::env::var("THISERROR_EXT_TEST_SHOW_USELESS_BACKTRACE").is_ok();

self.cleaned_error_trace(f, f.alternate())?;

if let Some(bt) = std::error::request_ref::<Backtrace>(self.0) {
// If the backtrace is disabled or unsupported, behave as if there's no backtrace.
if bt.status() == BacktraceStatus::Captured || force_show_backtrace {
// The alternate mode contains a trailing newline while non-alternate
// mode does not. So we need to add a newline before the backtrace.
if !f.alternate() {
writeln!(f)?;
#[cfg(feature = "backtrace")]
{
use std::backtrace::{Backtrace, BacktraceStatus};

if let Some(bt) = std::error::request_ref::<Backtrace>(self.0) {
// Hack for testing purposes.
// Read the env var could be slow but we short-circuit it in release mode,
// so this should be optimized out in production.
let force_show_backtrace = cfg!(debug_assertions)
&& std::env::var("THISERROR_EXT_TEST_SHOW_USELESS_BACKTRACE").is_ok();

// If the backtrace is disabled or unsupported, behave as if there's no backtrace.
if bt.status() == BacktraceStatus::Captured || force_show_backtrace {
// The alternate mode contains a trailing newline while non-alternate
// mode does not. So we need to add a newline before the backtrace.
if !f.alternate() {
writeln!(f)?;
}
writeln!(f, "\nBacktrace:\n{}", bt)?;
}
writeln!(f, "\nBacktrace:\n{}", bt)?;
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/arc_new_type.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![feature(error_generic_member_access)]
#![cfg_attr(feature = "backtrace", feature(error_generic_member_access))]

use std::{error::Error, num::ParseIntError};

Expand Down
1 change: 1 addition & 0 deletions tests/backtrace.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![cfg(feature = "backtrace")]
#![feature(error_generic_member_access)]

use std::backtrace::Backtrace;
Expand Down
Loading
Loading