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;
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,
41 pub(crate) mod checkstyle;
44 pub(crate) mod config;
46 pub(crate) mod formatting;
54 pub(crate) mod modules;
60 pub(crate) mod rustfmt_diff;
62 pub(crate) mod source_file;
63 pub(crate) mod source_map;
70 pub(crate) mod visitor;
72 /// The various errors that can occur during formatting. Note that not all of
73 /// these can currently be propagated to clients.
74 #[derive(Fail, Debug)]
76 /// Line has exceeded character limit (found, maximum).
78 display = "line formatted, but exceeded maximum width \
79 (maximum: {} (see `max_width` option), found: {})",
82 LineOverflow(usize, usize),
83 /// Line ends in whitespace.
84 #[fail(display = "left behind trailing whitespace")]
86 /// TODO or FIXME item without an issue number.
87 #[fail(display = "found {}", _0)]
89 /// License check has failed.
90 #[fail(display = "license check failed")]
92 /// Used deprecated skip attribute.
93 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
95 /// Used a rustfmt:: attribute other than skip.
96 #[fail(display = "invalid attribute")]
98 /// An io error during reading or writing.
99 #[fail(display = "io error: {}", _0)]
101 /// Parse error occurred when parsing the input.
102 #[fail(display = "parse error")]
104 /// The user mandated a version and the current version of Rustfmt does not
105 /// satisfy that requirement.
106 #[fail(display = "version mismatch")]
108 /// If we had formatted the given node, then we would have lost a comment.
109 #[fail(display = "not formatted because a comment would be lost")]
114 fn is_comment(&self) -> bool {
116 ErrorKind::LostComment => true,
122 impl From<io::Error> for ErrorKind {
123 fn from(e: io::Error) -> ErrorKind {
124 ErrorKind::IoError(e)
128 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
129 /// i.e., that got returned as they were originally.
131 struct FormattedSnippet {
133 non_formatted_ranges: Vec<(usize, usize)>,
136 impl FormattedSnippet {
137 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
138 /// non-formatted code.
139 fn unwrap_code_block(&mut self) {
140 self.non_formatted_ranges
142 .for_each(|(low, high)| {
148 /// Returns `true` if the line n did not get formatted.
149 fn is_line_non_formatted(&self, n: usize) -> bool {
150 self.non_formatted_ranges
152 .any(|(low, high)| *low <= n && n <= *high)
156 /// Reports on any issues that occurred during a run of Rustfmt.
158 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
160 pub struct FormatReport {
161 // Maps stringified file paths to their associated formatting errors.
162 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
163 non_formatted_ranges: Vec<(usize, usize)>,
167 fn new() -> FormatReport {
169 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
170 non_formatted_ranges: Vec::new(),
174 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
175 self.non_formatted_ranges.append(&mut ranges);
178 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
179 self.track_errors(&v);
184 .and_modify(|fe| fe.append(&mut v))
188 fn track_errors(&self, new_errors: &[FormattingError]) {
189 let errs = &mut self.internal.borrow_mut().1;
190 if !new_errors.is_empty() {
191 errs.has_formatting_errors = true;
193 if errs.has_operational_errors && errs.has_check_errors {
196 for err in new_errors {
198 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
199 errs.has_operational_errors = true;
201 ErrorKind::BadIssue(_)
202 | ErrorKind::LicenseCheck
203 | ErrorKind::DeprecatedAttr
205 | ErrorKind::VersionMismatch => {
206 errs.has_check_errors = true;
213 fn add_diff(&mut self) {
214 self.internal.borrow_mut().1.has_diff = true;
217 fn add_macro_format_failure(&mut self) {
218 self.internal.borrow_mut().1.has_macro_format_failure = true;
221 fn add_parsing_error(&mut self) {
222 self.internal.borrow_mut().1.has_parsing_errors = true;
225 fn warning_count(&self) -> usize {
230 .map(|(_, errors)| errors.len())
234 /// Whether any warnings or errors are present in the report.
235 pub fn has_warnings(&self) -> bool {
236 self.internal.borrow().1.has_formatting_errors
239 /// Print the report to a terminal using colours and potentially other
243 mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
244 ) -> Result<(), term::Error> {
245 for (file, errors) in &self.internal.borrow().0 {
246 for error in errors {
247 let prefix_space_len = error.line.to_string().len();
248 let prefix_spaces = " ".repeat(1 + prefix_space_len);
250 // First line: the overview of error
251 t.fg(term::color::RED)?;
252 t.attr(term::Attr::Bold)?;
253 write!(t, "{} ", error.msg_prefix())?;
255 t.attr(term::Attr::Bold)?;
256 writeln!(t, "{}", error.kind)?;
258 // Second line: file info
259 write!(t, "{}--> ", &prefix_spaces[1..])?;
261 writeln!(t, "{}:{}", file, error.line)?;
263 // Third to fifth lines: show the line which triggered error, if available.
264 if !error.line_buffer.is_empty() {
265 let (space_len, target_len) = error.format_len();
266 t.attr(term::Attr::Bold)?;
267 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
269 writeln!(t, "{}", error.line_buffer)?;
270 t.attr(term::Attr::Bold)?;
271 write!(t, "{}| ", prefix_spaces)?;
272 t.fg(term::color::RED)?;
273 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
277 // The last line: show note if available.
278 let msg_suffix = error.msg_suffix();
279 if !msg_suffix.is_empty() {
280 t.attr(term::Attr::Bold)?;
281 write!(t, "{}= note: ", prefix_spaces)?;
283 writeln!(t, "{}", error.msg_suffix())?;
291 if !self.internal.borrow().0.is_empty() {
292 t.attr(term::Attr::Bold)?;
293 write!(t, "warning: ")?;
297 "rustfmt may have failed to format. See previous {} errors.\n\n",
298 self.warning_count(),
305 fn target_str(space_len: usize, target_len: usize) -> String {
306 let empty_line = " ".repeat(space_len);
307 let overflowed = "^".repeat(target_len);
308 empty_line + &overflowed
312 impl fmt::Display for FormatReport {
313 // Prints all the formatting errors.
314 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
315 for (file, errors) in &self.internal.borrow().0 {
316 for error in errors {
317 let prefix_space_len = error.line.to_string().len();
318 let prefix_spaces = " ".repeat(1 + prefix_space_len);
320 let error_line_buffer = if error.line_buffer.is_empty() {
323 let (space_len, target_len) = error.format_len();
325 "{}|\n{} | {}\n{}| {}",
330 FormatReport::target_str(space_len, target_len)
334 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
335 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
336 let msg_suffix = error.msg_suffix();
337 let note = if msg_suffix.is_empty() {
340 format!("{}note= ", prefix_spaces)
354 if !self.internal.borrow().0.is_empty() {
357 "warning: rustfmt may have failed to format. See previous {} errors.",
358 self.warning_count(),
365 /// Format the given snippet. The snippet is expected to be *complete* code.
366 /// When we cannot parse the given snippet, this function returns `None`.
367 fn format_snippet(snippet: &str, config: &Config) -> Option<FormattedSnippet> {
368 let mut config = config.clone();
369 panic::catch_unwind(|| {
370 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
371 config.set().emit_mode(config::EmitMode::Stdout);
372 config.set().verbose(Verbosity::Quiet);
373 config.set().hide_parse_errors(true);
375 let (formatting_error, result) = {
376 let input = Input::Text(snippet.into());
377 let mut session = Session::new(config, Some(&mut out));
378 let result = session.format(input);
380 session.errors.has_macro_format_failure
381 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
386 if formatting_error {
389 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
391 non_formatted_ranges: result.unwrap().non_formatted_ranges,
395 // Discard panics encountered while formatting the snippet
396 // The ? operator is needed to remove the extra Option
400 /// Format the given code block. Mainly targeted for code block in comment.
401 /// The code block may be incomplete (i.e., parser may be unable to parse it).
402 /// To avoid panic in parser, we wrap the code block with a dummy function.
403 /// The returned code block does **not** end with newline.
404 fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSnippet> {
405 const FN_MAIN_PREFIX: &str = "fn main() {\n";
407 fn enclose_in_main_block(s: &str, config: &Config) -> String {
408 let indent = Indent::from_width(config, config.tab_spaces());
409 let mut result = String::with_capacity(s.len() * 2);
410 result.push_str(FN_MAIN_PREFIX);
411 let mut need_indent = true;
412 for (kind, line) in LineClasses::new(s) {
414 result.push_str(&indent.to_string(config));
416 result.push_str(&line);
418 need_indent = indent_next_line(kind, &line, config);
424 // Wrap the given code block with `fn main()` if it does not have one.
425 let snippet = enclose_in_main_block(code_snippet, config);
426 let mut result = String::with_capacity(snippet.len());
427 let mut is_first = true;
429 // While formatting the code, ignore the config's newline style setting and always use "\n"
430 // instead of "\r\n" for the newline characters. This is ok because the output here is
431 // not directly outputted by rustfmt command, but used by the comment formatter's input.
432 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
433 let mut config_with_unix_newline = config.clone();
434 config_with_unix_newline
436 .newline_style(NewlineStyle::Unix);
437 let mut formatted = format_snippet(&snippet, &config_with_unix_newline)?;
438 // Remove wrapping main block
439 formatted.unwrap_code_block();
441 // Trim "fn main() {" on the first line and "}" on the last line,
442 // then unindent the whole code block.
443 let block_len = formatted
446 .unwrap_or(formatted.snippet.len());
447 let mut is_indented = true;
448 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
454 let trimmed_line = if !is_indented {
456 } else if line.len() > config.max_width() {
457 // If there are lines that are larger than max width, we cannot tell
458 // whether we have succeeded but have some comments or strings that
459 // are too long, or we have failed to format code block. We will be
460 // conservative and just return `None` in this case.
462 } else if line.len() > config.tab_spaces() {
463 // Make sure that the line has leading whitespaces.
464 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
465 if line.starts_with(indent_str.as_ref()) {
466 let offset = if config.hard_tabs() {
478 result.push_str(trimmed_line);
479 is_indented = indent_next_line(kind, line, config);
481 Some(FormattedSnippet {
483 non_formatted_ranges: formatted.non_formatted_ranges,
487 /// A session is a run of rustfmt across a single or multiple inputs.
488 pub struct Session<'b, T: Write> {
490 pub out: Option<&'b mut T>,
491 pub(crate) errors: ReportedErrors,
492 source_file: SourceFile,
495 impl<'b, T: Write + 'b> Session<'b, T> {
496 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
497 if config.emit_mode() == EmitMode::Checkstyle {
498 println!("{}", checkstyle::header());
504 errors: ReportedErrors::default(),
505 source_file: SourceFile::new(),
509 /// The main entry point for Rustfmt. Formats the given input according to the
510 /// given config. `out` is only necessary if required by the configuration.
511 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
512 self.format_input_inner(input)
515 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
517 F: FnOnce(&mut Session<'b, T>) -> U,
519 mem::swap(&mut config, &mut self.config);
520 let result = f(self);
521 mem::swap(&mut config, &mut self.config);
525 pub fn add_operational_error(&mut self) {
526 self.errors.has_operational_errors = true;
529 pub fn has_operational_errors(&self) -> bool {
530 self.errors.has_operational_errors
533 pub fn has_parsing_errors(&self) -> bool {
534 self.errors.has_parsing_errors
537 pub fn has_formatting_errors(&self) -> bool {
538 self.errors.has_formatting_errors
541 pub fn has_check_errors(&self) -> bool {
542 self.errors.has_check_errors
545 pub fn has_diff(&self) -> bool {
549 pub fn has_no_errors(&self) -> bool {
550 !(self.has_operational_errors()
551 || self.has_parsing_errors()
552 || self.has_formatting_errors()
553 || self.has_check_errors()
555 || self.errors.has_macro_format_failure
559 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
561 if self.config.emit_mode() == EmitMode::Checkstyle {
562 println!("{}", checkstyle::footer());
574 fn is_text(&self) -> bool {
576 Input::File(_) => false,
577 Input::Text(_) => true,
581 fn file_name(&self) -> FileName {
583 Input::File(ref file) => FileName::Real(file.clone()),
584 Input::Text(..) => FileName::Stdin,
594 fn test_no_panic_on_format_snippet_and_format_code_block() {
595 // `format_snippet()` and `format_code_block()` should not panic
596 // even when we cannot parse the given snippet.
598 assert!(format_snippet(snippet, &Config::default()).is_none());
599 assert!(format_code_block(snippet, &Config::default()).is_none());
602 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
604 F: Fn(&str, &Config) -> Option<FormattedSnippet>,
606 let output = formatter(input, &Config::default());
607 output.is_some() && output.unwrap().snippet == expected
611 fn test_format_snippet() {
612 let snippet = "fn main() { println!(\"hello, world\"); }";
614 let expected = "fn main() {\n \
615 println!(\"hello, world\");\n\
618 let expected = "fn main() {\r\n \
619 println!(\"hello, world\");\r\n\
621 assert!(test_format_inner(format_snippet, snippet, expected));
625 fn test_format_code_block_fail() {
627 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
628 assert!(format_code_block(code_block, &Config::default()).is_none());
632 fn test_format_code_block() {
634 let code_block = "let x=3;";
635 let expected = "let x = 3;";
636 assert!(test_format_inner(format_code_block, code_block, expected));
638 // more complex code block, taken from chains.rs.
640 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
642 chain_indent(context, shape.add_offset(parent_rewrite.len())),
643 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
645 } else if is_block_expr(context, &parent, &parent_rewrite) {
646 match context.config.indent_style() {
647 // Try to put the first child on the same line with parent's last line
648 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
649 // The parent is a block, so align the rest of the chain with the closing
651 IndentStyle::Visual => (parent_shape, false),
655 chain_indent(context, shape.add_offset(parent_rewrite.len())),
661 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
663 chain_indent(context, shape.add_offset(parent_rewrite.len())),
664 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
666 } else if is_block_expr(context, &parent, &parent_rewrite) {
667 match context.config.indent_style() {
668 // Try to put the first child on the same line with parent's last line
669 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
670 // The parent is a block, so align the rest of the chain with the closing
672 IndentStyle::Visual => (parent_shape, false),
676 chain_indent(context, shape.add_offset(parent_rewrite.len())),
680 assert!(test_format_inner(format_code_block, code_block, expected));