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