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
Provenance
- Commit
270ea5e- Tree
f6b8ff4- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
3cd7273
4 files changed+71 added−15 removed
modified:src/context.rs+5 added-2 removed
1-use std::backtrace::Backtrace;1+use crate::Error;2 use std::error::Error as StdError;3 use std::fmt::{self, Debug, Display};4 5-use crate::Error;5+#[cfg(backtrace)]6+use std::backtrace::Backtrace;7 8 /// Provides the `context` method for `Result`.9 pub trait Context<T, E> {10 /// Wrap the error value with additional context.78 unmodified lines89 where90 E: StdError + 'static,91 C: Display,92 {93+ #[cfg(backtrace)]94 fn backtrace(&self) -> Option<&Backtrace> {95 self.error.backtrace()96 }97 5 unmodified lines103 impl<C> StdError for ContextError<Error, C>104 where105 C: Display,106 {107+ #[cfg(backtrace)]108 fn backtrace(&self) -> Option<&Backtrace> {109 Some(self.error.backtrace())110 }111 4 unmodified linesmodified:src/error.rs+26 added-12 removed
1 use crate::context::ContextError;2 use std::any::TypeId;3-use std::backtrace::{Backtrace, BacktraceStatus};3 use std::error::Error as StdError;4 use std::fmt::{self, Debug, Display};5 use std::mem;6 use std::ops::{Deref, DerefMut};7 use std::ptr;8 9+#[cfg(backtrace)]10+use std::backtrace::{Backtrace, BacktraceStatus};11+12 /// 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 lines49 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 lines61 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 lines93 self.inner.error_mut()94 }95 96 /// 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 code99 unmodified lines206 writeln!(f, "\t{}: {}", n, error)?;207 }208 }209 210+ #[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 }226 227 Ok(())228 }18 unmodified lines247 #[repr(C)]248 struct ErrorImpl<E> {249 vtable: *const (),250 type_id: TypeId,251+ #[cfg(backtrace)]252 backtrace: Option<Backtrace>,253 error: E,254 }255 118 unmodified linesmodified:src/lib.rs+1 added-1 removed
1-#![feature(backtrace)]1+#![cfg_attr(backtrace, feature(backtrace))]2 3 mod context;4 mod error;5 39 unmodified linesadded:build.rs+39 added
1+use std::env;2+use std::process::Command;3+use std::str;4+5+fn main() {6+ let compiler = match rustc_version() {7+ Some(compiler) => compiler,8+ None => return,9+ };10+11+ if compiler.nightly {12+ println!("cargo:rustc-cfg=backtrace");13+ }14+}15+16+struct Compiler {17+ nightly: bool,18+}19+20+fn rustc_version() -> Option<Compiler> {21+ let rustc = match env::var_os("RUSTC") {22+ Some(rustc) => rustc,23+ None => return None,24+ };25+26+ let output = match Command::new(rustc).arg("--version").output() {27+ Ok(output) => output,28+ Err(_) => return None,29+ };30+31+ let version = match str::from_utf8(&output.stdout) {32+ Ok(version) => version,33+ Err(_) => return None,34+ };35+36+ Some(Compiler {37+ nightly: version.contains("nightly") || version.contains("dev"),38+ })39+}