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;
14 extern crate bytecount;
17 extern crate itertools;
20 extern crate lazy_static;
24 extern crate rustc_target;
27 extern crate serde_derive;
28 extern crate serde_json;
30 extern crate syntax_pos;
32 extern crate unicode_segmentation;
34 use std::cell::RefCell;
35 use std::collections::HashMap;
37 use std::io::{self, Write};
40 use std::path::PathBuf;
44 use comment::LineClasses;
46 use formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
51 load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
60 pub(crate) mod checkstyle;
63 pub(crate) mod config;
65 pub(crate) mod formatting;
73 pub(crate) mod modules;
79 pub(crate) mod rustfmt_diff;
81 pub(crate) mod source_file;
82 pub(crate) mod source_map;
89 pub(crate) mod visitor;
91 /// The various errors that can occur during formatting. Note that not all of
92 /// these can currently be propagated to clients.
93 #[derive(Fail, Debug)]
95 /// Line has exceeded character limit (found, maximum).
97 display = "line formatted, but exceeded maximum width \
98 (maximum: {} (see `max_width` option), found: {})",
101 LineOverflow(usize, usize),
102 /// Line ends in whitespace.
103 #[fail(display = "left behind trailing whitespace")]
105 /// TODO or FIXME item without an issue number.
106 #[fail(display = "found {}", _0)]
108 /// License check has failed.
109 #[fail(display = "license check failed")]
111 /// Used deprecated skip attribute.
112 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
114 /// Used a rustfmt:: attribute other than skip.
115 #[fail(display = "invalid attribute")]
117 /// An io error during reading or writing.
118 #[fail(display = "io error: {}", _0)]
120 /// Parse error occurred when parsing the input.
121 #[fail(display = "parse error")]
123 /// The user mandated a version and the current version of Rustfmt does not
124 /// satisfy that requirement.
125 #[fail(display = "version mismatch")]
127 /// If we had formatted the given node, then we would have lost a comment.
128 #[fail(display = "not formatted because a comment would be lost")]
133 fn is_comment(&self) -> bool {
135 ErrorKind::LostComment => true,
141 impl From<io::Error> for ErrorKind {
142 fn from(e: io::Error) -> ErrorKind {
143 ErrorKind::IoError(e)
147 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
148 /// i.e., that got returned as they were originally.
150 struct FormattedSnippet {
152 non_formatted_ranges: Vec<(usize, usize)>,
155 impl FormattedSnippet {
156 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
157 /// non-formatted code.
158 fn unwrap_code_block(&mut self) {
159 self.non_formatted_ranges
161 .for_each(|(low, high)| {
167 /// Returns true if the line n did not get formatted.
168 fn is_line_non_formatted(&self, n: usize) -> bool {
169 self.non_formatted_ranges
171 .any(|(low, high)| *low <= n && n <= *high)
175 /// Reports on any issues that occurred during a run of Rustfmt.
177 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
179 pub struct FormatReport {
180 // Maps stringified file paths to their associated formatting errors.
181 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
182 non_formatted_ranges: Vec<(usize, usize)>,
186 fn new() -> FormatReport {
188 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
189 non_formatted_ranges: Vec::new(),
193 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
194 self.non_formatted_ranges.append(&mut ranges);
197 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
198 self.track_errors(&v);
203 .and_modify(|fe| fe.append(&mut v))
207 fn track_errors(&self, new_errors: &[FormattingError]) {
208 let errs = &mut self.internal.borrow_mut().1;
209 if !new_errors.is_empty() {
210 errs.has_formatting_errors = true;
212 if errs.has_operational_errors && errs.has_check_errors {
215 for err in new_errors {
217 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
218 errs.has_operational_errors = true;
220 ErrorKind::BadIssue(_)
221 | ErrorKind::LicenseCheck
222 | ErrorKind::DeprecatedAttr
224 | ErrorKind::VersionMismatch => {
225 errs.has_check_errors = true;
232 fn add_diff(&mut self) {
233 self.internal.borrow_mut().1.has_diff = true;
236 fn add_macro_format_failure(&mut self) {
237 self.internal.borrow_mut().1.has_macro_format_failure = true;
240 fn add_parsing_error(&mut self) {
241 self.internal.borrow_mut().1.has_parsing_errors = true;
244 fn warning_count(&self) -> usize {
249 .map(|(_, errors)| errors.len())
253 /// Whether any warnings or errors are present in the report.
254 pub fn has_warnings(&self) -> bool {
255 self.internal.borrow().1.has_formatting_errors
258 /// Print the report to a terminal using colours and potentially other
262 mut t: Box<term::Terminal<Output = io::Stderr>>,
263 ) -> Result<(), term::Error> {
264 for (file, errors) in &self.internal.borrow().0 {
265 for error in errors {
266 let prefix_space_len = error.line.to_string().len();
267 let prefix_spaces = " ".repeat(1 + prefix_space_len);
269 // First line: the overview of error
270 t.fg(term::color::RED)?;
271 t.attr(term::Attr::Bold)?;
272 write!(t, "{} ", error.msg_prefix())?;
274 t.attr(term::Attr::Bold)?;
275 writeln!(t, "{}", error.kind)?;
277 // Second line: file info
278 write!(t, "{}--> ", &prefix_spaces[1..])?;
280 writeln!(t, "{}:{}", file, error.line)?;
282 // Third to fifth lines: show the line which triggered error, if available.
283 if !error.line_buffer.is_empty() {
284 let (space_len, target_len) = error.format_len();
285 t.attr(term::Attr::Bold)?;
286 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
288 writeln!(t, "{}", error.line_buffer)?;
289 t.attr(term::Attr::Bold)?;
290 write!(t, "{}| ", prefix_spaces)?;
291 t.fg(term::color::RED)?;
292 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
296 // The last line: show note if available.
297 let msg_suffix = error.msg_suffix();
298 if !msg_suffix.is_empty() {
299 t.attr(term::Attr::Bold)?;
300 write!(t, "{}= note: ", prefix_spaces)?;
302 writeln!(t, "{}", error.msg_suffix())?;
310 if !self.internal.borrow().0.is_empty() {
311 t.attr(term::Attr::Bold)?;
312 write!(t, "warning: ")?;
316 "rustfmt may have failed to format. See previous {} errors.\n\n",
317 self.warning_count(),
324 fn target_str(space_len: usize, target_len: usize) -> String {
325 let empty_line = " ".repeat(space_len);
326 let overflowed = "^".repeat(target_len);
327 empty_line + &overflowed
331 impl fmt::Display for FormatReport {
332 // Prints all the formatting errors.
333 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
334 for (file, errors) in &self.internal.borrow().0 {
335 for error in errors {
336 let prefix_space_len = error.line.to_string().len();
337 let prefix_spaces = " ".repeat(1 + prefix_space_len);
339 let error_line_buffer = if error.line_buffer.is_empty() {
342 let (space_len, target_len) = error.format_len();
344 "{}|\n{} | {}\n{}| {}",
349 FormatReport::target_str(space_len, target_len)
353 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
354 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
355 let msg_suffix = error.msg_suffix();
356 let note = if msg_suffix.is_empty() {
359 format!("{}note= ", prefix_spaces)
373 if !self.internal.borrow().0.is_empty() {
376 "warning: rustfmt may have failed to format. See previous {} errors.",
377 self.warning_count(),
384 /// Format the given snippet. The snippet is expected to be *complete* code.
385 /// When we cannot parse the given snippet, this function returns `None`.
386 fn format_snippet(snippet: &str, config: &Config) -> Option<FormattedSnippet> {
387 let mut config = config.clone();
388 panic::catch_unwind(|| {
389 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
390 config.set().emit_mode(config::EmitMode::Stdout);
391 config.set().verbose(Verbosity::Quiet);
392 config.set().hide_parse_errors(true);
394 let (formatting_error, result) = {
395 let input = Input::Text(snippet.into());
396 let mut session = Session::new(config, Some(&mut out));
397 let result = session.format(input);
399 session.errors.has_macro_format_failure
400 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
405 if formatting_error {
408 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
410 non_formatted_ranges: result.unwrap().non_formatted_ranges,
414 // Discard panics encountered while formatting the snippet
415 // The ? operator is needed to remove the extra Option
419 /// Format the given code block. Mainly targeted for code block in comment.
420 /// The code block may be incomplete (i.e. parser may be unable to parse it).
421 /// To avoid panic in parser, we wrap the code block with a dummy function.
422 /// The returned code block does *not* end with newline.
423 fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSnippet> {
424 const FN_MAIN_PREFIX: &str = "fn main() {\n";
426 fn enclose_in_main_block(s: &str, config: &Config) -> String {
427 let indent = Indent::from_width(config, config.tab_spaces());
428 let mut result = String::with_capacity(s.len() * 2);
429 result.push_str(FN_MAIN_PREFIX);
430 let mut need_indent = true;
431 for (kind, line) in LineClasses::new(s) {
433 result.push_str(&indent.to_string(config));
435 result.push_str(&line);
437 need_indent = !kind.is_string() || line.ends_with('\\');
443 // Wrap the given code block with `fn main()` if it does not have one.
444 let snippet = enclose_in_main_block(code_snippet, config);
445 let mut result = String::with_capacity(snippet.len());
446 let mut is_first = true;
448 // While formatting the code, ignore the config's newline style setting and always use "\n"
449 // instead of "\r\n" for the newline characters. This is okay because the output here is
450 // not directly outputted by rustfmt command, but used by the comment formatter's input.
451 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
452 let mut config_with_unix_newline = config.clone();
453 config_with_unix_newline
455 .newline_style(NewlineStyle::Unix);
456 let mut formatted = format_snippet(&snippet, &config_with_unix_newline)?;
457 // Remove wrapping main block
458 formatted.unwrap_code_block();
460 // Trim "fn main() {" on the first line and "}" on the last line,
461 // then unindent the whole code block.
462 let block_len = formatted
465 .unwrap_or(formatted.snippet.len());
466 let mut is_indented = true;
467 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
473 let trimmed_line = if !is_indented {
475 } else if line.len() > config.max_width() {
476 // If there are lines that are larger than max width, we cannot tell
477 // whether we have succeeded but have some comments or strings that
478 // are too long, or we have failed to format code block. We will be
479 // conservative and just return `None` in this case.
481 } else if line.len() > config.tab_spaces() {
482 // Make sure that the line has leading whitespaces.
483 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
484 if line.starts_with(indent_str.as_ref()) {
485 let offset = if config.hard_tabs() {
497 result.push_str(trimmed_line);
498 is_indented = !kind.is_string() || line.ends_with('\\');
500 Some(FormattedSnippet {
502 non_formatted_ranges: formatted.non_formatted_ranges,
506 /// A session is a run of rustfmt across a single or multiple inputs.
507 pub struct Session<'b, T: Write + 'b> {
509 pub out: Option<&'b mut T>,
510 pub(crate) errors: ReportedErrors,
511 source_file: SourceFile,
514 impl<'b, T: Write + 'b> Session<'b, T> {
515 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
516 if config.emit_mode() == EmitMode::Checkstyle {
517 println!("{}", checkstyle::header());
523 errors: ReportedErrors::default(),
524 source_file: SourceFile::new(),
528 /// The main entry point for Rustfmt. Formats the given input according to the
529 /// given config. `out` is only necessary if required by the configuration.
530 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
531 self.format_input_inner(input)
534 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
536 F: FnOnce(&mut Session<'b, T>) -> U,
538 mem::swap(&mut config, &mut self.config);
539 let result = f(self);
540 mem::swap(&mut config, &mut self.config);
544 pub fn add_operational_error(&mut self) {
545 self.errors.has_operational_errors = true;
548 pub fn has_operational_errors(&self) -> bool {
549 self.errors.has_operational_errors
552 pub fn has_parsing_errors(&self) -> bool {
553 self.errors.has_parsing_errors
556 pub fn has_formatting_errors(&self) -> bool {
557 self.errors.has_formatting_errors
560 pub fn has_check_errors(&self) -> bool {
561 self.errors.has_check_errors
564 pub fn has_diff(&self) -> bool {
568 pub fn has_no_errors(&self) -> bool {
569 !(self.has_operational_errors()
570 || self.has_parsing_errors()
571 || self.has_formatting_errors()
572 || self.has_check_errors()
574 || self.errors.has_macro_format_failure
578 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
580 if self.config.emit_mode() == EmitMode::Checkstyle {
581 println!("{}", checkstyle::footer());
593 fn is_text(&self) -> bool {
595 Input::File(_) => false,
596 Input::Text(_) => true,
600 fn file_name(&self) -> FileName {
602 Input::File(ref file) => FileName::Real(file.clone()),
603 Input::Text(..) => FileName::Stdin,
613 fn test_no_panic_on_format_snippet_and_format_code_block() {
614 // `format_snippet()` and `format_code_block()` should not panic
615 // even when we cannot parse the given snippet.
617 assert!(format_snippet(snippet, &Config::default()).is_none());
618 assert!(format_code_block(snippet, &Config::default()).is_none());
621 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
623 F: Fn(&str, &Config) -> Option<FormattedSnippet>,
625 let output = formatter(input, &Config::default());
626 output.is_some() && output.unwrap().snippet == expected
630 fn test_format_snippet() {
631 let snippet = "fn main() { println!(\"hello, world\"); }";
633 let expected = "fn main() {\n \
634 println!(\"hello, world\");\n\
637 let expected = "fn main() {\r\n \
638 println!(\"hello, world\");\r\n\
640 assert!(test_format_inner(format_snippet, snippet, expected));
644 fn test_format_code_block_fail() {
646 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
647 assert!(format_code_block(code_block, &Config::default()).is_none());
651 fn test_format_code_block() {
653 let code_block = "let x=3;";
654 let expected = "let x = 3;";
655 assert!(test_format_inner(format_code_block, code_block, expected));
657 // more complex code block, taken from chains.rs.
659 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
661 chain_indent(context, shape.add_offset(parent_rewrite.len())),
662 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
664 } else if is_block_expr(context, &parent, &parent_rewrite) {
665 match context.config.indent_style() {
666 // Try to put the first child on the same line with parent's last line
667 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
668 // The parent is a block, so align the rest of the chain with the closing
670 IndentStyle::Visual => (parent_shape, false),
674 chain_indent(context, shape.add_offset(parent_rewrite.len())),
680 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
682 chain_indent(context, shape.add_offset(parent_rewrite.len())),
683 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
685 } else if is_block_expr(context, &parent, &parent_rewrite) {
686 match context.config.indent_style() {
687 // Try to put the first child on the same line with parent's last line
688 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
689 // The parent is a block, so align the rest of the chain with the closing
691 IndentStyle::Visual => (parent_shape, false),
695 chain_indent(context, shape.add_offset(parent_rewrite.len())),
699 assert!(test_format_inner(format_code_block, code_block, expected));