1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 extern crate lazy_static;
16 extern crate rustfmt_config as config;
17 extern crate rustfmt_core as rustfmt;
20 use std::collections::HashMap;
22 use std::io::{self, BufRead, BufReader, Read};
23 use std::iter::{Enumerate, Peekable};
24 use std::path::{Path, PathBuf};
28 use config::{Color, Config, ReportTactic};
29 use config::summary::Summary;
30 use rustfmt::filemap::write_system_newlines;
31 use rustfmt::rustfmt_diff::*;
33 const DIFF_CONTEXT_SIZE: usize = 3;
34 const CONFIGURATIONS_FILE_NAME: &str = "Configurations.md";
36 // Returns a `Vec` containing `PathBuf`s of files with a rs extension in the
37 // given path. The `recursive` argument controls if files from subdirectories
39 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
40 let mut files = vec![];
42 for entry in fs::read_dir(path).expect(&format!(
43 "Couldn't read directory {}",
44 path.to_str().unwrap()
46 let entry = entry.expect("Couldn't get DirEntry");
47 let path = entry.path();
48 if path.is_dir() && recursive {
49 files.append(&mut get_test_files(&path, recursive));
50 } else if path.extension().map_or(false, |f| f == "rs") {
58 fn verify_config_used(path: &Path, config_name: &str) {
59 for entry in fs::read_dir(path).expect(&format!(
60 "Couldn't read {} directory",
61 path.to_str().unwrap()
63 let entry = entry.expect("Couldn't get directory entry");
64 let path = entry.path();
65 if path.extension().map_or(false, |f| f == "rs") {
66 // check if "// rustfmt-<config_name>:" appears in the file.
67 let filebuf = BufReader::new(
68 fs::File::open(&path).expect(&format!("Couldn't read file {}", path.display())),
74 .take_while(|l| l.starts_with("//"))
75 .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
77 "config option file {} does not contain expected config name",
86 fn verify_config_test_names() {
88 Path::new("tests/source/configs"),
89 Path::new("tests/target/configs"),
91 for entry in fs::read_dir(path).expect("Couldn't read configs directory") {
92 let entry = entry.expect("Couldn't get directory entry");
93 let path = entry.path();
95 let config_name = path.file_name().unwrap().to_str().unwrap();
97 // Make sure that config name is used in the files in the directory.
98 verify_config_used(&path, config_name);
104 // This writes to the terminal using the same approach (via term::stdout or
105 // println!) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
106 // using only one or the other will cause the output order to differ when
107 // `print_diff` selects the approach not used.
108 fn write_message(msg: &str) {
109 let mut writer = OutputWriter::new(Color::Auto);
110 writer.writeln(&format!("{}", msg), None);
113 // Integration tests. The files in the tests/source are formatted and compared
114 // to their equivalent in tests/target. The target file and config can be
115 // overridden by annotations in the source file. The input and output must match
119 // Get all files in the tests/source directory.
120 let files = get_test_files(Path::new("tests/source"), true);
121 let (_reports, count, fails) = check_files(files);
124 println!("Ran {} system tests.", count);
125 assert_eq!(fails, 0, "{} system tests failed", fails);
128 // Do the same for tests/coverage-source directory
129 // the only difference is the coverage mode
131 fn coverage_tests() {
132 let files = get_test_files(Path::new("tests/coverage/source"), true);
133 let (_reports, count, fails) = check_files(files);
135 println!("Ran {} tests in coverage mode.", count);
136 assert_eq!(fails, 0, "{} tests failed", fails);
140 fn checkstyle_test() {
141 let filename = "tests/writemode/source/fn-single-line.rs";
142 let expected_filename = "tests/writemode/target/checkstyle.xml";
143 assert_output(Path::new(filename), Path::new(expected_filename));
148 // Test "modified" output
149 let filename = "tests/writemode/source/modified.rs";
150 let result = get_modified_lines(Input::File(filename.into()), &Config::default()).unwrap();
152 result.modified_lines,
158 lines: vec!["fn blah() {}".into()],
163 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
170 // Helper function for comparing the results of rustfmt
171 // to a known output file generated by one of the write modes.
172 fn assert_output(source: &Path, expected_filename: &Path) {
173 let config = read_config(source);
174 let (_error_summary, file_map, _report) = format_file(source, &config);
176 // Populate output by writing to a vec.
177 let mut out = vec![];
178 let _ = filemap::write_all_files(&file_map, &mut out, &config);
179 let output = String::from_utf8(out).unwrap();
181 let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
182 let mut expected_text = String::new();
184 .read_to_string(&mut expected_text)
185 .expect("Failed reading target");
187 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
188 if !compare.is_empty() {
189 let mut failures = HashMap::new();
190 failures.insert(source.to_owned(), compare);
191 print_mismatches_default_message(failures);
192 assert!(false, "Text does not match expected output");
196 // Idempotence tests. Files in tests/target are checked to be unaltered by
199 fn idempotence_tests() {
200 // Get all files in the tests/target directory.
201 let files = get_test_files(Path::new("tests/target"), true);
202 let (_reports, count, fails) = check_files(files);
205 println!("Ran {} idempotent tests.", count);
206 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
209 // Run rustfmt on itself. This operation must be idempotent. We also check that
210 // no warnings are emitted.
213 let mut files = get_test_files(Path::new("tests"), false);
214 let bin_directories = vec![
218 "rustfmt-format-diff",
220 for dir in bin_directories {
221 let mut path = PathBuf::from("..");
223 path.push("src/main.rs");
226 let lib_directories = vec!["rustfmt-core", "rustfmt-config"];
227 for dir in lib_directories {
228 let mut path = PathBuf::from("..");
230 path.push("src/lib.rs");
234 let (reports, count, fails) = check_files(files);
235 let mut warnings = 0;
238 println!("Ran {} self tests.", count);
239 assert_eq!(fails, 0, "{} self tests failed", fails);
241 for format_report in reports {
242 println!("{}", format_report);
243 warnings += format_report.warning_count();
248 "Rustfmt's code generated {} warnings",
254 fn stdin_formatting_smoke_test() {
255 let input = Input::Text("fn main () {}".to_owned());
256 let config = Config::default();
257 let (error_summary, file_map, _report) =
258 format_input::<io::Stdout>(input, &config, None).unwrap();
259 assert!(error_summary.has_no_errors());
260 for &(ref file_name, ref text) in &file_map {
261 if let FileName::Custom(ref file_name) = *file_name {
262 if file_name == "stdin" {
263 assert_eq!(text.to_string(), "fn main() {}\n");
271 // FIXME(#1990) restore this test
273 // fn stdin_disable_all_formatting_test() {
274 // let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
275 // let mut child = Command::new("./target/debug/rustfmt")
276 // .stdin(Stdio::piped())
277 // .stdout(Stdio::piped())
278 // .arg("--config-path=./tests/config/disable_all_formatting.toml")
280 // .expect("failed to execute child");
283 // let stdin = child.stdin.as_mut().expect("failed to get stdin");
285 // .write_all(input.as_bytes())
286 // .expect("failed to write stdin");
288 // let output = child.wait_with_output().expect("failed to wait on child");
289 // assert!(output.status.success());
290 // assert!(output.stderr.is_empty());
291 // assert_eq!(input, String::from_utf8(output.stdout).unwrap());
295 fn format_lines_errors_are_reported() {
296 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
297 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
298 let config = Config::default();
299 let (error_summary, _file_map, _report) =
300 format_input::<io::Stdout>(input, &config, None).unwrap();
301 assert!(error_summary.has_formatting_errors());
305 fn format_lines_errors_are_reported_with_tabs() {
306 let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
307 let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
308 let config = Config::from_toml("hard_tabs = true").unwrap();
309 let (error_summary, _file_map, _report) =
310 format_input::<io::Stdout>(input, &config, None).unwrap();
311 assert!(error_summary.has_formatting_errors());
314 // For each file, run rustfmt and collect the output.
315 // Returns the number of files checked and the number of failures.
316 fn check_files(files: Vec<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
319 let mut reports = vec![];
321 for file_name in files {
322 debug!("Testing '{}'...", file_name.display());
324 match idempotent_check(&file_name) {
325 Ok(ref report) if report.has_warnings() => {
326 print!("{}", report);
329 Ok(report) => reports.push(report),
331 if let IdempotentCheckError::Mismatch(msg) = err {
332 print_mismatches_default_message(msg);
341 (reports, count, fails)
344 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
345 let mut t = term::stdout().unwrap();
346 for (file_name, diff) in result {
347 let mismatch_msg_formatter =
348 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
349 print_diff(diff, &mismatch_msg_formatter, Color::Auto);
355 fn print_mismatches<T: Fn(u32) -> String>(
356 result: HashMap<PathBuf, Vec<Mismatch>>,
357 mismatch_msg_formatter: T,
359 let mut t = term::stdout().unwrap();
360 for (_file_name, diff) in result {
361 print_diff(diff, &mismatch_msg_formatter, Color::Auto);
367 fn read_config(filename: &Path) -> Config {
368 let sig_comments = read_significant_comments(filename);
369 // Look for a config file... If there is a 'config' property in the significant comments, use
370 // that. Otherwise, if there are no significant comments at all, look for a config file with
371 // the same name as the test file.
372 let mut config = if !sig_comments.is_empty() {
373 get_config(sig_comments.get("config").map(Path::new))
375 get_config(filename.with_extension("toml").file_name().map(Path::new))
378 for (key, val) in &sig_comments {
379 if key != "target" && key != "config" {
380 config.override_value(key, val);
384 // Don't generate warnings for to-do items.
385 config.set().report_todo(ReportTactic::Never);
390 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (Summary, FileMap, FormatReport) {
391 let filepath = filepath.into();
392 let input = Input::File(filepath);
393 format_input::<io::Stdout>(input, config, None).unwrap()
396 pub enum IdempotentCheckError {
397 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
401 pub fn idempotent_check(filename: &PathBuf) -> Result<FormatReport, IdempotentCheckError> {
402 let sig_comments = read_significant_comments(filename);
403 let config = read_config(filename);
404 let (error_summary, file_map, format_report) = format_file(filename, &config);
405 if error_summary.has_parsing_errors() {
406 return Err(IdempotentCheckError::Parse);
409 let mut write_result = HashMap::new();
410 for &(ref filename, ref text) in &file_map {
411 let mut v = Vec::new();
412 // Won't panic, as we're not doing any IO.
413 write_system_newlines(&mut v, text, &config).unwrap();
414 // Won't panic, we are writing correct utf8.
415 let one_result = String::from_utf8(v).unwrap();
416 if let FileName::Real(ref filename) = *filename {
417 write_result.insert(filename.to_owned(), one_result);
421 let target = sig_comments.get("target").map(|x| &(*x)[..]);
423 handle_result(write_result, target).map(|_| format_report)
426 // Reads test config file using the supplied (optional) file name. If there's no file name or the
427 // file doesn't exist, just return the default config. Otherwise, the file must be read
429 fn get_config(config_file: Option<&Path>) -> Config {
430 let config_file_name = match config_file {
431 None => return Default::default(),
433 let mut full_path = PathBuf::from("tests/config/");
434 full_path.push(file_name);
435 if !full_path.exists() {
436 return Default::default();
442 let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
443 let mut def_config = String::new();
445 .read_to_string(&mut def_config)
446 .expect("Couldn't read config");
448 Config::from_toml(&def_config).expect("Invalid toml")
451 // Reads significant comments of the form: // rustfmt-key: value
453 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
455 fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name.display()));
456 let reader = BufReader::new(file);
457 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
458 let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
460 // Matches lines containing significant comments or whitespace.
461 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
462 .expect("Failed creating pattern 2");
466 .map(|line| line.expect("Failed getting line"))
467 .take_while(|line| line_regex.is_match(line))
469 regex.captures_iter(&line).next().map(|capture| {
473 .expect("Couldn't unwrap capture")
478 .expect("Couldn't unwrap capture")
487 // Compare output to input.
488 // TODO: needs a better name, more explanation.
490 result: HashMap<PathBuf, String>,
491 target: Option<&str>,
492 ) -> Result<(), IdempotentCheckError> {
493 let mut failures = HashMap::new();
495 for (file_name, fmt_text) in result {
496 // If file is in tests/source, compare to file with same name in tests/target.
497 let target = get_target(&file_name, target);
498 let open_error = format!("Couldn't open target {:?}", &target);
499 let mut f = fs::File::open(&target).expect(&open_error);
501 let mut text = String::new();
502 let read_error = format!("Failed reading target {:?}", &target);
503 f.read_to_string(&mut text).expect(&read_error);
505 // Ignore LF and CRLF difference for Windows.
506 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
507 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
510 "Empty diff? Maybe due to a missing a newline at the end of a file?"
512 failures.insert(file_name, diff);
516 if failures.is_empty() {
519 Err(IdempotentCheckError::Mismatch(failures))
523 // Map source file paths to their target paths.
524 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
525 if let Some(n) = file_name
527 .position(|c| c.as_os_str() == "source")
529 let mut target_file_name = PathBuf::new();
530 for (i, c) in file_name.components().enumerate() {
532 target_file_name.push("target");
534 target_file_name.push(c.as_os_str());
537 if let Some(replace_name) = target {
538 target_file_name.with_file_name(replace_name)
543 // This is either and idempotence check or a self check
549 fn rustfmt_diff_make_diff_tests() {
550 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
558 DiffLine::Context("a".into()),
559 DiffLine::Resulting("b".into()),
560 DiffLine::Expected("e".into()),
561 DiffLine::Context("c".into()),
562 DiffLine::Context("d".into()),
570 fn rustfmt_diff_no_diff_test() {
571 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
572 assert_eq!(diff, vec![]);
575 // Compare strings without distinguishing between CRLF and LF
576 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
577 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
578 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
582 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
584 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
586 fn next(&mut self) -> Option<char> {
587 self.0.next().map(|c| {
589 if *self.0.peek().unwrap_or(&'\0') == '\n' {
603 fn string_eq_ignore_newline_repr_test() {
604 assert!(string_eq_ignore_newline_repr("", ""));
605 assert!(!string_eq_ignore_newline_repr("", "abc"));
606 assert!(!string_eq_ignore_newline_repr("abc", ""));
607 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
608 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
609 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
612 // This enum is used to represent one of three text features in Configurations.md: a block of code
613 // with its starting line number, the name of a rustfmt configuration option, or the value of a
614 // rustfmt configuration option.
615 enum ConfigurationSection {
616 CodeBlock((String, u32)), // (String: block of code, u32: line number of code block start)
621 impl ConfigurationSection {
622 fn get_section<I: Iterator<Item = String>>(
623 file: &mut Enumerate<I>,
624 ) -> Option<ConfigurationSection> {
626 static ref CONFIG_NAME_REGEX: regex::Regex = regex::Regex::new(r"^## `([^`]+)`").expect("Failed creating configuration pattern");
627 static ref CONFIG_VALUE_REGEX: regex::Regex = regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#).expect("Failed creating configuration value pattern");
633 if line.starts_with("```rust") {
634 // Get the lines of the code block.
635 let lines: Vec<String> = file.map(|(_i, l)| l)
636 .take_while(|l| !l.starts_with("```"))
638 let block = format!("{}\n", lines.join("\n"));
640 // +1 to translate to one-based indexing
641 // +1 to get to first line of code (line after "```")
642 let start_line = (i + 2) as u32;
644 return Some(ConfigurationSection::CodeBlock((block, start_line)));
645 } else if let Some(c) = CONFIG_NAME_REGEX.captures(&line) {
646 return Some(ConfigurationSection::ConfigName(String::from(&c[1])));
647 } else if let Some(c) = CONFIG_VALUE_REGEX.captures(&line) {
648 return Some(ConfigurationSection::ConfigValue(String::from(&c[1])));
651 None => return None, // reached the end of the file
657 // This struct stores the information about code blocks in the configurations
658 // file, formats the code blocks, and prints formatting errors.
659 struct ConfigCodeBlock {
660 config_name: Option<String>,
661 config_value: Option<String>,
662 code_block: Option<String>,
663 code_block_start: Option<u32>,
666 impl ConfigCodeBlock {
667 fn new() -> ConfigCodeBlock {
672 code_block_start: None,
676 fn set_config_name(&mut self, name: Option<String>) {
677 self.config_name = name;
678 self.config_value = None;
681 fn set_config_value(&mut self, value: Option<String>) {
682 self.config_value = value;
685 fn set_code_block(&mut self, code_block: String, code_block_start: u32) {
686 self.code_block = Some(code_block);
687 self.code_block_start = Some(code_block_start);
690 fn get_block_config(&self) -> Config {
691 let mut config = Config::default();
692 if self.config_value.is_some() && self.config_value.is_some() {
693 config.override_value(
694 self.config_name.as_ref().unwrap(),
695 self.config_value.as_ref().unwrap(),
701 fn code_block_valid(&self) -> bool {
702 // We never expect to not have a code block.
703 assert!(self.code_block.is_some() && self.code_block_start.is_some());
705 // See if code block begins with #![rustfmt_skip].
706 let fmt_skip = self.code_block
711 .unwrap_or("") == "#![rustfmt_skip]";
713 if self.config_name.is_none() && !fmt_skip {
714 write_message(&format!(
715 "No configuration name for {}:{}",
716 CONFIGURATIONS_FILE_NAME,
717 self.code_block_start.unwrap()
721 if self.config_value.is_none() && !fmt_skip {
722 write_message(&format!(
723 "No configuration value for {}:{}",
724 CONFIGURATIONS_FILE_NAME,
725 self.code_block_start.unwrap()
732 fn has_parsing_errors(&self, error_summary: Summary) -> bool {
733 if error_summary.has_parsing_errors() {
734 write_message(&format!(
735 "\u{261d}\u{1f3fd} Cannot format {}:{}",
736 CONFIGURATIONS_FILE_NAME,
737 self.code_block_start.unwrap()
745 fn print_diff(&self, compare: Vec<Mismatch>) {
746 let mut mismatches = HashMap::new();
747 mismatches.insert(PathBuf::from(CONFIGURATIONS_FILE_NAME), compare);
748 print_mismatches(mismatches, |line_num| {
750 "\nMismatch at {}:{}:",
751 CONFIGURATIONS_FILE_NAME,
752 line_num + self.code_block_start.unwrap() - 1
757 fn formatted_has_diff(&self, file_map: &FileMap) -> bool {
758 let &(ref _file_name, ref text) = file_map.first().unwrap();
759 let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
760 if !compare.is_empty() {
761 self.print_diff(compare);
768 // Return a bool indicating if formatting this code block is an idempotent
769 // operation. This function also triggers printing any formatting failure
771 fn formatted_is_idempotent(&self) -> bool {
772 // Verify that we have all of the expected information.
773 if !self.code_block_valid() {
777 let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
778 let config = self.get_block_config();
780 let (error_summary, file_map, _report) =
781 format_input::<io::Stdout>(input, &config, None).unwrap();
783 !self.has_parsing_errors(error_summary) && !self.formatted_has_diff(&file_map)
786 // Extract a code block from the iterator. Behavior:
787 // - Rust code blocks are identifed by lines beginning with "```rust".
788 // - One explicit configuration setting is supported per code block.
789 // - Rust code blocks with no configuration setting are illegal and cause an
790 // assertion failure, unless the snippet begins with #![rustfmt_skip].
791 // - Configuration names in Configurations.md must be in the form of
793 // - Configuration values in Configurations.md must be in the form of
795 fn extract<I: Iterator<Item = String>>(
796 file: &mut Enumerate<I>,
797 prev: Option<&ConfigCodeBlock>,
798 ) -> Option<ConfigCodeBlock> {
799 let mut code_block = ConfigCodeBlock::new();
800 code_block.config_name = prev.and_then(|cb| cb.config_name.clone());
803 match ConfigurationSection::get_section(file) {
804 Some(ConfigurationSection::CodeBlock((block, start_line))) => {
805 code_block.set_code_block(block, start_line);
808 Some(ConfigurationSection::ConfigName(name)) => {
809 code_block.set_config_name(Some(name));
811 Some(ConfigurationSection::ConfigValue(value)) => {
812 code_block.set_config_value(Some(value));
814 None => return None, // end of file was reached
823 fn configuration_snippet_tests() {
824 // Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one
825 // entry for each Rust code block found.
826 fn get_code_blocks() -> Vec<ConfigCodeBlock> {
827 let mut file_iter = BufReader::new(
828 fs::File::open(Path::new("..").join(CONFIGURATIONS_FILE_NAME))
829 .expect(&format!("Couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
833 let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
835 while let Some(cb) = ConfigCodeBlock::extract(&mut file_iter, code_blocks.last()) {
836 code_blocks.push(cb);
842 let blocks = get_code_blocks();
843 let failures = blocks
845 .map(|b| b.formatted_is_idempotent())
846 .fold(0, |acc, r| acc + (!r as u32));
849 println!("Ran {} configurations tests.", blocks.len());
850 assert_eq!(failures, 0, "{} configurations tests failed", failures);