10 use text_unit::{TextRange, TextUnit};
12 pub use difference::Changeset as __Changeset;
14 pub const CURSOR_MARKER: &str = "<|>";
17 macro_rules! assert_eq_text {
18 ($left:expr, $right:expr) => {
19 assert_eq_text!($left, $right,)
21 ($left:expr, $right:expr, $($tt:tt)*) => {{
25 if left.trim() == right.trim() {
26 eprintln!("Left:\n{:?}\n\nRight:\n{:?}\n\nWhitespace difference\n", left, right);
28 let changeset = $crate::__Changeset::new(right, left, "\n");
29 eprintln!("Left:\n{}\n\nRight:\n{}\n\nDiff:\n{}\n", left, right, changeset);
32 panic!("text differs");
37 pub fn extract_offset(text: &str) -> (TextUnit, String) {
38 match try_extract_offset(text) {
39 None => panic!("text should contain cursor marker"),
40 Some(result) => result,
44 pub fn try_extract_offset(text: &str) -> Option<(TextUnit, String)> {
45 let cursor_pos = text.find(CURSOR_MARKER)?;
46 let mut new_text = String::with_capacity(text.len() - CURSOR_MARKER.len());
47 new_text.push_str(&text[..cursor_pos]);
48 new_text.push_str(&text[cursor_pos + CURSOR_MARKER.len()..]);
49 let cursor_pos = TextUnit::from(cursor_pos as u32);
50 Some((cursor_pos, new_text))
53 pub fn extract_range(text: &str) -> (TextRange, String) {
54 match try_extract_range(text) {
55 None => panic!("text should contain cursor marker"),
56 Some(result) => result,
60 pub fn try_extract_range(text: &str) -> Option<(TextRange, String)> {
61 let (start, text) = try_extract_offset(text)?;
62 let (end, text) = try_extract_offset(&text)?;
63 Some((TextRange::from_to(start, end), text))
66 /// Extracts ranges, marked with `<tag> </tag>` paris from the `text`
67 pub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) {
68 let open = format!("<{}>", tag);
69 let close = format!("</{}>", tag);
70 let mut ranges = Vec::new();
71 let mut res = String::new();
72 let mut stack = Vec::new();
74 match text.find('<') {
80 res.push_str(&text[..i]);
82 if text.starts_with(&open) {
83 text = &text[open.len()..];
84 let from = TextUnit::of_str(&res);
86 } else if text.starts_with(&close) {
87 text = &text[close.len()..];
88 let from = stack.pop().unwrap_or_else(|| panic!("unmatched </{}>", tag));
89 let to = TextUnit::of_str(&res);
90 ranges.push(TextRange::from_to(from, to));
95 assert!(stack.is_empty(), "unmatched <{}>", tag);
96 ranges.sort_by_key(|r| (r.start(), r.end()));
100 pub fn add_cursor(text: &str, offset: TextUnit) -> String {
101 let offset: u32 = offset.into();
102 let offset: usize = offset as usize;
103 let mut res = String::new();
104 res.push_str(&text[..offset]);
106 res.push_str(&text[offset..]);
111 pub struct FixtureEntry {
116 /// Parses text which looks like this:
124 pub fn parse_fixture(fixture: &str) -> Vec<FixtureEntry> {
125 let mut res = Vec::new();
126 let mut buf = String::new();
127 let mut meta: Option<&str> = None;
131 if let Some(meta) = meta {
132 res.push(FixtureEntry { meta: meta.to_string(), text: buf.clone() });
140 .filter(|it| it.trim_start().starts_with("//-"))
141 .map(|it| it.len() - it.trim_start().len())
143 .expect("empty fixture");
146 .split('\n') // don't use `.lines` to not drop `\r\n`
148 if line.len() >= margin {
149 assert!(line[..margin].trim().is_empty());
150 Some(&line[margin..])
152 assert!(line.trim().is_empty());
158 if line.starts_with("//-") {
161 meta = Some(line["//-".len()..].trim());
171 // Comparison functionality borrowed from cargo:
173 /// Compare a line with an expected pattern.
174 /// - Use `[..]` as a wildcard to match 0 or more characters on the same line
175 /// (similar to `.*` in a regex).
176 pub fn lines_match(expected: &str, actual: &str) -> bool {
177 // Let's not deal with / vs \ (windows...)
178 // First replace backslash-escaped backslashes with forward slashes
179 // which can occur in, for example, JSON output
180 let expected = expected.replace("\\\\", "/").replace("\\", "/");
181 let mut actual: &str = &actual.replace("\\\\", "/").replace("\\", "/");
182 for (i, part) in expected.split("[..]").enumerate() {
183 match actual.find(part) {
185 if i == 0 && j != 0 {
188 actual = &actual[j + part.len()..];
190 None => return false,
193 actual.is_empty() || expected.ends_with("[..]")
197 fn lines_match_works() {
198 assert!(lines_match("a b", "a b"));
199 assert!(lines_match("a[..]b", "a b"));
200 assert!(lines_match("a[..]", "a b"));
201 assert!(lines_match("[..]", "a b"));
202 assert!(lines_match("[..]b", "a b"));
204 assert!(!lines_match("[..]b", "c"));
205 assert!(!lines_match("b", "c"));
206 assert!(!lines_match("b", "cb"));
209 // Compares JSON object for approximate equality.
210 // You can use `[..]` wildcard in strings (useful for OS dependent things such
211 // as paths). You can use a `"{...}"` string literal as a wildcard for
212 // arbitrary nested JSON (useful for parts of object emitted by other programs
213 // (e.g. rustc) rather than Cargo itself). Arrays are sorted before comparison.
214 pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a Value, &'a Value)> {
215 use serde_json::Value::*;
216 match (expected, actual) {
217 (&Number(ref l), &Number(ref r)) if l == r => None,
218 (&Bool(l), &Bool(r)) if l == r => None,
219 (&String(ref l), &String(ref r)) if lines_match(l, r) => None,
220 (&Array(ref l), &Array(ref r)) => {
221 if l.len() != r.len() {
222 return Some((expected, actual));
225 let mut l = l.iter().collect::<Vec<_>>();
226 let mut r = r.iter().collect::<Vec<_>>();
228 l.retain(|l| match r.iter().position(|r| find_mismatch(l, r).is_none()) {
237 assert!(!r.is_empty());
240 assert_eq!(r.len(), 0);
244 (&Object(ref l), &Object(ref r)) => {
245 let same_keys = l.len() == r.len() && l.keys().all(|k| r.contains_key(k));
247 return Some((expected, actual));
250 l.values().zip(r.values()).filter_map(|(l, r)| find_mismatch(l, r)).nth(0)
252 (&Null, &Null) => None,
253 // magic string literal "{...}" acts as wildcard for any sub-JSON
254 (&String(ref l), _) if l == "{...}" => None,
255 _ => Some((expected, actual)),
259 pub fn dir_tests<F>(test_data_dir: &Path, paths: &[&str], f: F)
261 F: Fn(&str, &Path) -> String,
263 for (path, input_code) in collect_tests(test_data_dir, paths) {
264 let parse_tree = f(&input_code, &path);
265 let path = path.with_extension("txt");
267 println!("\nfile: {}", path.display());
268 println!("No .txt file with expected result, creating...\n");
269 println!("{}\n{}", input_code, parse_tree);
270 fs::write(&path, &parse_tree).unwrap();
271 panic!("No expected result")
273 let expected = read_text(&path);
274 let expected = expected.as_str();
275 let parse_tree = parse_tree.as_str();
276 assert_equal_text(expected, parse_tree, &path);
280 pub fn collect_tests(test_data_dir: &Path, paths: &[&str]) -> Vec<(PathBuf, String)> {
284 let path = test_data_dir.to_owned().join(path);
285 test_from_dir(&path).into_iter()
288 let text = read_text(&path);
294 fn test_from_dir(dir: &Path) -> Vec<PathBuf> {
295 let mut acc = Vec::new();
296 for file in fs::read_dir(&dir).unwrap() {
297 let file = file.unwrap();
298 let path = file.path();
299 if path.extension().unwrap_or_default() == "rs" {
307 pub fn project_dir() -> PathBuf {
308 let dir = env!("CARGO_MANIFEST_DIR");
309 PathBuf::from(dir).parent().unwrap().parent().unwrap().to_owned()
312 /// Read file and normalize newlines.
314 /// `rustc` seems to always normalize `\r\n` newlines to `\n`:
319 /// assert_eq!(s.as_bytes(), &[10]);
322 /// so this should always be correct.
323 pub fn read_text(path: &Path) -> String {
324 fs::read_to_string(path)
325 .unwrap_or_else(|_| panic!("File at {:?} should be valid", path))
326 .replace("\r\n", "\n")
329 const REWRITE: bool = false;
331 fn assert_equal_text(expected: &str, actual: &str, path: &Path) {
332 if expected == actual {
335 let dir = project_dir();
336 let pretty_path = path.strip_prefix(&dir).unwrap_or_else(|_| path);
337 if expected.trim() == actual.trim() {
338 println!("whitespace difference, rewriting");
339 println!("file: {}\n", pretty_path.display());
340 fs::write(path, actual).unwrap();
344 println!("rewriting {}", pretty_path.display());
345 fs::write(path, actual).unwrap();
348 assert_eq_text!(expected, actual, "file: {}", pretty_path.display());