use self::WhichLine::*;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
pub struct ExpectedError {
pub line_num: usize,
pub kind: String,
pub msg: String,
}
#[derive(PartialEq, Debug)]
enum WhichLine { ThisLine, FollowPrevious(usize), AdjustBackward(usize) }
pub fn load_errors(testfile: &Path, cfg: Option<&str>) -> Vec<ExpectedError> {
let rdr = BufReader::new(File::open(testfile).unwrap());
let mut last_nonfollow_error = None;
let tag = match cfg {
Some(rev) => format!("//[{}]~", rev),
None => format!("//~")
};
rdr.lines()
.enumerate()
.filter_map(|(line_num, line)| {
parse_expected(last_nonfollow_error,
line_num + 1,
&line.unwrap(),
&tag)
.map(|(which, error)| {
match which {
FollowPrevious(_) => {}
_ => last_nonfollow_error = Some(error.line_num),
}
error
})
})
.collect()
}
fn parse_expected(last_nonfollow_error: Option<usize>,
line_num: usize,
line: &str,
tag: &str)
-> Option<(WhichLine, ExpectedError)> {
let start = match line.find(tag) { Some(i) => i, None => return None };
let (follow, adjusts) = if line[start + tag.len()..].chars().next().unwrap() == '|' {
(true, 0)
} else {
(false, line[start + tag.len()..].chars().take_while(|c| *c == '^').count())
};
let kind_start = start + tag.len() + adjusts + (follow as usize);
let letters = line[kind_start..].chars();
let kind = letters.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.flat_map(|c| c.to_lowercase())
.collect::<String>();
let letters = line[kind_start..].chars();
let msg = letters.skip_while(|c| c.is_whitespace())
.skip_while(|c| !c.is_whitespace())
.collect::<String>().trim().to_owned();
let (which, line_num) = if follow {
assert!(adjusts == 0, "use either //~| or //~^, not both.");
let line_num = last_nonfollow_error.expect("encountered //~| without \
preceding //~^ line.");
(FollowPrevious(line_num), line_num)
} else {
let which =
if adjusts > 0 { AdjustBackward(adjusts) } else { ThisLine };
let line_num = line_num - adjusts;
(which, line_num)
};
debug!("line={} tag={:?} which={:?} kind={:?} msg={:?}",
line_num, tag, which, kind, msg);
Some((which, ExpectedError { line_num: line_num,
kind: kind,
msg: msg, }))
}