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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use super::{Record, RecordKind};
use failure::Fail;
use std::num::ParseIntError;
use std::path::PathBuf;
use std::str::FromStr;

/// All possible errors that can occur when parsing LCOV record kind.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct ParseRecordKindError;

impl FromStr for RecordKind {
    type Err = ParseRecordKindError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use RecordKind::*;
        let kind = match s {
            "TN" => TestName,
            "SF" => SourceFile,
            "FN" => FunctionName,
            "FNDA" => FunctionData,
            "FNF" => FunctionsFound,
            "FNH" => FunctionsHit,
            "BRDA" => BranchData,
            "BRF" => BranchesFound,
            "BRH" => BranchesHit,
            "DA" => LineData,
            "LF" => LinesFound,
            "LH" => LinesHit,
            "end_of_record" => EndOfRecord,
            _ => Err(ParseRecordKindError)?,
        };

        Ok(kind)
    }
}

/// All possible errors that can occur when parsing LCOV record.
#[derive(Debug, Clone, Fail, Eq, PartialEq)]
pub enum ParseRecordError {
    /// An error indicating that the field of the record is not found in the input.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lcov::Record;
    /// use lcov::record::ParseRecordError;
    /// assert_eq!("FNDA:3".parse::<Record>(), Err(ParseRecordError::FieldNotFound("name")));
    /// ```
    #[fail(display = "field `{}` not found", _0)]
    FieldNotFound(&'static str),

    /// An error indicating that the number of fields is larger than expected.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lcov::Record;
    /// use lcov::record::ParseRecordError;
    /// assert_eq!("LF:1,2".parse::<Record>(), Err(ParseRecordError::TooManyFields));
    /// ```
    #[fail(display = "too many fields found")]
    TooManyFields,

    /// An error indicating that parsing integer field failed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use matches::assert_matches;
    /// # fn main() {
    /// use lcov::Record;
    /// use lcov::record::ParseRecordError;
    /// assert_matches!("LH:foo".parse::<Record>(), Err(ParseRecordError::ParseIntError("hit", _)));
    /// # }
    /// ```
    #[fail(display = "invalid value of field `{}`: {}", _0, _1)]
    ParseIntError(&'static str, #[cause] ParseIntError),

    /// An error indicating that the unknown record is found in the input.
    ///
    /// # Example
    ///
    /// ```rust
    /// use lcov::Record;
    /// use lcov::record::ParseRecordError;
    /// assert_eq!("FOO:1,2".parse::<Record>(), Err(ParseRecordError::UnknownRecord));
    /// ```
    #[fail(display = "unknown record")]
    UnknownRecord,
}

macro_rules! replace_expr {
    ($_id:ident $sub:expr) => {
        $sub
    };
}
macro_rules! count_idents {
    ($($id:ident)*) => { 0 $(+ replace_expr!($id 1))* }
}
macro_rules! parse_record {
    ($input:expr => $rec:ident { $($field:ident,)* .. $last: ident}) => {{
        let mut sp = $input.splitn(count_idents!($($field)*) + 1, ',');
        let rec = $rec {
            $($field: ParseField::parse_iter_next(&mut sp, stringify!($field))?,)*
            $last: ParseField::parse_iter_next(&mut sp, stringify!($last))?
        };
        debug_assert!(sp.next().is_none());
        Ok(rec)
    }};
    ($input:expr => $rec:ident { $($field:ident,)* .. ?$last: ident}) => {{
        let mut sp = $input.splitn(count_idents!($($field)*) + 1, ',');
        let rec = $rec {
            $($field: ParseField::parse_iter_next(&mut sp, stringify!($field))?,)*
            $last: if let Some(s) = sp.next() {
                ParseField::parse_field(s, stringify!($last))?
            } else {
                None
            }
        };
        debug_assert!(sp.next().is_none());
        Ok(rec)
    }};
    ($input:expr => $rec:ident { $($field:ident),* $(,?$opt_field:ident),* }) => {{
        let mut sp = $input.split(',');
        let rec = $rec {
            $($field: ParseField::parse_iter_next(&mut sp, stringify!($field))?,)*
            $($opt_field: if let Some(s) = sp.next() {
                Some(ParseField::parse_field(s, stringify!($opt_field))?)
            } else {
                None
            },)*
        };
        if sp.next().is_some() {
            return Err(ParseRecordError::TooManyFields)
        }
        Ok(rec)
    }};
}

impl FromStr for Record {
    type Err = ParseRecordError;

    fn from_str(mut s: &str) -> Result<Self, Self::Err> {
        use Record::*;
        use RecordKind as Kind;

        s = s.trim_right_matches::<&[_]>(&['\n', '\r']);
        let mut sp = s.splitn(2, ':');

        let kind = sp
            .next()
            .unwrap()
            .parse::<RecordKind>()
            .map_err(|_e| ParseRecordError::UnknownRecord)?;
        let body = sp.next().unwrap_or("");
        debug_assert!(sp.next().is_none());

        match kind {
            Kind::TestName => parse_record!(body => TestName { .. name }),
            Kind::SourceFile => parse_record!(body => SourceFile { .. path }),
            Kind::FunctionName => parse_record!(body => FunctionName { start_line, .. name }),
            Kind::FunctionData => parse_record!(body => FunctionData { count, .. name }),
            Kind::FunctionsFound => parse_record!(body => FunctionsFound { found }),
            Kind::FunctionsHit => parse_record!(body => FunctionsHit { hit }),
            Kind::BranchData => parse_record!(body => BranchData { line, block, branch, taken}),
            Kind::BranchesFound => parse_record!(body => BranchesFound { found }),
            Kind::BranchesHit => parse_record!(body => BranchesHit { hit }),
            Kind::LineData => parse_record!(body => LineData { line, count, .. ?checksum }),
            Kind::LinesFound => parse_record!(body => LinesFound { found }),
            Kind::LinesHit => parse_record!(body => LinesHit { hit }),
            Kind::EndOfRecord => Ok(EndOfRecord),
        }
    }
}

trait ParseField: Sized {
    fn parse_field(s: &str, name: &'static str) -> Result<Self, ParseRecordError>;
    fn parse_iter_next<'a, I>(it: &mut I, name: &'static str) -> Result<Self, ParseRecordError>
    where
        I: Iterator<Item = &'a str>,
    {
        let s = it
            .next()
            .ok_or_else(|| ParseRecordError::FieldNotFound(name))?;
        Self::parse_field(s, name)
    }
}

impl ParseField for String {
    fn parse_field(s: &str, _name: &'static str) -> Result<Self, ParseRecordError> {
        Ok(s.into())
    }
}

impl ParseField for PathBuf {
    fn parse_field(s: &str, _name: &'static str) -> Result<Self, ParseRecordError> {
        Ok(From::from(s))
    }
}

impl ParseField for u32 {
    fn parse_field(s: &str, name: &'static str) -> Result<Self, ParseRecordError> {
        s.parse()
            .map_err(|e| ParseRecordError::ParseIntError(name, e))
    }
}

impl ParseField for u64 {
    fn parse_field(s: &str, name: &'static str) -> Result<Self, ParseRecordError> {
        s.parse()
            .map_err(|e| ParseRecordError::ParseIntError(name, e))
    }
}
impl<T> ParseField for Option<T>
where
    T: ParseField,
{
    fn parse_field(s: &str, name: &'static str) -> Result<Self, ParseRecordError> {
        let val = if s == "-" {
            None
        } else {
            Some(ParseField::parse_field(s, name)?)
        };
        Ok(val)
    }
}