1 // Copyright 2015-2018 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.
11 #![feature(custom_attribute)]
12 #![feature(decl_macro)]
13 #![feature(match_default_bindings)]
14 #![feature(type_ascription)]
17 extern crate derive_new;
22 extern crate rustc_errors as errors;
25 extern crate serde_derive;
26 extern crate serde_json;
30 extern crate unicode_segmentation;
32 use std::collections::HashMap;
34 use std::io::{self, stdout, BufRead, Write};
35 use std::iter::repeat;
36 use std::path::PathBuf;
38 use std::time::Duration;
40 use errors::{DiagnosticBuilder, Handler};
41 use errors::emitter::{ColorConfig, EmitterWriter};
43 use syntax::codemap::{CodeMap, FilePathMapping};
44 pub use syntax::codemap::FileName;
45 use syntax::parse::{self, ParseSess};
47 use checkstyle::{output_footer, output_header};
48 use comment::{CharClasses, FullCodeCharKind};
49 use issues::{BadIssueSeeker, Issue};
51 use utils::use_colored_tty;
52 use visitor::{FmtVisitor, SnippetProvider};
54 pub use config::Config;
55 pub use config::summary::Summary;
87 const STDIN: &str = "<stdin>";
89 // A map of the files of a crate, with their new content
90 pub type FileMap = Vec<FileRecord>;
92 pub type FileRecord = (FileName, String);
94 #[derive(Clone, Copy)]
96 // Line has exceeded character limit (found, maximum)
97 LineOverflow(usize, usize),
98 // Line ends in whitespace
100 // TO-DO or FIX-ME item without an issue number
104 impl fmt::Display for ErrorKind {
105 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
107 ErrorKind::LineOverflow(found, maximum) => write!(
109 "line exceeded maximum width (maximum: {}, found: {})",
112 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
113 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
118 // Formatting errors that are identified *after* rustfmt has run.
119 pub struct FormattingError {
127 impl FormattingError {
128 fn msg_prefix(&self) -> &str {
130 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "error:",
131 ErrorKind::BadIssue(_) => "WARNING:",
135 fn msg_suffix(&self) -> &str {
136 if self.is_comment || self.is_string {
137 "set `error_on_unformatted = false` to suppress \
138 the warning against comments or string literals\n"
145 pub fn format_len(&self) -> (usize, usize) {
147 ErrorKind::LineOverflow(found, max) => (max, found - max),
148 ErrorKind::TrailingWhitespace => {
149 let trailing_ws_len = self.line_buffer
152 .take_while(|c| c.is_whitespace())
154 (self.line_buffer.len() - trailing_ws_len, trailing_ws_len)
161 pub struct FormatReport {
162 // Maps stringified file paths to their associated formatting errors.
163 file_error_map: HashMap<FileName, Vec<FormattingError>>,
167 fn new() -> FormatReport {
169 file_error_map: HashMap::new(),
173 pub fn warning_count(&self) -> usize {
176 .map(|(_, errors)| errors.len())
180 pub fn has_warnings(&self) -> bool {
181 self.warning_count() > 0
184 pub fn print_warnings_fancy(
186 mut t: Box<term::Terminal<Output = io::Stderr>>,
187 ) -> Result<(), term::Error> {
188 for (file, errors) in &self.file_error_map {
189 for error in errors {
190 let prefix_space_len = error.line.to_string().len();
191 let prefix_spaces: String = repeat(" ").take(1 + prefix_space_len).collect();
193 // First line: the overview of error
194 t.fg(term::color::RED)?;
195 t.attr(term::Attr::Bold)?;
196 write!(t, "{} ", error.msg_prefix())?;
198 t.attr(term::Attr::Bold)?;
199 write!(t, "{}\n", error.kind)?;
201 // Second line: file info
202 write!(t, "{}--> ", &prefix_spaces[1..])?;
204 write!(t, "{}:{}\n", file, error.line)?;
206 // Third to fifth lines: show the line which triggered error, if available.
207 if !error.line_buffer.is_empty() {
208 let (space_len, target_len) = error.format_len();
209 t.attr(term::Attr::Bold)?;
210 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
212 write!(t, "{}\n", error.line_buffer)?;
213 t.attr(term::Attr::Bold)?;
214 write!(t, "{}| ", prefix_spaces)?;
215 t.fg(term::color::RED)?;
216 write!(t, "{}\n", target_str(space_len, target_len))?;
220 // The last line: show note if available.
221 let msg_suffix = error.msg_suffix();
222 if !msg_suffix.is_empty() {
223 t.attr(term::Attr::Bold)?;
224 write!(t, "{}= note: ", prefix_spaces)?;
226 write!(t, "{}\n", error.msg_suffix())?;
234 if !self.file_error_map.is_empty() {
235 t.attr(term::Attr::Bold)?;
236 write!(t, "warning: ")?;
240 "rustfmt may have failed to format. See previous {} errors.\n\n",
241 self.warning_count(),
249 fn target_str(space_len: usize, target_len: usize) -> String {
250 let empty_line: String = repeat(" ").take(space_len).collect();
251 let overflowed: String = repeat("^").take(target_len).collect();
252 empty_line + &overflowed
255 impl fmt::Display for FormatReport {
256 // Prints all the formatting errors.
257 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
258 for (file, errors) in &self.file_error_map {
259 for error in errors {
260 let prefix_space_len = error.line.to_string().len();
261 let prefix_spaces: String = repeat(" ").take(1 + prefix_space_len).collect();
263 let error_line_buffer = if error.line_buffer.is_empty() {
266 let (space_len, target_len) = error.format_len();
268 "{}|\n{} | {}\n{}| {}",
273 target_str(space_len, target_len)
277 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
278 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
279 let msg_suffix = error.msg_suffix();
280 let note = if msg_suffix.is_empty() {
283 format!("{}note= ", prefix_spaces)
288 "{}\n{}\n{}\n{}{}\n",
297 if !self.file_error_map.is_empty() {
300 "warning: rustfmt may have failed to format. See previous {} errors.\n",
301 self.warning_count(),
308 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
312 if config.verbose() && path.to_string() != STDIN {
317 // Formatting which depends on the AST.
320 parse_session: &mut ParseSess,
321 main_file: &FileName,
324 ) -> Result<(FileMap, bool), io::Error>
326 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
328 let mut result = FileMap::new();
329 // diff mode: check if any files are differing
330 let mut has_diff = false;
332 // We always skip children for the "Plain" write mode, since there is
333 // nothing to distinguish the nested module contents.
334 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
335 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
336 if skip_children && path != *main_file {
339 should_emit_verbose(&path, config, || println!("Formatting {}", path));
340 let filemap = parse_session
342 .lookup_char_pos(module.inner.lo())
344 let big_snippet = filemap.src.as_ref().unwrap();
345 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
346 let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
347 // Format inner attributes if available.
348 if !krate.attrs.is_empty() && path == *main_file {
349 visitor.skip_empty_lines(filemap.end_pos);
350 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
351 visitor.push_rewrite(module.inner, None);
353 visitor.format_separate_mod(module, &*filemap);
356 visitor.last_pos = filemap.start_pos;
357 visitor.skip_empty_lines(filemap.end_pos);
358 visitor.format_separate_mod(module, &*filemap);
363 ::utils::count_newlines(&format!("{}", visitor.buffer))
366 let filename = path.clone();
367 has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
368 Ok(result) => result,
370 // Create a new error with path_str to help users see which files failed
371 let err_msg = format!("{}: {}", path, e);
372 return Err(io::Error::new(e.kind(), err_msg));
376 result.push((filename, visitor.buffer));
379 Ok((result, has_diff))
382 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
383 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
386 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
389 fn should_report_error(
391 char_kind: FullCodeCharKind,
393 error_kind: ErrorKind,
395 let allow_error_report = if char_kind.is_comment() || is_string {
396 config.error_on_unformatted()
402 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
403 ErrorKind::TrailingWhitespace => allow_error_report,
408 // Formatting done on a char by char or line by line basis.
409 // FIXME(#209) warn on bad license
410 // FIXME(#20) other stuff for parity with make tidy
414 skipped_range: &[(usize, usize)],
416 report: &mut FormatReport,
418 // Iterate over the chars in the file map.
419 let mut trims = vec![];
420 let mut last_wspace: Option<usize> = None;
421 let mut line_len = 0;
422 let mut cur_line = 1;
423 let mut newline_count = 0;
424 let mut errors = vec![];
425 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
426 let mut line_buffer = String::with_capacity(config.max_width() * 2);
427 let mut is_string = false; // true if the current line contains a string literal.
428 let mut format_line = config.file_lines().contains_line(name, cur_line);
429 let allow_issue_seek = !issue_seeker.is_disabled();
431 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
436 if allow_issue_seek && format_line {
437 // Add warnings for bad todos/ fixmes
438 if let Some(issue) = issue_seeker.inspect(c) {
439 errors.push(FormattingError {
441 kind: ErrorKind::BadIssue(issue),
444 line_buffer: String::new(),
451 // Check for (and record) trailing whitespace.
452 if let Some(..) = last_wspace {
453 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
454 trims.push((cur_line, kind, line_buffer.clone()));
459 // Check for any line width errors we couldn't correct.
460 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
461 if line_len > config.max_width() && !is_skipped_line(cur_line, skipped_range)
462 && should_report_error(config, kind, is_string, error_kind)
464 errors.push(FormattingError {
467 is_comment: kind.is_comment(),
469 line_buffer: line_buffer.clone(),
476 format_line = config.file_lines().contains_line(name, cur_line);
483 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
484 if c.is_whitespace() {
485 if last_wspace.is_none() {
486 last_wspace = Some(b);
492 if kind.is_string() {
498 if newline_count > 1 {
499 debug!("track truncate: {} {}", text.len(), newline_count);
500 let line = text.len() - newline_count + 1;
504 for &(l, kind, ref b) in &trims {
505 if !is_skipped_line(l, skipped_range) {
506 errors.push(FormattingError {
508 kind: ErrorKind::TrailingWhitespace,
509 is_comment: kind.is_comment(),
510 is_string: kind.is_string(),
511 line_buffer: b.clone(),
516 report.file_error_map.insert(name.clone(), errors);
519 fn parse_input<'sess>(
521 parse_session: &'sess ParseSess,
523 ) -> Result<ast::Crate, Option<DiagnosticBuilder<'sess>>> {
524 let result = match input {
525 Input::File(file) => {
526 let mut parser = parse::new_parser_from_file(parse_session, &file);
527 parser.cfg_mods = false;
528 if config.skip_children() {
529 parser.recurse_into_file_modules = false;
531 parser.parse_crate_mod()
533 Input::Text(text) => {
534 let mut parser = parse::new_parser_from_source_str(
536 FileName::Custom("stdin".to_owned()),
539 parser.cfg_mods = false;
540 if config.skip_children() {
541 parser.recurse_into_file_modules = false;
543 parser.parse_crate_mod()
549 if parse_session.span_diagnostic.has_errors() {
550 // Bail out if the parser recovered from an error.
556 Err(e) => Err(Some(e)),
560 /// Format the given snippet. The snippet is expected to be *complete* code.
561 /// When we cannot parse the given snippet, this function returns `None`.
562 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
563 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
564 let input = Input::Text(snippet.into());
565 let mut config = config.clone();
566 config.set().write_mode(config::WriteMode::Plain);
567 config.set().hide_parse_errors(true);
568 match format_input(input, &config, Some(&mut out)) {
569 // `format_input()` returns an empty string on parsing error.
570 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
571 Ok(..) => String::from_utf8(out).ok(),
576 /// Format the given code block. Mainly targeted for code block in comment.
577 /// The code block may be incomplete (i.e. parser may be unable to parse it).
578 /// To avoid panic in parser, we wrap the code block with a dummy function.
579 /// The returned code block does *not* end with newline.
580 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
581 // Wrap the given code block with `fn main()` if it does not have one.
582 let fn_main_prefix = "fn main() {\n";
583 let snippet = fn_main_prefix.to_owned() + code_snippet + "\n}";
584 let mut result = String::with_capacity(snippet.len());
585 let mut is_first = true;
587 // Trim "fn main() {" on the first line and "}" on the last line,
588 // then unindent the whole code block.
589 let formatted = format_snippet(&snippet, config)?;
591 let block_len = formatted.len().checked_sub(2).unwrap_or(0);
592 for line in formatted[fn_main_prefix.len()..block_len].lines() {
598 let trimmed_line = if line.len() > config.max_width() {
599 // If there are lines that are larger than max width, we cannot tell
600 // whether we have succeeded but have some comments or strings that
601 // are too long, or we have failed to format code block. We will be
602 // conservative and just return `None` in this case.
604 } else if line.len() > config.tab_spaces() {
605 // Make sure that the line has leading whitespaces.
606 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
607 if line.starts_with(indent_str.as_ref()) {
608 let offset = if config.hard_tabs() {
620 result.push_str(trimmed_line);
625 pub fn format_input<T: Write>(
628 mut out: Option<&mut T>,
629 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
630 let mut summary = Summary::default();
631 if config.disable_all_formatting() {
632 // When the input is from stdin, echo back the input.
633 if let Input::Text(ref buf) = input {
634 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
635 return Err((e, summary));
638 return Ok((summary, FileMap::new(), FormatReport::new()));
640 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
642 let tty_handler = if config.hide_parse_errors() {
643 let silent_emitter = Box::new(EmitterWriter::new(
644 Box::new(Vec::new()),
645 Some(codemap.clone()),
649 Handler::with_emitter(true, false, silent_emitter)
651 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
652 let color_cfg = if supports_color {
657 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
659 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
661 let main_file = match input {
662 Input::File(ref file) => FileName::Real(file.clone()),
663 Input::Text(..) => FileName::Custom("stdin".to_owned()),
666 let krate = match parse_input(input, &parse_session, config) {
669 if let Some(mut diagnostic) = diagnostic {
672 summary.add_parsing_error();
673 return Ok((summary, FileMap::new(), FormatReport::new()));
677 summary.mark_parse_time();
679 if parse_session.span_diagnostic.has_errors() {
680 summary.add_parsing_error();
683 // Suppress error output after parsing.
684 let silent_emitter = Box::new(EmitterWriter::new(
685 Box::new(Vec::new()),
686 Some(codemap.clone()),
690 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
692 let mut report = FormatReport::new();
694 let format_result = format_ast(
699 |file_name, file, skipped_range| {
700 // For some reason, the codemap does not include terminating
701 // newlines so we must add one on for each file. This is sad.
702 filemap::append_newline(file);
704 format_lines(file, file_name, skipped_range, config, &mut report);
706 if let Some(ref mut out) = out {
707 return filemap::write_file(file, file_name, out, config);
713 summary.mark_format_time();
715 should_emit_verbose(&main_file, config, || {
716 fn duration_to_f32(d: Duration) -> f32 {
717 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
721 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
722 duration_to_f32(summary.get_parse_time().unwrap()),
723 duration_to_f32(summary.get_format_time().unwrap()),
727 match format_result {
728 Ok((file_map, has_diff)) => {
729 if report.has_warnings() {
730 summary.add_formatting_error();
737 Ok((summary, file_map, report))
739 Err(e) => Err((e, summary)),
743 /// A single span of changed lines, with 0 or more removed lines
744 /// and a vector of 0 or more inserted lines.
745 #[derive(Debug, PartialEq, Eq)]
746 pub struct ModifiedChunk {
747 /// The first to be removed from the original text
748 pub line_number_orig: u32,
749 /// The number of lines which have been replaced
750 pub lines_removed: u32,
752 pub lines: Vec<String>,
755 /// Set of changed sections of a file.
756 #[derive(Debug, PartialEq, Eq)]
757 pub struct ModifiedLines {
758 /// The set of changed chunks.
759 pub chunks: Vec<ModifiedChunk>,
762 /// The successful result of formatting via `get_modified_lines()`.
763 pub struct ModifiedLinesResult {
764 /// The high level summary details
765 pub summary: Summary,
766 /// The result Filemap
767 pub filemap: FileMap,
768 /// Map of formatting errors
769 pub report: FormatReport,
770 /// The sets of updated lines.
771 pub modified_lines: ModifiedLines,
774 /// Format a file and return a `ModifiedLines` data structure describing
775 /// the changed ranges of lines.
776 pub fn get_modified_lines(
779 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
780 let mut data = Vec::new();
782 let mut config = config.clone();
783 config.set().write_mode(config::WriteMode::Modified);
784 let (summary, filemap, formatreport) = format_input(input, &config, Some(&mut data))?;
786 let mut lines = data.lines();
787 let mut chunks = Vec::new();
788 while let Some(Ok(header)) = lines.next() {
789 // Parse the header line
790 let values: Vec<_> = header
792 .map(|s| s.parse::<u32>().unwrap())
794 assert_eq!(values.len(), 3);
795 let line_number_orig = values[0];
796 let lines_removed = values[1];
797 let num_added = values[2];
798 let mut added_lines = Vec::new();
799 for _ in 0..num_added {
800 added_lines.push(lines.next().unwrap().unwrap());
802 chunks.push(ModifiedChunk {
808 Ok(ModifiedLinesResult {
811 report: formatreport,
812 modified_lines: ModifiedLines { chunks },
822 pub fn run(input: Input, config: &Config) -> Summary {
823 let out = &mut stdout();
824 output_header(out, config.write_mode()).ok();
825 match format_input(input, config, Some(out)) {
826 Ok((summary, _, report)) => {
827 output_footer(out, config.write_mode()).ok();
829 if report.has_warnings() {
830 match term::stderr() {
832 if use_colored_tty(config.color()) && t.supports_color()
833 && t.supports_attr(term::Attr::Bold) =>
835 match report.print_warnings_fancy(term::stderr().unwrap()) {
837 Err(..) => panic!("Unable to write to stderr: {}", report),
840 _ => msg!("{}", report),
846 Err((msg, mut summary)) => {
847 msg!("Error writing files: {}", msg);
848 summary.add_operational_error();
856 use super::{format_code_block, format_snippet, Config};
859 fn test_no_panic_on_format_snippet_and_format_code_block() {
860 // `format_snippet()` and `format_code_block()` should not panic
861 // even when we cannot parse the given snippet.
863 assert!(format_snippet(snippet, &Config::default()).is_none());
864 assert!(format_code_block(snippet, &Config::default()).is_none());
867 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
869 F: Fn(&str, &Config) -> Option<String>,
871 let output = formatter(input, &Config::default());
872 output.is_some() && output.unwrap() == expected
876 fn test_format_snippet() {
877 let snippet = "fn main() { println!(\"hello, world\"); }";
878 let expected = "fn main() {\n \
879 println!(\"hello, world\");\n\
881 assert!(test_format_inner(format_snippet, snippet, expected));
885 fn test_format_code_block_fail() {
887 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
888 assert!(format_code_block(code_block, &Config::default()).is_none());
892 fn test_format_code_block() {
894 let code_block = "let x=3;";
895 let expected = "let x = 3;";
896 assert!(test_format_inner(format_code_block, code_block, expected));
898 // more complex code block, taken from chains.rs.
900 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
902 chain_indent(context, shape.add_offset(parent_rewrite.len())),
903 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
905 } else if is_block_expr(context, &parent, &parent_rewrite) {
906 match context.config.indent_style() {
907 // Try to put the first child on the same line with parent's last line
908 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
909 // The parent is a block, so align the rest of the chain with the closing
911 IndentStyle::Visual => (parent_shape, false),
915 chain_indent(context, shape.add_offset(parent_rewrite.len())),
921 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
923 chain_indent(context, shape.add_offset(parent_rewrite.len())),
924 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
926 } else if is_block_expr(context, &parent, &parent_rewrite) {
927 match context.config.indent_style() {
928 // Try to put the first child on the same line with parent's last line
929 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
930 // The parent is a block, so align the rest of the chain with the closing
932 IndentStyle::Visual => (parent_shape, false),
936 chain_indent(context, shape.add_offset(parent_rewrite.len())),
940 assert!(test_format_inner(format_code_block, code_block, expected));