1 #![deny(rust_2018_idioms)]
4 extern crate derive_new;
7 extern crate lazy_static;
11 extern crate serde_derive;
13 use std::cell::RefCell;
14 use std::collections::HashMap;
16 use std::io::{self, Write};
19 use std::path::PathBuf;
23 use syntax::{ast, parse::DirectoryOwnership};
25 use crate::comment::LineClasses;
26 use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
27 use crate::issues::Issue;
28 use crate::shape::Indent;
29 use crate::utils::indent_next_line;
31 pub use crate::config::{
32 load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
36 pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
43 pub(crate) mod checkstyle;
46 pub(crate) mod config;
48 pub(crate) mod formatting;
56 pub(crate) mod modules;
62 pub(crate) mod rustfmt_diff;
64 pub(crate) mod source_file;
65 pub(crate) mod source_map;
72 pub(crate) mod visitor;
74 /// The various errors that can occur during formatting. Note that not all of
75 /// these can currently be propagated to clients.
76 #[derive(Fail, Debug)]
78 /// Line has exceeded character limit (found, maximum).
80 display = "line formatted, but exceeded maximum width \
81 (maximum: {} (see `max_width` option), found: {})",
84 LineOverflow(usize, usize),
85 /// Line ends in whitespace.
86 #[fail(display = "left behind trailing whitespace")]
88 /// TODO or FIXME item without an issue number.
89 #[fail(display = "found {}", _0)]
91 /// License check has failed.
92 #[fail(display = "license check failed")]
94 /// Used deprecated skip attribute.
95 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
97 /// Used a rustfmt:: attribute other than skip or skip::macros.
98 #[fail(display = "invalid attribute")]
100 /// An io error during reading or writing.
101 #[fail(display = "io error: {}", _0)]
103 /// Parse error occurred when parsing the input.
104 #[fail(display = "parse error")]
106 /// The user mandated a version and the current version of Rustfmt does not
107 /// satisfy that requirement.
108 #[fail(display = "version mismatch")]
110 /// If we had formatted the given node, then we would have lost a comment.
111 #[fail(display = "not formatted because a comment would be lost")]
116 fn is_comment(&self) -> bool {
118 ErrorKind::LostComment => true,
124 impl From<io::Error> for ErrorKind {
125 fn from(e: io::Error) -> ErrorKind {
126 ErrorKind::IoError(e)
130 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
131 /// i.e., that got returned as they were originally.
133 struct FormattedSnippet {
135 non_formatted_ranges: Vec<(usize, usize)>,
138 impl FormattedSnippet {
139 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
140 /// non-formatted code.
141 fn unwrap_code_block(&mut self) {
142 self.non_formatted_ranges
144 .for_each(|(low, high)| {
150 /// Returns `true` if the line n did not get formatted.
151 fn is_line_non_formatted(&self, n: usize) -> bool {
152 self.non_formatted_ranges
154 .any(|(low, high)| *low <= n && n <= *high)
158 /// Reports on any issues that occurred during a run of Rustfmt.
160 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
162 pub struct FormatReport {
163 // Maps stringified file paths to their associated formatting errors.
164 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
165 non_formatted_ranges: Vec<(usize, usize)>,
169 fn new() -> FormatReport {
171 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
172 non_formatted_ranges: Vec::new(),
176 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
177 self.non_formatted_ranges.append(&mut ranges);
180 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
181 self.track_errors(&v);
186 .and_modify(|fe| fe.append(&mut v))
190 fn track_errors(&self, new_errors: &[FormattingError]) {
191 let errs = &mut self.internal.borrow_mut().1;
192 if !new_errors.is_empty() {
193 errs.has_formatting_errors = true;
195 if errs.has_operational_errors && errs.has_check_errors {
198 for err in new_errors {
200 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
201 errs.has_operational_errors = true;
203 ErrorKind::BadIssue(_)
204 | ErrorKind::LicenseCheck
205 | ErrorKind::DeprecatedAttr
207 | ErrorKind::VersionMismatch => {
208 errs.has_check_errors = true;
215 fn add_diff(&mut self) {
216 self.internal.borrow_mut().1.has_diff = true;
219 fn add_macro_format_failure(&mut self) {
220 self.internal.borrow_mut().1.has_macro_format_failure = true;
223 fn add_parsing_error(&mut self) {
224 self.internal.borrow_mut().1.has_parsing_errors = true;
227 fn warning_count(&self) -> usize {
232 .map(|(_, errors)| errors.len())
236 /// Whether any warnings or errors are present in the report.
237 pub fn has_warnings(&self) -> bool {
238 self.internal.borrow().1.has_formatting_errors
241 /// Print the report to a terminal using colours and potentially other
245 mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
246 ) -> Result<(), term::Error> {
247 for (file, errors) in &self.internal.borrow().0 {
248 for error in errors {
249 let prefix_space_len = error.line.to_string().len();
250 let prefix_spaces = " ".repeat(1 + prefix_space_len);
252 // First line: the overview of error
253 t.fg(term::color::RED)?;
254 t.attr(term::Attr::Bold)?;
255 write!(t, "{} ", error.msg_prefix())?;
257 t.attr(term::Attr::Bold)?;
258 writeln!(t, "{}", error.kind)?;
260 // Second line: file info
261 write!(t, "{}--> ", &prefix_spaces[1..])?;
263 writeln!(t, "{}:{}", file, error.line)?;
265 // Third to fifth lines: show the line which triggered error, if available.
266 if !error.line_buffer.is_empty() {
267 let (space_len, target_len) = error.format_len();
268 t.attr(term::Attr::Bold)?;
269 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
271 writeln!(t, "{}", error.line_buffer)?;
272 t.attr(term::Attr::Bold)?;
273 write!(t, "{}| ", prefix_spaces)?;
274 t.fg(term::color::RED)?;
275 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
279 // The last line: show note if available.
280 let msg_suffix = error.msg_suffix();
281 if !msg_suffix.is_empty() {
282 t.attr(term::Attr::Bold)?;
283 write!(t, "{}= note: ", prefix_spaces)?;
285 writeln!(t, "{}", error.msg_suffix())?;
293 if !self.internal.borrow().0.is_empty() {
294 t.attr(term::Attr::Bold)?;
295 write!(t, "warning: ")?;
299 "rustfmt may have failed to format. See previous {} errors.\n\n",
300 self.warning_count(),
307 fn target_str(space_len: usize, target_len: usize) -> String {
308 let empty_line = " ".repeat(space_len);
309 let overflowed = "^".repeat(target_len);
310 empty_line + &overflowed
314 impl fmt::Display for FormatReport {
315 // Prints all the formatting errors.
316 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
317 for (file, errors) in &self.internal.borrow().0 {
318 for error in errors {
319 let prefix_space_len = error.line.to_string().len();
320 let prefix_spaces = " ".repeat(1 + prefix_space_len);
322 let error_line_buffer = if error.line_buffer.is_empty() {
325 let (space_len, target_len) = error.format_len();
327 "{}|\n{} | {}\n{}| {}",
332 FormatReport::target_str(space_len, target_len)
336 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
337 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
338 let msg_suffix = error.msg_suffix();
339 let note = if msg_suffix.is_empty() {
342 format!("{}note= ", prefix_spaces)
356 if !self.internal.borrow().0.is_empty() {
359 "warning: rustfmt may have failed to format. See previous {} errors.",
360 self.warning_count(),
367 /// Format the given snippet. The snippet is expected to be *complete* code.
368 /// When we cannot parse the given snippet, this function returns `None`.
369 fn format_snippet(snippet: &str, config: &Config) -> Option<FormattedSnippet> {
370 let mut config = config.clone();
371 panic::catch_unwind(|| {
372 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
373 config.set().emit_mode(config::EmitMode::Stdout);
374 config.set().verbose(Verbosity::Quiet);
375 config.set().hide_parse_errors(true);
377 let (formatting_error, result) = {
378 let input = Input::Text(snippet.into());
379 let mut session = Session::new(config, Some(&mut out));
380 let result = session.format(input);
382 session.errors.has_macro_format_failure
383 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
388 if formatting_error {
391 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
393 non_formatted_ranges: result.unwrap().non_formatted_ranges,
397 // Discard panics encountered while formatting the snippet
398 // The ? operator is needed to remove the extra Option
402 /// Format the given code block. Mainly targeted for code block in comment.
403 /// The code block may be incomplete (i.e., parser may be unable to parse it).
404 /// To avoid panic in parser, we wrap the code block with a dummy function.
405 /// The returned code block does **not** end with newline.
406 fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSnippet> {
407 const FN_MAIN_PREFIX: &str = "fn main() {\n";
409 fn enclose_in_main_block(s: &str, config: &Config) -> String {
410 let indent = Indent::from_width(config, config.tab_spaces());
411 let mut result = String::with_capacity(s.len() * 2);
412 result.push_str(FN_MAIN_PREFIX);
413 let mut need_indent = true;
414 for (kind, line) in LineClasses::new(s) {
416 result.push_str(&indent.to_string(config));
418 result.push_str(&line);
420 need_indent = indent_next_line(kind, &line, config);
426 // Wrap the given code block with `fn main()` if it does not have one.
427 let snippet = enclose_in_main_block(code_snippet, config);
428 let mut result = String::with_capacity(snippet.len());
429 let mut is_first = true;
431 // While formatting the code, ignore the config's newline style setting and always use "\n"
432 // instead of "\r\n" for the newline characters. This is ok because the output here is
433 // not directly outputted by rustfmt command, but used by the comment formatter's input.
434 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
435 let mut config_with_unix_newline = config.clone();
436 config_with_unix_newline
438 .newline_style(NewlineStyle::Unix);
439 let mut formatted = format_snippet(&snippet, &config_with_unix_newline)?;
440 // Remove wrapping main block
441 formatted.unwrap_code_block();
443 // Trim "fn main() {" on the first line and "}" on the last line,
444 // then unindent the whole code block.
445 let block_len = formatted
448 .unwrap_or(formatted.snippet.len());
449 let mut is_indented = true;
450 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
456 let trimmed_line = if !is_indented {
458 } else if line.len() > config.max_width() {
459 // If there are lines that are larger than max width, we cannot tell
460 // whether we have succeeded but have some comments or strings that
461 // are too long, or we have failed to format code block. We will be
462 // conservative and just return `None` in this case.
464 } else if line.len() > config.tab_spaces() {
465 // Make sure that the line has leading whitespaces.
466 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
467 if line.starts_with(indent_str.as_ref()) {
468 let offset = if config.hard_tabs() {
480 result.push_str(trimmed_line);
481 is_indented = indent_next_line(kind, line, config);
483 Some(FormattedSnippet {
485 non_formatted_ranges: formatted.non_formatted_ranges,
489 /// A session is a run of rustfmt across a single or multiple inputs.
490 pub struct Session<'b, T: Write> {
492 pub out: Option<&'b mut T>,
493 pub(crate) errors: ReportedErrors,
494 source_file: SourceFile,
497 impl<'b, T: Write + 'b> Session<'b, T> {
498 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
499 if config.emit_mode() == EmitMode::Checkstyle {
500 println!("{}", checkstyle::header());
506 errors: ReportedErrors::default(),
507 source_file: SourceFile::new(),
511 /// The main entry point for Rustfmt. Formats the given input according to the
512 /// given config. `out` is only necessary if required by the configuration.
513 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
514 self.format_input_inner(input)
517 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
519 F: FnOnce(&mut Session<'b, T>) -> U,
521 mem::swap(&mut config, &mut self.config);
522 let result = f(self);
523 mem::swap(&mut config, &mut self.config);
527 pub fn add_operational_error(&mut self) {
528 self.errors.has_operational_errors = true;
531 pub fn has_operational_errors(&self) -> bool {
532 self.errors.has_operational_errors
535 pub fn has_parsing_errors(&self) -> bool {
536 self.errors.has_parsing_errors
539 pub fn has_formatting_errors(&self) -> bool {
540 self.errors.has_formatting_errors
543 pub fn has_check_errors(&self) -> bool {
544 self.errors.has_check_errors
547 pub fn has_diff(&self) -> bool {
551 pub fn has_no_errors(&self) -> bool {
552 !(self.has_operational_errors()
553 || self.has_parsing_errors()
554 || self.has_formatting_errors()
555 || self.has_check_errors()
557 || self.errors.has_macro_format_failure
561 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
563 if self.config.emit_mode() == EmitMode::Checkstyle {
564 println!("{}", checkstyle::footer());
576 fn is_text(&self) -> bool {
578 Input::File(_) => false,
579 Input::Text(_) => true,
583 fn file_name(&self) -> FileName {
585 Input::File(ref file) => FileName::Real(file.clone()),
586 Input::Text(..) => FileName::Stdin,
590 fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
592 Input::File(ref file) => {
593 // If there exists a directory with the same name as an input,
594 // then the input should be parsed as a sub module.
595 let file_stem = file.file_stem()?;
596 if file.parent()?.to_path_buf().join(file_stem).is_dir() {
597 Some(DirectoryOwnership::Owned {
598 relative: file_stem.to_str().map(ast::Ident::from_str),
614 fn test_no_panic_on_format_snippet_and_format_code_block() {
615 // `format_snippet()` and `format_code_block()` should not panic
616 // even when we cannot parse the given snippet.
618 assert!(format_snippet(snippet, &Config::default()).is_none());
619 assert!(format_code_block(snippet, &Config::default()).is_none());
622 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
624 F: Fn(&str, &Config) -> Option<FormattedSnippet>,
626 let output = formatter(input, &Config::default());
627 output.is_some() && output.unwrap().snippet == expected
631 fn test_format_snippet() {
632 let snippet = "fn main() { println!(\"hello, world\"); }";
634 let expected = "fn main() {\n \
635 println!(\"hello, world\");\n\
638 let expected = "fn main() {\r\n \
639 println!(\"hello, world\");\r\n\
641 assert!(test_format_inner(format_snippet, snippet, expected));
645 fn test_format_code_block_fail() {
647 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
648 assert!(format_code_block(code_block, &Config::default()).is_none());
652 fn test_format_code_block() {
654 let code_block = "let x=3;";
655 let expected = "let x = 3;";
656 assert!(test_format_inner(format_code_block, code_block, expected));
658 // more complex code block, taken from chains.rs.
660 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
662 chain_indent(context, shape.add_offset(parent_rewrite.len())),
663 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
665 } else if is_block_expr(context, &parent, &parent_rewrite) {
666 match context.config.indent_style() {
667 // Try to put the first child on the same line with parent's last line
668 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
669 // The parent is a block, so align the rest of the chain with the closing
671 IndentStyle::Visual => (parent_shape, false),
675 chain_indent(context, shape.add_offset(parent_rewrite.len())),
681 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
683 chain_indent(context, shape.add_offset(parent_rewrite.len())),
684 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
686 } else if is_block_expr(context, &parent, &parent_rewrite) {
687 match context.config.indent_style() {
688 // Try to put the first child on the same line with parent's last line
689 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
690 // The parent is a block, so align the rest of the chain with the closing
692 IndentStyle::Visual => (parent_shape, false),
696 chain_indent(context, shape.add_offset(parent_rewrite.len())),
700 assert!(test_format_inner(format_code_block, code_block, expected));