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.
12 extern crate derive_new;
15 extern crate lazy_static;
19 extern crate serde_derive;
21 use std::cell::RefCell;
22 use std::collections::HashMap;
24 use std::io::{self, Write};
27 use std::path::PathBuf;
33 use crate::comment::LineClasses;
34 use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
35 use crate::issues::Issue;
36 use crate::shape::Indent;
38 pub use crate::config::{
39 load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
48 pub(crate) mod checkstyle;
51 pub(crate) mod config;
53 pub(crate) mod formatting;
61 pub(crate) mod modules;
67 pub(crate) mod rustfmt_diff;
69 pub(crate) mod source_file;
70 pub(crate) mod source_map;
77 pub(crate) mod visitor;
79 /// The various errors that can occur during formatting. Note that not all of
80 /// these can currently be propagated to clients.
81 #[derive(Fail, Debug)]
83 /// Line has exceeded character limit (found, maximum).
85 display = "line formatted, but exceeded maximum width \
86 (maximum: {} (see `max_width` option), found: {})",
89 LineOverflow(usize, usize),
90 /// Line ends in whitespace.
91 #[fail(display = "left behind trailing whitespace")]
93 /// TODO or FIXME item without an issue number.
94 #[fail(display = "found {}", _0)]
96 /// License check has failed.
97 #[fail(display = "license check failed")]
99 /// Used deprecated skip attribute.
100 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
102 /// Used a rustfmt:: attribute other than skip.
103 #[fail(display = "invalid attribute")]
105 /// An io error during reading or writing.
106 #[fail(display = "io error: {}", _0)]
108 /// Parse error occurred when parsing the input.
109 #[fail(display = "parse error")]
111 /// The user mandated a version and the current version of Rustfmt does not
112 /// satisfy that requirement.
113 #[fail(display = "version mismatch")]
115 /// If we had formatted the given node, then we would have lost a comment.
116 #[fail(display = "not formatted because a comment would be lost")]
121 fn is_comment(&self) -> bool {
123 ErrorKind::LostComment => true,
129 impl From<io::Error> for ErrorKind {
130 fn from(e: io::Error) -> ErrorKind {
131 ErrorKind::IoError(e)
135 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
136 /// i.e., that got returned as they were originally.
138 struct FormattedSnippet {
140 non_formatted_ranges: Vec<(usize, usize)>,
143 impl FormattedSnippet {
144 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
145 /// non-formatted code.
146 fn unwrap_code_block(&mut self) {
147 self.non_formatted_ranges
149 .for_each(|(low, high)| {
155 /// Returns true if the line n did not get formatted.
156 fn is_line_non_formatted(&self, n: usize) -> bool {
157 self.non_formatted_ranges
159 .any(|(low, high)| *low <= n && n <= *high)
163 /// Reports on any issues that occurred during a run of Rustfmt.
165 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
167 pub struct FormatReport {
168 // Maps stringified file paths to their associated formatting errors.
169 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
170 non_formatted_ranges: Vec<(usize, usize)>,
174 fn new() -> FormatReport {
176 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
177 non_formatted_ranges: Vec::new(),
181 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
182 self.non_formatted_ranges.append(&mut ranges);
185 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
186 self.track_errors(&v);
191 .and_modify(|fe| fe.append(&mut v))
195 fn track_errors(&self, new_errors: &[FormattingError]) {
196 let errs = &mut self.internal.borrow_mut().1;
197 if !new_errors.is_empty() {
198 errs.has_formatting_errors = true;
200 if errs.has_operational_errors && errs.has_check_errors {
203 for err in new_errors {
205 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
206 errs.has_operational_errors = true;
208 ErrorKind::BadIssue(_)
209 | ErrorKind::LicenseCheck
210 | ErrorKind::DeprecatedAttr
212 | ErrorKind::VersionMismatch => {
213 errs.has_check_errors = true;
220 fn add_diff(&mut self) {
221 self.internal.borrow_mut().1.has_diff = true;
224 fn add_macro_format_failure(&mut self) {
225 self.internal.borrow_mut().1.has_macro_format_failure = true;
228 fn add_parsing_error(&mut self) {
229 self.internal.borrow_mut().1.has_parsing_errors = true;
232 fn warning_count(&self) -> usize {
237 .map(|(_, errors)| errors.len())
241 /// Whether any warnings or errors are present in the report.
242 pub fn has_warnings(&self) -> bool {
243 self.internal.borrow().1.has_formatting_errors
246 /// Print the report to a terminal using colours and potentially other
250 mut t: Box<term::Terminal<Output = io::Stderr>>,
251 ) -> Result<(), term::Error> {
252 for (file, errors) in &self.internal.borrow().0 {
253 for error in errors {
254 let prefix_space_len = error.line.to_string().len();
255 let prefix_spaces = " ".repeat(1 + prefix_space_len);
257 // First line: the overview of error
258 t.fg(term::color::RED)?;
259 t.attr(term::Attr::Bold)?;
260 write!(t, "{} ", error.msg_prefix())?;
262 t.attr(term::Attr::Bold)?;
263 writeln!(t, "{}", error.kind)?;
265 // Second line: file info
266 write!(t, "{}--> ", &prefix_spaces[1..])?;
268 writeln!(t, "{}:{}", file, error.line)?;
270 // Third to fifth lines: show the line which triggered error, if available.
271 if !error.line_buffer.is_empty() {
272 let (space_len, target_len) = error.format_len();
273 t.attr(term::Attr::Bold)?;
274 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
276 writeln!(t, "{}", error.line_buffer)?;
277 t.attr(term::Attr::Bold)?;
278 write!(t, "{}| ", prefix_spaces)?;
279 t.fg(term::color::RED)?;
280 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
284 // The last line: show note if available.
285 let msg_suffix = error.msg_suffix();
286 if !msg_suffix.is_empty() {
287 t.attr(term::Attr::Bold)?;
288 write!(t, "{}= note: ", prefix_spaces)?;
290 writeln!(t, "{}", error.msg_suffix())?;
298 if !self.internal.borrow().0.is_empty() {
299 t.attr(term::Attr::Bold)?;
300 write!(t, "warning: ")?;
304 "rustfmt may have failed to format. See previous {} errors.\n\n",
305 self.warning_count(),
312 fn target_str(space_len: usize, target_len: usize) -> String {
313 let empty_line = " ".repeat(space_len);
314 let overflowed = "^".repeat(target_len);
315 empty_line + &overflowed
319 impl fmt::Display for FormatReport {
320 // Prints all the formatting errors.
321 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
322 for (file, errors) in &self.internal.borrow().0 {
323 for error in errors {
324 let prefix_space_len = error.line.to_string().len();
325 let prefix_spaces = " ".repeat(1 + prefix_space_len);
327 let error_line_buffer = if error.line_buffer.is_empty() {
330 let (space_len, target_len) = error.format_len();
332 "{}|\n{} | {}\n{}| {}",
337 FormatReport::target_str(space_len, target_len)
341 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
342 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
343 let msg_suffix = error.msg_suffix();
344 let note = if msg_suffix.is_empty() {
347 format!("{}note= ", prefix_spaces)
361 if !self.internal.borrow().0.is_empty() {
364 "warning: rustfmt may have failed to format. See previous {} errors.",
365 self.warning_count(),
372 /// Format the given snippet. The snippet is expected to be *complete* code.
373 /// When we cannot parse the given snippet, this function returns `None`.
374 fn format_snippet(snippet: &str, config: &Config) -> Option<FormattedSnippet> {
375 let mut config = config.clone();
376 panic::catch_unwind(|| {
377 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
378 config.set().emit_mode(config::EmitMode::Stdout);
379 config.set().verbose(Verbosity::Quiet);
380 config.set().hide_parse_errors(true);
382 let (formatting_error, result) = {
383 let input = Input::Text(snippet.into());
384 let mut session = Session::new(config, Some(&mut out));
385 let result = session.format(input);
387 session.errors.has_macro_format_failure
388 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
393 if formatting_error {
396 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
398 non_formatted_ranges: result.unwrap().non_formatted_ranges,
402 // Discard panics encountered while formatting the snippet
403 // The ? operator is needed to remove the extra Option
407 /// Format the given code block. Mainly targeted for code block in comment.
408 /// The code block may be incomplete (i.e. parser may be unable to parse it).
409 /// To avoid panic in parser, we wrap the code block with a dummy function.
410 /// The returned code block does *not* end with newline.
411 fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSnippet> {
412 const FN_MAIN_PREFIX: &str = "fn main() {\n";
414 fn enclose_in_main_block(s: &str, config: &Config) -> String {
415 let indent = Indent::from_width(config, config.tab_spaces());
416 let mut result = String::with_capacity(s.len() * 2);
417 result.push_str(FN_MAIN_PREFIX);
418 let mut need_indent = true;
419 for (kind, line) in LineClasses::new(s) {
421 result.push_str(&indent.to_string(config));
423 result.push_str(&line);
425 need_indent = !kind.is_string() || line.ends_with('\\');
431 // Wrap the given code block with `fn main()` if it does not have one.
432 let snippet = enclose_in_main_block(code_snippet, config);
433 let mut result = String::with_capacity(snippet.len());
434 let mut is_first = true;
436 // While formatting the code, ignore the config's newline style setting and always use "\n"
437 // instead of "\r\n" for the newline characters. This is okay because the output here is
438 // not directly outputted by rustfmt command, but used by the comment formatter's input.
439 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
440 let mut config_with_unix_newline = config.clone();
441 config_with_unix_newline
443 .newline_style(NewlineStyle::Unix);
444 let mut formatted = format_snippet(&snippet, &config_with_unix_newline)?;
445 // Remove wrapping main block
446 formatted.unwrap_code_block();
448 // Trim "fn main() {" on the first line and "}" on the last line,
449 // then unindent the whole code block.
450 let block_len = formatted
453 .unwrap_or(formatted.snippet.len());
454 let mut is_indented = true;
455 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
461 let trimmed_line = if !is_indented {
463 } else if line.len() > config.max_width() {
464 // If there are lines that are larger than max width, we cannot tell
465 // whether we have succeeded but have some comments or strings that
466 // are too long, or we have failed to format code block. We will be
467 // conservative and just return `None` in this case.
469 } else if line.len() > config.tab_spaces() {
470 // Make sure that the line has leading whitespaces.
471 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
472 if line.starts_with(indent_str.as_ref()) {
473 let offset = if config.hard_tabs() {
485 result.push_str(trimmed_line);
486 is_indented = !kind.is_string() || line.ends_with('\\');
488 Some(FormattedSnippet {
490 non_formatted_ranges: formatted.non_formatted_ranges,
494 /// A session is a run of rustfmt across a single or multiple inputs.
495 pub struct Session<'b, T: Write + 'b> {
497 pub out: Option<&'b mut T>,
498 pub(crate) errors: ReportedErrors,
499 source_file: SourceFile,
502 impl<'b, T: Write + 'b> Session<'b, T> {
503 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
504 if config.emit_mode() == EmitMode::Checkstyle {
505 println!("{}", checkstyle::header());
511 errors: ReportedErrors::default(),
512 source_file: SourceFile::new(),
516 /// The main entry point for Rustfmt. Formats the given input according to the
517 /// given config. `out` is only necessary if required by the configuration.
518 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
519 self.format_input_inner(input)
522 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
524 F: FnOnce(&mut Session<'b, T>) -> U,
526 mem::swap(&mut config, &mut self.config);
527 let result = f(self);
528 mem::swap(&mut config, &mut self.config);
532 pub fn add_operational_error(&mut self) {
533 self.errors.has_operational_errors = true;
536 pub fn has_operational_errors(&self) -> bool {
537 self.errors.has_operational_errors
540 pub fn has_parsing_errors(&self) -> bool {
541 self.errors.has_parsing_errors
544 pub fn has_formatting_errors(&self) -> bool {
545 self.errors.has_formatting_errors
548 pub fn has_check_errors(&self) -> bool {
549 self.errors.has_check_errors
552 pub fn has_diff(&self) -> bool {
556 pub fn has_no_errors(&self) -> bool {
557 !(self.has_operational_errors()
558 || self.has_parsing_errors()
559 || self.has_formatting_errors()
560 || self.has_check_errors()
562 || self.errors.has_macro_format_failure
566 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
568 if self.config.emit_mode() == EmitMode::Checkstyle {
569 println!("{}", checkstyle::footer());
581 fn is_text(&self) -> bool {
583 Input::File(_) => false,
584 Input::Text(_) => true,
588 fn file_name(&self) -> FileName {
590 Input::File(ref file) => FileName::Real(file.clone()),
591 Input::Text(..) => FileName::Stdin,
601 fn test_no_panic_on_format_snippet_and_format_code_block() {
602 // `format_snippet()` and `format_code_block()` should not panic
603 // even when we cannot parse the given snippet.
605 assert!(format_snippet(snippet, &Config::default()).is_none());
606 assert!(format_code_block(snippet, &Config::default()).is_none());
609 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
611 F: Fn(&str, &Config) -> Option<FormattedSnippet>,
613 let output = formatter(input, &Config::default());
614 output.is_some() && output.unwrap().snippet == expected
618 fn test_format_snippet() {
619 let snippet = "fn main() { println!(\"hello, world\"); }";
621 let expected = "fn main() {\n \
622 println!(\"hello, world\");\n\
625 let expected = "fn main() {\r\n \
626 println!(\"hello, world\");\r\n\
628 assert!(test_format_inner(format_snippet, snippet, expected));
632 fn test_format_code_block_fail() {
634 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
635 assert!(format_code_block(code_block, &Config::default()).is_none());
639 fn test_format_code_block() {
641 let code_block = "let x=3;";
642 let expected = "let x = 3;";
643 assert!(test_format_inner(format_code_block, code_block, expected));
645 // more complex code block, taken from chains.rs.
647 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
649 chain_indent(context, shape.add_offset(parent_rewrite.len())),
650 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
652 } else if is_block_expr(context, &parent, &parent_rewrite) {
653 match context.config.indent_style() {
654 // Try to put the first child on the same line with parent's last line
655 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
656 // The parent is a block, so align the rest of the chain with the closing
658 IndentStyle::Visual => (parent_shape, false),
662 chain_indent(context, shape.add_offset(parent_rewrite.len())),
668 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
670 chain_indent(context, shape.add_offset(parent_rewrite.len())),
671 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
673 } else if is_block_expr(context, &parent, &parent_rewrite) {
674 match context.config.indent_style() {
675 // Try to put the first child on the same line with parent's last line
676 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
677 // The parent is a block, so align the rest of the chain with the closing
679 IndentStyle::Visual => (parent_shape, false),
683 chain_indent(context, shape.add_offset(parent_rewrite.len())),
687 assert!(test_format_inner(format_code_block, code_block, expected));