]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/test/mod.rs
Rollup merge of #97711 - Nilstrieb:rustc-arena-ub, r=wesleywiser
[rust.git] / src / tools / rustfmt / src / test / mod.rs
1 use std::collections::HashMap;
2 use std::env;
3 use std::fs;
4 use std::io::{self, BufRead, BufReader, Read, Write};
5 use std::iter::Peekable;
6 use std::mem;
7 use std::path::{Path, PathBuf};
8 use std::process::{Command, Stdio};
9 use std::str::Chars;
10 use std::thread;
11
12 use crate::config::{Color, Config, EmitMode, FileName, NewlineStyle};
13 use crate::formatting::{ReportedErrors, SourceFile};
14 use crate::rustfmt_diff::{make_diff, print_diff, DiffLine, Mismatch, ModifiedChunk, OutputWriter};
15 use crate::source_file;
16 use crate::{is_nightly_channel, FormatReport, FormatReportFormatterBuilder, Input, Session};
17
18 use rustfmt_config_proc_macro::nightly_only_test;
19
20 mod configuration_snippet;
21 mod mod_resolver;
22 mod parser;
23
24 const DIFF_CONTEXT_SIZE: usize = 3;
25
26 // A list of files on which we want to skip testing.
27 const FILE_SKIP_LIST: &[&str] = &[
28     // We want to make sure that the `skip_children` is correctly working,
29     // so we do not want to test this file directly.
30     "configs/skip_children/foo/mod.rs",
31     "issue-3434/no_entry.rs",
32     "issue-3665/sub_mod.rs",
33     // Testing for issue-3779
34     "issue-3779/ice.rs",
35     // These files and directory are a part of modules defined inside `cfg_if!`.
36     "cfg_if/mod.rs",
37     "cfg_if/detect",
38     "issue-3253/foo.rs",
39     "issue-3253/bar.rs",
40     "issue-3253/paths",
41     // These files and directory are a part of modules defined inside `cfg_attr(..)`.
42     "cfg_mod/dir",
43     "cfg_mod/bar.rs",
44     "cfg_mod/foo.rs",
45     "cfg_mod/wasm32.rs",
46     "skip/foo.rs",
47 ];
48
49 fn init_log() {
50     let _ = env_logger::builder().is_test(true).try_init();
51 }
52
53 struct TestSetting {
54     /// The size of the stack of the thread that run tests.
55     stack_size: usize,
56 }
57
58 impl Default for TestSetting {
59     fn default() -> Self {
60         TestSetting {
61             stack_size: 8_388_608, // 8MB
62         }
63     }
64 }
65
66 fn run_test_with<F>(test_setting: &TestSetting, f: F)
67 where
68     F: FnOnce(),
69     F: Send + 'static,
70 {
71     thread::Builder::new()
72         .stack_size(test_setting.stack_size)
73         .spawn(f)
74         .expect("Failed to create a test thread")
75         .join()
76         .expect("Failed to join a test thread")
77 }
78
79 fn is_subpath<P>(path: &Path, subpath: &P) -> bool
80 where
81     P: AsRef<Path>,
82 {
83     (0..path.components().count())
84         .map(|i| {
85             path.components()
86                 .skip(i)
87                 .take(subpath.as_ref().components().count())
88         })
89         .any(|c| c.zip(subpath.as_ref().components()).all(|(a, b)| a == b))
90 }
91
92 fn is_file_skip(path: &Path) -> bool {
93     FILE_SKIP_LIST
94         .iter()
95         .any(|file_path| is_subpath(path, file_path))
96 }
97
98 // Returns a `Vec` containing `PathBuf`s of files with an  `rs` extension in the
99 // given path. The `recursive` argument controls if files from subdirectories
100 // are also returned.
101 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
102     let mut files = vec![];
103     if path.is_dir() {
104         for entry in fs::read_dir(path).expect(&format!(
105             "couldn't read directory {}",
106             path.to_str().unwrap()
107         )) {
108             let entry = entry.expect("couldn't get `DirEntry`");
109             let path = entry.path();
110             if path.is_dir() && recursive {
111                 files.append(&mut get_test_files(&path, recursive));
112             } else if path.extension().map_or(false, |f| f == "rs") && !is_file_skip(&path) {
113                 files.push(path);
114             }
115         }
116     }
117     files
118 }
119
120 fn verify_config_used(path: &Path, config_name: &str) {
121     for entry in fs::read_dir(path).expect(&format!(
122         "couldn't read {} directory",
123         path.to_str().unwrap()
124     )) {
125         let entry = entry.expect("couldn't get directory entry");
126         let path = entry.path();
127         if path.extension().map_or(false, |f| f == "rs") {
128             // check if "// rustfmt-<config_name>:" appears in the file.
129             let filebuf = BufReader::new(
130                 fs::File::open(&path)
131                     .unwrap_or_else(|_| panic!("couldn't read file {}", path.display())),
132             );
133             assert!(
134                 filebuf
135                     .lines()
136                     .map(Result::unwrap)
137                     .take_while(|l| l.starts_with("//"))
138                     .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
139                 "config option file {} does not contain expected config name",
140                 path.display()
141             );
142         }
143     }
144 }
145
146 #[test]
147 fn verify_config_test_names() {
148     init_log();
149     for path in &[
150         Path::new("tests/source/configs"),
151         Path::new("tests/target/configs"),
152     ] {
153         for entry in fs::read_dir(path).expect("couldn't read configs directory") {
154             let entry = entry.expect("couldn't get directory entry");
155             let path = entry.path();
156             if path.is_dir() {
157                 let config_name = path.file_name().unwrap().to_str().unwrap();
158
159                 // Make sure that config name is used in the files in the directory.
160                 verify_config_used(&path, config_name);
161             }
162         }
163     }
164 }
165
166 // This writes to the terminal using the same approach (via `term::stdout` or
167 // `println!`) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
168 // using only one or the other will cause the output order to differ when
169 // `print_diff` selects the approach not used.
170 fn write_message(msg: &str) {
171     let mut writer = OutputWriter::new(Color::Auto);
172     writer.writeln(msg, None);
173 }
174
175 // Integration tests. The files in `tests/source` are formatted and compared
176 // to their equivalent in `tests/target`. The target file and config can be
177 // overridden by annotations in the source file. The input and output must match
178 // exactly.
179 #[test]
180 fn system_tests() {
181     init_log();
182     run_test_with(&TestSetting::default(), || {
183         // Get all files in the tests/source directory.
184         let files = get_test_files(Path::new("tests/source"), true);
185         let (_reports, count, fails) = check_files(files, &None);
186
187         // Display results.
188         println!("Ran {} system tests.", count);
189         assert_eq!(fails, 0, "{} system tests failed", fails);
190         assert!(
191             count >= 300,
192             "Expected a minimum of {} system tests to be executed",
193             300
194         )
195     });
196 }
197
198 // Do the same for tests/coverage-source directory.
199 // The only difference is the coverage mode.
200 #[test]
201 fn coverage_tests() {
202     init_log();
203     let files = get_test_files(Path::new("tests/coverage/source"), true);
204     let (_reports, count, fails) = check_files(files, &None);
205
206     println!("Ran {} tests in coverage mode.", count);
207     assert_eq!(fails, 0, "{} tests failed", fails);
208 }
209
210 #[test]
211 fn checkstyle_test() {
212     init_log();
213     let filename = "tests/writemode/source/fn-single-line.rs";
214     let expected_filename = "tests/writemode/target/checkstyle.xml";
215     assert_output(Path::new(filename), Path::new(expected_filename));
216 }
217
218 #[test]
219 fn json_test() {
220     init_log();
221     let filename = "tests/writemode/source/json.rs";
222     let expected_filename = "tests/writemode/target/output.json";
223     assert_output(Path::new(filename), Path::new(expected_filename));
224 }
225
226 #[test]
227 fn modified_test() {
228     init_log();
229     use std::io::BufRead;
230
231     // Test "modified" output
232     let filename = "tests/writemode/source/modified.rs";
233     let mut data = Vec::new();
234     let mut config = Config::default();
235     config
236         .set()
237         .emit_mode(crate::config::EmitMode::ModifiedLines);
238
239     {
240         let mut session = Session::new(config, Some(&mut data));
241         session.format(Input::File(filename.into())).unwrap();
242     }
243
244     let mut lines = data.lines();
245     let mut chunks = Vec::new();
246     while let Some(Ok(header)) = lines.next() {
247         // Parse the header line
248         let values: Vec<_> = header
249             .split(' ')
250             .map(|s| s.parse::<u32>().unwrap())
251             .collect();
252         assert_eq!(values.len(), 3);
253         let line_number_orig = values[0];
254         let lines_removed = values[1];
255         let num_added = values[2];
256         let mut added_lines = Vec::new();
257         for _ in 0..num_added {
258             added_lines.push(lines.next().unwrap().unwrap());
259         }
260         chunks.push(ModifiedChunk {
261             line_number_orig,
262             lines_removed,
263             lines: added_lines,
264         });
265     }
266
267     assert_eq!(
268         chunks,
269         vec![
270             ModifiedChunk {
271                 line_number_orig: 4,
272                 lines_removed: 4,
273                 lines: vec!["fn blah() {}".into()],
274             },
275             ModifiedChunk {
276                 line_number_orig: 9,
277                 lines_removed: 6,
278                 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
279             },
280         ],
281     );
282 }
283
284 // Helper function for comparing the results of rustfmt
285 // to a known output file generated by one of the write modes.
286 fn assert_output(source: &Path, expected_filename: &Path) {
287     let config = read_config(source);
288     let (_, source_file, _) = format_file(source, config.clone());
289
290     // Populate output by writing to a vec.
291     let mut out = vec![];
292     let _ = source_file::write_all_files(&source_file, &mut out, &config);
293     let output = String::from_utf8(out).unwrap();
294
295     let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
296     let mut expected_text = String::new();
297     expected_file
298         .read_to_string(&mut expected_text)
299         .expect("Failed reading target");
300
301     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
302     if !compare.is_empty() {
303         let mut failures = HashMap::new();
304         failures.insert(source.to_owned(), compare);
305         print_mismatches_default_message(failures);
306         panic!("Text does not match expected output");
307     }
308 }
309
310 // Helper function for comparing the results of rustfmt
311 // to a known output generated by one of the write modes.
312 fn assert_stdin_output(
313     source: &Path,
314     expected_filename: &Path,
315     emit_mode: EmitMode,
316     has_diff: bool,
317 ) {
318     let mut config = Config::default();
319     config.set().newline_style(NewlineStyle::Unix);
320     config.set().emit_mode(emit_mode);
321
322     let mut source_file = fs::File::open(&source).expect("couldn't open source");
323     let mut source_text = String::new();
324     source_file
325         .read_to_string(&mut source_text)
326         .expect("Failed reading target");
327     let input = Input::Text(source_text);
328
329     // Populate output by writing to a vec.
330     let mut buf: Vec<u8> = vec![];
331     {
332         let mut session = Session::new(config, Some(&mut buf));
333         session.format(input).unwrap();
334         let errors = ReportedErrors {
335             has_diff: has_diff,
336             ..Default::default()
337         };
338         assert_eq!(session.errors, errors);
339     }
340
341     let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
342     let mut expected_text = String::new();
343     expected_file
344         .read_to_string(&mut expected_text)
345         .expect("Failed reading target");
346
347     let output = String::from_utf8(buf).unwrap();
348     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
349     if !compare.is_empty() {
350         let mut failures = HashMap::new();
351         failures.insert(source.to_owned(), compare);
352         print_mismatches_default_message(failures);
353         panic!("Text does not match expected output");
354     }
355 }
356 // Idempotence tests. Files in tests/target are checked to be unaltered by
357 // rustfmt.
358 #[nightly_only_test]
359 #[test]
360 fn idempotence_tests() {
361     init_log();
362     run_test_with(&TestSetting::default(), || {
363         // Get all files in the tests/target directory.
364         let files = get_test_files(Path::new("tests/target"), true);
365         let (_reports, count, fails) = check_files(files, &None);
366
367         // Display results.
368         println!("Ran {} idempotent tests.", count);
369         assert_eq!(fails, 0, "{} idempotent tests failed", fails);
370         assert!(
371             count >= 400,
372             "Expected a minimum of {} idempotent tests to be executed",
373             400
374         )
375     });
376 }
377
378 // Run rustfmt on itself. This operation must be idempotent. We also check that
379 // no warnings are emitted.
380 // Issue-3443: these tests require nightly
381 #[nightly_only_test]
382 #[test]
383 fn self_tests() {
384     init_log();
385     let mut files = get_test_files(Path::new("tests"), false);
386     let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
387     for dir in bin_directories {
388         let mut path = PathBuf::from("src");
389         path.push(dir);
390         path.push("main.rs");
391         files.push(path);
392     }
393     files.push(PathBuf::from("src/lib.rs"));
394
395     let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
396     let mut warnings = 0;
397
398     // Display results.
399     println!("Ran {} self tests.", count);
400     assert_eq!(fails, 0, "{} self tests failed", fails);
401
402     for format_report in reports {
403         println!(
404             "{}",
405             FormatReportFormatterBuilder::new(&format_report).build()
406         );
407         warnings += format_report.warning_count();
408     }
409
410     assert_eq!(
411         warnings, 0,
412         "Rustfmt's code generated {} warnings",
413         warnings
414     );
415 }
416
417 #[test]
418 fn format_files_find_new_files_via_cfg_if() {
419     init_log();
420     run_test_with(&TestSetting::default(), || {
421         // To repro issue-4656, it is necessary that these files are parsed
422         // as a part of the same session (hence this separate test runner).
423         let files = vec![
424             Path::new("tests/source/issue-4656/lib2.rs"),
425             Path::new("tests/source/issue-4656/lib.rs"),
426         ];
427
428         let config = Config::default();
429         let mut session = Session::<io::Stdout>::new(config, None);
430
431         let mut write_result = HashMap::new();
432         for file in files {
433             assert!(file.exists());
434             let result = session.format(Input::File(file.into())).unwrap();
435             assert!(!session.has_formatting_errors());
436             assert!(!result.has_warnings());
437             let mut source_file = SourceFile::new();
438             mem::swap(&mut session.source_file, &mut source_file);
439
440             for (filename, text) in source_file {
441                 if let FileName::Real(ref filename) = filename {
442                     write_result.insert(filename.to_owned(), text);
443                 }
444             }
445         }
446         assert_eq!(
447             3,
448             write_result.len(),
449             "Should have uncovered an extra file (format_me_please.rs) via lib.rs"
450         );
451         assert!(handle_result(write_result, None).is_ok());
452     });
453 }
454
455 #[test]
456 fn stdin_formatting_smoke_test() {
457     init_log();
458     let input = Input::Text("fn main () {}".to_owned());
459     let mut config = Config::default();
460     config.set().emit_mode(EmitMode::Stdout);
461     let mut buf: Vec<u8> = vec![];
462     {
463         let mut session = Session::new(config, Some(&mut buf));
464         session.format(input).unwrap();
465         assert!(session.has_no_errors());
466     }
467
468     #[cfg(not(windows))]
469     assert_eq!(buf, "<stdin>:\n\nfn main() {}\n".as_bytes());
470     #[cfg(windows)]
471     assert_eq!(buf, "<stdin>:\n\nfn main() {}\r\n".as_bytes());
472 }
473
474 #[test]
475 fn stdin_parser_panic_caught() {
476     init_log();
477     // See issue #3239.
478     for text in ["{", "}"].iter().cloned().map(String::from) {
479         let mut buf = vec![];
480         let mut session = Session::new(Default::default(), Some(&mut buf));
481         let _ = session.format(Input::Text(text));
482
483         assert!(session.has_parsing_errors());
484     }
485 }
486
487 /// Ensures that `EmitMode::ModifiedLines` works with input from `stdin`. Useful
488 /// when embedding Rustfmt (e.g. inside RLS).
489 #[test]
490 fn stdin_works_with_modified_lines() {
491     init_log();
492     let input = "\nfn\n some( )\n{\n}\nfn main () {}\n";
493     let output = "1 6 2\nfn some() {}\nfn main() {}\n";
494
495     let input = Input::Text(input.to_owned());
496     let mut config = Config::default();
497     config.set().newline_style(NewlineStyle::Unix);
498     config.set().emit_mode(EmitMode::ModifiedLines);
499     let mut buf: Vec<u8> = vec![];
500     {
501         let mut session = Session::new(config, Some(&mut buf));
502         session.format(input).unwrap();
503         let errors = ReportedErrors {
504             has_diff: true,
505             ..Default::default()
506         };
507         assert_eq!(session.errors, errors);
508     }
509     assert_eq!(buf, output.as_bytes());
510 }
511
512 /// Ensures that `EmitMode::Json` works with input from `stdin`.
513 #[test]
514 fn stdin_works_with_json() {
515     init_log();
516     assert_stdin_output(
517         Path::new("tests/writemode/source/stdin.rs"),
518         Path::new("tests/writemode/target/stdin.json"),
519         EmitMode::Json,
520         true,
521     );
522 }
523
524 /// Ensures that `EmitMode::Checkstyle` works with input from `stdin`.
525 #[test]
526 fn stdin_works_with_checkstyle() {
527     init_log();
528     assert_stdin_output(
529         Path::new("tests/writemode/source/stdin.rs"),
530         Path::new("tests/writemode/target/stdin.xml"),
531         EmitMode::Checkstyle,
532         false,
533     );
534 }
535
536 #[test]
537 fn stdin_disable_all_formatting_test() {
538     init_log();
539     let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
540     let mut child = Command::new(rustfmt().to_str().unwrap())
541         .stdin(Stdio::piped())
542         .stdout(Stdio::piped())
543         .arg("--config-path=./tests/config/disable_all_formatting.toml")
544         .spawn()
545         .expect("failed to execute child");
546
547     {
548         let stdin = child.stdin.as_mut().expect("failed to get stdin");
549         stdin
550             .write_all(input.as_bytes())
551             .expect("failed to write stdin");
552     }
553
554     let output = child.wait_with_output().expect("failed to wait on child");
555     assert!(output.status.success());
556     assert!(output.stderr.is_empty());
557     assert_eq!(input, String::from_utf8(output.stdout).unwrap());
558 }
559
560 #[test]
561 fn stdin_generated_files_issue_5172() {
562     init_log();
563     let input = Input::Text("//@generated\nfn   main() {}".to_owned());
564     let mut config = Config::default();
565     config.set().emit_mode(EmitMode::Stdout);
566     config.set().format_generated_files(false);
567     config.set().newline_style(NewlineStyle::Unix);
568     let mut buf: Vec<u8> = vec![];
569     {
570         let mut session = Session::new(config, Some(&mut buf));
571         session.format(input).unwrap();
572         assert!(session.has_no_errors());
573     }
574     // N.B. this should be changed once `format_generated_files` is supported with stdin
575     assert_eq!(
576         String::from_utf8(buf).unwrap(),
577         "<stdin>:\n\n//@generated\nfn main() {}\n",
578     );
579 }
580
581 #[test]
582 fn stdin_handles_mod_inner_ignore_attr() {
583     // see https://github.com/rust-lang/rustfmt/issues/5368
584     init_log();
585     let input = String::from("#![rustfmt::skip]\n\nfn    main() {  }");
586     let mut child = Command::new(rustfmt().to_str().unwrap())
587         .stdin(Stdio::piped())
588         .stdout(Stdio::piped())
589         .spawn()
590         .expect("failed to execute child");
591
592     {
593         let stdin = child.stdin.as_mut().expect("failed to get stdin");
594         stdin
595             .write_all(input.as_bytes())
596             .expect("failed to write stdin");
597     }
598
599     let output = child.wait_with_output().expect("failed to wait on child");
600     assert!(output.status.success());
601     assert!(output.stderr.is_empty());
602     assert_eq!(input, String::from_utf8(output.stdout).unwrap());
603 }
604
605 #[test]
606 fn format_lines_errors_are_reported() {
607     init_log();
608     let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
609     let input = Input::Text(format!("fn {}() {{}}", long_identifier));
610     let mut config = Config::default();
611     config.set().error_on_line_overflow(true);
612     let mut session = Session::<io::Stdout>::new(config, None);
613     session.format(input).unwrap();
614     assert!(session.has_formatting_errors());
615 }
616
617 #[test]
618 fn format_lines_errors_are_reported_with_tabs() {
619     init_log();
620     let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
621     let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
622     let mut config = Config::default();
623     config.set().error_on_line_overflow(true);
624     config.set().hard_tabs(true);
625     let mut session = Session::<io::Stdout>::new(config, None);
626     session.format(input).unwrap();
627     assert!(session.has_formatting_errors());
628 }
629
630 // For each file, run rustfmt and collect the output.
631 // Returns the number of files checked and the number of failures.
632 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
633     let mut count = 0;
634     let mut fails = 0;
635     let mut reports = vec![];
636
637     for file_name in files {
638         let sig_comments = read_significant_comments(&file_name);
639         if sig_comments.contains_key("unstable") && !is_nightly_channel!() {
640             debug!(
641                 "Skipping '{}' because it requires unstable \
642                  features which are only available on nightly...",
643                 file_name.display()
644             );
645             continue;
646         }
647
648         debug!("Testing '{}'...", file_name.display());
649
650         match idempotent_check(&file_name, opt_config) {
651             Ok(ref report) if report.has_warnings() => {
652                 print!("{}", FormatReportFormatterBuilder::new(report).build());
653                 fails += 1;
654             }
655             Ok(report) => reports.push(report),
656             Err(err) => {
657                 if let IdempotentCheckError::Mismatch(msg) = err {
658                     print_mismatches_default_message(msg);
659                 }
660                 fails += 1;
661             }
662         }
663
664         count += 1;
665     }
666
667     (reports, count, fails)
668 }
669
670 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
671     for (file_name, diff) in result {
672         let mismatch_msg_formatter =
673             |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
674         print_diff(diff, &mismatch_msg_formatter, &Default::default());
675     }
676
677     if let Some(mut t) = term::stdout() {
678         t.reset().unwrap_or(());
679     }
680 }
681
682 fn print_mismatches<T: Fn(u32) -> String>(
683     result: HashMap<PathBuf, Vec<Mismatch>>,
684     mismatch_msg_formatter: T,
685 ) {
686     for (_file_name, diff) in result {
687         print_diff(diff, &mismatch_msg_formatter, &Default::default());
688     }
689
690     if let Some(mut t) = term::stdout() {
691         t.reset().unwrap_or(());
692     }
693 }
694
695 fn read_config(filename: &Path) -> Config {
696     let sig_comments = read_significant_comments(filename);
697     // Look for a config file. If there is a 'config' property in the significant comments, use
698     // that. Otherwise, if there are no significant comments at all, look for a config file with
699     // the same name as the test file.
700     let mut config = if !sig_comments.is_empty() {
701         get_config(sig_comments.get("config").map(Path::new))
702     } else {
703         get_config(filename.with_extension("toml").file_name().map(Path::new))
704     };
705
706     for (key, val) in &sig_comments {
707         if key != "target" && key != "config" && key != "unstable" {
708             config.override_value(key, val);
709             if config.is_default(key) {
710                 warn!("Default value {} used explicitly for {}", val, key);
711             }
712         }
713     }
714
715     config
716 }
717
718 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
719     let filepath = filepath.into();
720     let input = Input::File(filepath);
721     let mut session = Session::<io::Stdout>::new(config, None);
722     let result = session.format(input).unwrap();
723     let parsing_errors = session.has_parsing_errors();
724     let mut source_file = SourceFile::new();
725     mem::swap(&mut session.source_file, &mut source_file);
726     (parsing_errors, source_file, result)
727 }
728
729 enum IdempotentCheckError {
730     Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
731     Parse,
732 }
733
734 fn idempotent_check(
735     filename: &PathBuf,
736     opt_config: &Option<PathBuf>,
737 ) -> Result<FormatReport, IdempotentCheckError> {
738     let sig_comments = read_significant_comments(filename);
739     let config = if let Some(ref config_file_path) = opt_config {
740         Config::from_toml_path(config_file_path).expect("`rustfmt.toml` not found")
741     } else {
742         read_config(filename)
743     };
744     let (parsing_errors, source_file, format_report) = format_file(filename, config);
745     if parsing_errors {
746         return Err(IdempotentCheckError::Parse);
747     }
748
749     let mut write_result = HashMap::new();
750     for (filename, text) in source_file {
751         if let FileName::Real(ref filename) = filename {
752             write_result.insert(filename.to_owned(), text);
753         }
754     }
755
756     let target = sig_comments.get("target").map(|x| &(*x)[..]);
757
758     handle_result(write_result, target).map(|_| format_report)
759 }
760
761 // Reads test config file using the supplied (optional) file name. If there's no file name or the
762 // file doesn't exist, just return the default config. Otherwise, the file must be read
763 // successfully.
764 fn get_config(config_file: Option<&Path>) -> Config {
765     let config_file_name = match config_file {
766         None => return Default::default(),
767         Some(file_name) => {
768             let mut full_path = PathBuf::from("tests/config/");
769             full_path.push(file_name);
770             if !full_path.exists() {
771                 return Default::default();
772             };
773             full_path
774         }
775     };
776
777     let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
778     let mut def_config = String::new();
779     def_config_file
780         .read_to_string(&mut def_config)
781         .expect("Couldn't read config");
782
783     Config::from_toml(&def_config, Path::new("tests/config/")).expect("invalid TOML")
784 }
785
786 // Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
787 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
788     let file = fs::File::open(file_name)
789         .unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
790     let reader = BufReader::new(file);
791     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
792     let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
793
794     // Matches lines containing significant comments or whitespace.
795     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
796         .expect("failed creating pattern 2");
797
798     reader
799         .lines()
800         .map(|line| line.expect("failed getting line"))
801         .filter(|line| line_regex.is_match(line))
802         .filter_map(|line| {
803             regex.captures_iter(&line).next().map(|capture| {
804                 (
805                     capture
806                         .get(1)
807                         .expect("couldn't unwrap capture")
808                         .as_str()
809                         .to_owned(),
810                     capture
811                         .get(2)
812                         .expect("couldn't unwrap capture")
813                         .as_str()
814                         .to_owned(),
815                 )
816             })
817         })
818         .collect()
819 }
820
821 // Compares output to input.
822 // TODO: needs a better name, more explanation.
823 fn handle_result(
824     result: HashMap<PathBuf, String>,
825     target: Option<&str>,
826 ) -> Result<(), IdempotentCheckError> {
827     let mut failures = HashMap::new();
828
829     for (file_name, fmt_text) in result {
830         // If file is in tests/source, compare to file with same name in tests/target.
831         let target = get_target(&file_name, target);
832         let open_error = format!("couldn't open target {:?}", target);
833         let mut f = fs::File::open(&target).expect(&open_error);
834
835         let mut text = String::new();
836         let read_error = format!("failed reading target {:?}", target);
837         f.read_to_string(&mut text).expect(&read_error);
838
839         // Ignore LF and CRLF difference for Windows.
840         if !string_eq_ignore_newline_repr(&fmt_text, &text) {
841             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
842             assert!(
843                 !diff.is_empty(),
844                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
845             );
846             failures.insert(file_name, diff);
847         }
848     }
849
850     if failures.is_empty() {
851         Ok(())
852     } else {
853         Err(IdempotentCheckError::Mismatch(failures))
854     }
855 }
856
857 // Maps source file paths to their target paths.
858 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
859     if let Some(n) = file_name
860         .components()
861         .position(|c| c.as_os_str() == "source")
862     {
863         let mut target_file_name = PathBuf::new();
864         for (i, c) in file_name.components().enumerate() {
865             if i == n {
866                 target_file_name.push("target");
867             } else {
868                 target_file_name.push(c.as_os_str());
869             }
870         }
871         if let Some(replace_name) = target {
872             target_file_name.with_file_name(replace_name)
873         } else {
874             target_file_name
875         }
876     } else {
877         // This is either and idempotence check or a self check.
878         file_name.to_owned()
879     }
880 }
881
882 #[test]
883 fn rustfmt_diff_make_diff_tests() {
884     init_log();
885     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
886     assert_eq!(
887         diff,
888         vec![Mismatch {
889             line_number: 1,
890             line_number_orig: 1,
891             lines: vec![
892                 DiffLine::Context("a".into()),
893                 DiffLine::Resulting("b".into()),
894                 DiffLine::Expected("e".into()),
895                 DiffLine::Context("c".into()),
896                 DiffLine::Context("d".into()),
897             ],
898         }]
899     );
900 }
901
902 #[test]
903 fn rustfmt_diff_no_diff_test() {
904     init_log();
905     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
906     assert_eq!(diff, vec![]);
907 }
908
909 // Compare strings without distinguishing between CRLF and LF
910 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
911     let left = CharsIgnoreNewlineRepr(left.chars().peekable());
912     let right = CharsIgnoreNewlineRepr(right.chars().peekable());
913     left.eq(right)
914 }
915
916 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
917
918 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
919     type Item = char;
920
921     fn next(&mut self) -> Option<char> {
922         self.0.next().map(|c| {
923             if c == '\r' {
924                 if *self.0.peek().unwrap_or(&'\0') == '\n' {
925                     self.0.next();
926                     '\n'
927                 } else {
928                     '\r'
929                 }
930             } else {
931                 c
932             }
933         })
934     }
935 }
936
937 #[test]
938 fn string_eq_ignore_newline_repr_test() {
939     init_log();
940     assert!(string_eq_ignore_newline_repr("", ""));
941     assert!(!string_eq_ignore_newline_repr("", "abc"));
942     assert!(!string_eq_ignore_newline_repr("abc", ""));
943     assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
944     assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
945     assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
946 }
947
948 struct TempFile {
949     path: PathBuf,
950 }
951
952 fn make_temp_file(file_name: &'static str) -> TempFile {
953     use std::env::var;
954     use std::fs::File;
955
956     // Used in the Rust build system.
957     let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
958     let path = Path::new(&target_dir).join(file_name);
959
960     let mut file = File::create(&path).expect("couldn't create temp file");
961     let content = "fn main() {}\n";
962     file.write_all(content.as_bytes())
963         .expect("couldn't write temp file");
964     TempFile { path }
965 }
966
967 impl Drop for TempFile {
968     fn drop(&mut self) {
969         use std::fs::remove_file;
970         remove_file(&self.path).expect("couldn't delete temp file");
971     }
972 }
973
974 fn rustfmt() -> PathBuf {
975     let mut me = env::current_exe().expect("failed to get current executable");
976     // Chop of the test name.
977     me.pop();
978     // Chop off `deps`.
979     me.pop();
980
981     me.push("rustfmt");
982     assert!(
983         me.is_file() || me.with_extension("exe").is_file(),
984         "{}",
985         if cfg!(release) {
986             "no rustfmt bin, try running `cargo build --release` before testing"
987         } else {
988             "no rustfmt bin, try running `cargo build` before testing"
989         }
990     );
991     me
992 }
993
994 #[test]
995 fn verify_check_works() {
996     init_log();
997     let temp_file = make_temp_file("temp_check.rs");
998
999     Command::new(rustfmt().to_str().unwrap())
1000         .arg("--check")
1001         .arg(temp_file.path.to_str().unwrap())
1002         .status()
1003         .expect("run with check option failed");
1004 }
1005
1006 #[test]
1007 fn verify_check_works_with_stdin() {
1008     init_log();
1009
1010     let mut child = Command::new(rustfmt().to_str().unwrap())
1011         .arg("--check")
1012         .stdin(Stdio::piped())
1013         .stderr(Stdio::piped())
1014         .spawn()
1015         .expect("run with check option failed");
1016
1017     {
1018         let stdin = child.stdin.as_mut().expect("Failed to open stdin");
1019         stdin
1020             .write_all("fn main() {}\n".as_bytes())
1021             .expect("Failed to write to rustfmt --check");
1022     }
1023     let output = child
1024         .wait_with_output()
1025         .expect("Failed to wait on rustfmt child");
1026     assert!(output.status.success());
1027 }
1028
1029 #[test]
1030 fn verify_check_l_works_with_stdin() {
1031     init_log();
1032
1033     let mut child = Command::new(rustfmt().to_str().unwrap())
1034         .arg("--check")
1035         .arg("-l")
1036         .stdin(Stdio::piped())
1037         .stdout(Stdio::piped())
1038         .stderr(Stdio::piped())
1039         .spawn()
1040         .expect("run with check option failed");
1041
1042     {
1043         let stdin = child.stdin.as_mut().expect("Failed to open stdin");
1044         stdin
1045             .write_all("fn main()\n{}\n".as_bytes())
1046             .expect("Failed to write to rustfmt --check");
1047     }
1048     let output = child
1049         .wait_with_output()
1050         .expect("Failed to wait on rustfmt child");
1051     assert!(output.status.success());
1052     assert_eq!(std::str::from_utf8(&output.stdout).unwrap(), "<stdin>\n");
1053 }