1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
//! This crate implements a parser for backtraces.
//!
//! The aim is to parse backtraces in the standard format
//! that any Rust program can generate, for instance when
//! crashing due to a panic, by creating a `failure::Error`,
//! or by using the [`backtrace`][1] crate directly.
//!
//! The parser follows a zero-copy approach, which means that
//! the input string can be provided by reference, and will not
//! be copied during parsing. This has the effect that parsing
//! a captured backtrace tends to be very performant.
//!
//! [1]: https://crates.io/crates/backtrace
//!
//! ## Example
//!
//! ```rust
//! use backtrace_parser::Backtrace;
//!
//! # let input = "stack backtrace: 0: 0x0 - <no info>";
//! let backtrace = Backtrace::parse(input).unwrap();
//!
//! for frame in backtrace.frames() {
//!     for symbol in frame.symbols() {
//!         println!("symbol: {:?}", symbol);
//!     }
//! }
//! ```
//!

#![deny(warnings)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]

extern crate pest;
#[macro_use]
extern crate pest_derive;

use std::error;
use std::fmt;
use std::path::Path;

use pest::Parser;

mod parser;
use self::parser::{BacktraceParser, Rule};

#[derive(Debug)]
/// Represents a parser error.
pub struct Error<'a> {
    inner: pest::Error<'a, Rule>,
}

impl<'a> fmt::Display for Error<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.inner, f)
    }
}

impl<'a> error::Error for Error<'a> {}

#[derive(Debug)]
/// Represents a parsed backtrace.
pub struct Backtrace<'a> {
    pairs: pest::iterators::Pairs<'a, Rule>,
}

impl<'a> Backtrace<'a> {
    /// Parse the provided input string and return either a parsed backtrace,
    /// or a parse error.
    pub fn parse(input: &'a str) -> Result<Backtrace<'a>, Error<'a>> {
        let pairs =
            BacktraceParser::parse(Rule::backtrace, input).map_err(|err| Error { inner: err })?;

        Ok(Backtrace { pairs })
    }

    /// Create an iterator over the stack frames in this backtrace.
    pub fn frames(&self) -> Frames<'a> {
        Frames {
            inner: self.pairs.clone(),
        }
    }
}

#[derive(Debug)]
/// Iterator over the stack frames in a parsed backtrace.
pub struct Frames<'a> {
    inner: pest::iterators::Pairs<'a, Rule>,
}

impl<'a> Iterator for Frames<'a> {
    type Item = Frame<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(frame) = self.inner.next() {
            debug_assert!(frame.as_rule() == Rule::frame);
            let mut frame_inner = frame.into_inner();

            let frame_index = frame_inner.next().unwrap();
            debug_assert!(frame_index.as_rule() == Rule::frame_index);
            let frame_pointer = frame_inner.next().unwrap();
            debug_assert!(frame_pointer.as_rule() == Rule::frame_pointer);

            Some(Frame { pairs: frame_inner })
        } else {
            None
        }
    }
}

#[derive(Debug)]
/// Represents a parsed stack frame.
pub struct Frame<'a> {
    pairs: pest::iterators::Pairs<'a, Rule>,
}

impl<'a> Frame<'a> {
    /// Create an iterator over the symbols in this stack frame.
    pub fn symbols(&self) -> Symbols<'a> {
        Symbols {
            inner: self.pairs.clone(),
        }
    }
}

#[derive(Debug)]
/// Iterator over the symbols in a parsed stack frame.
pub struct Symbols<'a> {
    inner: pest::iterators::Pairs<'a, Rule>,
}

impl<'a> Iterator for Symbols<'a> {
    type Item = Symbol<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(symbol) = self.inner.next() {
            match symbol.as_rule() {
                Rule::symbol_non_empty => {
                    let mut parsed_symbol = Symbol {
                        name: None,
                        filename: None,
                        lineno: None,
                    };
                    let mut symbol_inner = symbol.into_inner();
                    let symbol_name = symbol_inner.next().unwrap();
                    match symbol_name.as_rule() {
                        Rule::symbol_name_known => {
                            parsed_symbol.name = Some(symbol_name.into_span().as_str())
                        }
                        _ => {}
                    }
                    if let Some(symbol_location) = symbol_inner.next() {
                        debug_assert!(symbol_location.as_rule() == Rule::symbol_location);
                        let mut symbol_location_inner = symbol_location.into_inner();
                        let symbol_location_path = symbol_location_inner.next().unwrap();
                        debug_assert!(symbol_location_path.as_rule() == Rule::symbol_location_path);
                        parsed_symbol.filename =
                            Some(Path::new(symbol_location_path.into_span().as_str()));
                        let symbol_location_lineno = symbol_location_inner.next().unwrap();
                        debug_assert!(
                            symbol_location_lineno.as_rule() == Rule::symbol_location_lineno
                        );
                        parsed_symbol.lineno =
                            symbol_location_lineno.into_span().as_str().parse().ok();
                    }
                    Some(parsed_symbol)
                }
                _ => None,
            }
        } else {
            None
        }
    }
}

#[derive(Debug)]
/// Represents a parsed symbol.
pub struct Symbol<'a> {
    name: Option<&'a str>,
    filename: Option<&'a Path>,
    lineno: Option<u32>,
}

impl<'a> Symbol<'a> {
    /// Return the name of the symbol, if resolved.
    pub fn name(&self) -> Option<&'a str> {
        self.name
    }

    /// Return the path of the source file, if known.
    pub fn filename(&self) -> Option<&'a Path> {
        self.filename
    }

    /// Return the line number in source file, if known.
    pub fn lineno(&self) -> Option<u32> {
        self.lineno
    }
}