Skip to content
Myr

Detect nightly and only expose backtrace if available

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

authored by David Tolnay · committed by David Tolnay · parent 3cd7273 · Browse files · 4 files+71 added−15 removed
This commit

State

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

Diff stats

4 files+71 added−15 removed

  • other:+71 added−15 removed

4 files+71 added−15 removed

modified:src/context.rs+5 added-2 removed
1use std::backtrace::Backtrace;1use crate::Error;2use std::error::Error as StdError;3use std::fmt::{self, Debug, Display};45use crate::Error;5#[cfg(backtrace)]6use std::backtrace::Backtrace;78/// Provides the `context` method for `Result`.9pub trait Context<T, E> {10 /// Wrap the error value with additional context.
78 unmodified lines
89where90 E: StdError + 'static,91 C: Display,92{93 #[cfg(backtrace)]94 fn backtrace(&self) -> Option<&Backtrace> {95 self.error.backtrace()96 }97
5 unmodified lines
103impl<C> StdError for ContextError<Error, C>104where105 C: Display,106{107 #[cfg(backtrace)]108 fn backtrace(&self) -> Option<&Backtrace> {109 Some(self.error.backtrace())110 }111
4 unmodified lines
modified:src/error.rs+26 added-12 removed
1use crate::context::ContextError;2use std::any::TypeId;3use std::backtrace::{Backtrace, BacktraceStatus};3use std::error::Error as StdError;4use std::fmt::{self, Debug, Display};5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;89#[cfg(backtrace)]10use std::backtrace::{Backtrace, BacktraceStatus};1112/// The `Error` type, a wrapper around a dynamic error type.13///14/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these15/// differences:
33 unmodified lines
49 fn construct<E>(error: E, type_id: TypeId) -> Self50 where51 E: StdError + Send + Sync + 'static,52 {53 #[cfg(backtrace)]54 let backtrace = match error.backtrace() {55 Some(_) => None,56 None => Some(Backtrace::capture()),57 };
3 unmodified lines
61 let vtable = obj.vtable;62 let inner = Box::new(ErrorImpl {63 vtable,64 type_id,65 #[cfg(backtrace)]66 backtrace,67 error,68 });69 Error {
23 unmodified lines
93 self.inner.error_mut()94 }9596 /// Get the backtrace for this Error.97 ///98 /// Backtraces are only available on the nightly channel. Tracking issue:99 /// [rust-lang/rust#53487][tracking].100 ///101 /// [tracking]: https://github.com/rust-lang/rust/issues/53487102 #[cfg(backtrace)]103 pub fn backtrace(&self) -> &Backtrace {104 // NB: this unwrap can only fail if the underlying error's backtrace105 // method is nondeterministic, which would only happen in maliciously106 // constructed code
99 unmodified lines
206 writeln!(f, "\t{}: {}", n, error)?;207 }208 }209210 #[cfg(backtrace)]211 {200 let backtrace = self.backtrace();201 match backtrace.status() {202 BacktraceStatus::Captured => {203 writeln!(f, "\n{}", backtrace)?;212 let backtrace = self.backtrace();213 match backtrace.status() {214 BacktraceStatus::Captured => {215 writeln!(f, "\n{}", backtrace)?;216 }217 BacktraceStatus::Disabled => {218 writeln!(219 f,220 "\nbacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"221 )?;222 }223 _ => {}224 }205 BacktraceStatus::Disabled => {206 writeln!(207 f,208 "\nbacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"209 )?;210 }211 _ => {}225 }226227 Ok(())228 }
18 unmodified lines
247#[repr(C)]248struct ErrorImpl<E> {249 vtable: *const (),250 type_id: TypeId,251 #[cfg(backtrace)]252 backtrace: Option<Backtrace>,253 error: E,254}255
118 unmodified lines
modified:src/lib.rs+1 added-1 removed
1#![feature(backtrace)]1#![cfg_attr(backtrace, feature(backtrace))]23mod context;4mod error;5
39 unmodified lines
added:build.rs+39 added
1use std::env;2use std::process::Command;3use std::str;45fn main() {6 let compiler = match rustc_version() {7 Some(compiler) => compiler,8 None => return,9 };1011 if compiler.nightly {12 println!("cargo:rustc-cfg=backtrace");13 }14}1516struct Compiler {17 nightly: bool,18}1920fn rustc_version() -> Option<Compiler> {21 let rustc = match env::var_os("RUSTC") {22 Some(rustc) => rustc,23 None => return None,24 };2526 let output = match Command::new(rustc).arg("--version").output() {27 Ok(output) => output,28 Err(_) => return None,29 };3031 let version = match str::from_utf8(&output.stdout) {32 Ok(version) => version,33 Err(_) => return None,34 };3536 Some(Compiler {37 nightly: version.contains("nightly") || version.contains("dev"),38 })39}