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(decl_macro)]
12 #![allow(unused_attributes)]
13 #![feature(type_ascription)]
14 #![feature(unicode_internals)]
18 extern crate derive_new;
22 extern crate itertools;
25 extern crate lazy_static;
29 extern crate rustc_target;
32 extern crate serde_derive;
33 extern crate serde_json;
35 extern crate syntax_pos;
37 extern crate unicode_segmentation;
39 use std::cell::RefCell;
40 use std::collections::HashMap;
42 use std::io::{self, Write};
44 use std::path::PathBuf;
48 use comment::LineClasses;
50 use formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
55 load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, NewlineStyle, Range,
64 pub(crate) mod checkstyle;
67 pub(crate) mod config;
69 pub(crate) mod formatting;
77 pub(crate) mod modules;
83 pub(crate) mod rustfmt_diff;
85 pub(crate) mod source_file;
86 pub(crate) mod source_map;
93 pub(crate) mod visitor;
95 /// The various errors that can occur during formatting. Note that not all of
96 /// these can currently be propagated to clients.
97 #[derive(Fail, Debug)]
99 /// Line has exceeded character limit (found, maximum).
101 display = "line formatted, but exceeded maximum width \
102 (maximum: {} (see `max_width` option), found: {})",
105 LineOverflow(usize, usize),
106 /// Line ends in whitespace.
107 #[fail(display = "left behind trailing whitespace")]
109 /// TODO or FIXME item without an issue number.
110 #[fail(display = "found {}", _0)]
112 /// License check has failed.
113 #[fail(display = "license check failed")]
115 /// Used deprecated skip attribute.
116 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
118 /// Used a rustfmt:: attribute other than skip.
119 #[fail(display = "invalid attribute")]
121 /// An io error during reading or writing.
122 #[fail(display = "io error: {}", _0)]
124 /// Parse error occured when parsing the Input.
125 #[fail(display = "parse error")]
127 /// The user mandated a version and the current version of Rustfmt does not
128 /// satisfy that requirement.
129 #[fail(display = "version mismatch")]
131 /// If we had formatted the given node, then we would have lost a comment.
132 #[fail(display = "not formatted because a comment would be lost")]
137 fn is_comment(&self) -> bool {
139 ErrorKind::LostComment => true,
145 impl From<io::Error> for ErrorKind {
146 fn from(e: io::Error) -> ErrorKind {
147 ErrorKind::IoError(e)
151 /// Reports on any issues that occurred during a run of Rustfmt.
153 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
155 pub struct FormatReport {
156 // Maps stringified file paths to their associated formatting errors.
157 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
161 fn new() -> FormatReport {
163 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
167 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
168 self.track_errors(&v);
173 .and_modify(|fe| fe.append(&mut v))
177 fn track_errors(&self, new_errors: &[FormattingError]) {
178 let errs = &mut self.internal.borrow_mut().1;
179 if !new_errors.is_empty() {
180 errs.has_formatting_errors = true;
182 if errs.has_operational_errors && errs.has_check_errors {
185 for err in new_errors {
187 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
188 errs.has_operational_errors = true;
190 ErrorKind::BadIssue(_)
191 | ErrorKind::LicenseCheck
192 | ErrorKind::DeprecatedAttr
194 | ErrorKind::VersionMismatch => {
195 errs.has_check_errors = true;
202 fn add_diff(&mut self) {
203 self.internal.borrow_mut().1.has_diff = true;
206 fn add_macro_format_failure(&mut self) {
207 self.internal.borrow_mut().1.has_macro_format_failure = true;
210 fn add_parsing_error(&mut self) {
211 self.internal.borrow_mut().1.has_parsing_errors = true;
214 fn warning_count(&self) -> usize {
219 .map(|(_, errors)| errors.len())
223 /// Whether any warnings or errors are present in the report.
224 pub fn has_warnings(&self) -> bool {
225 self.internal.borrow().1.has_formatting_errors
228 /// Print the report to a terminal using colours and potentially other
232 mut t: Box<term::Terminal<Output = io::Stderr>>,
233 ) -> Result<(), term::Error> {
234 for (file, errors) in &self.internal.borrow().0 {
235 for error in errors {
236 let prefix_space_len = error.line.to_string().len();
237 let prefix_spaces = " ".repeat(1 + prefix_space_len);
239 // First line: the overview of error
240 t.fg(term::color::RED)?;
241 t.attr(term::Attr::Bold)?;
242 write!(t, "{} ", error.msg_prefix())?;
244 t.attr(term::Attr::Bold)?;
245 writeln!(t, "{}", error.kind)?;
247 // Second line: file info
248 write!(t, "{}--> ", &prefix_spaces[1..])?;
250 writeln!(t, "{}:{}", file, error.line)?;
252 // Third to fifth lines: show the line which triggered error, if available.
253 if !error.line_buffer.is_empty() {
254 let (space_len, target_len) = error.format_len();
255 t.attr(term::Attr::Bold)?;
256 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
258 writeln!(t, "{}", error.line_buffer)?;
259 t.attr(term::Attr::Bold)?;
260 write!(t, "{}| ", prefix_spaces)?;
261 t.fg(term::color::RED)?;
262 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
266 // The last line: show note if available.
267 let msg_suffix = error.msg_suffix();
268 if !msg_suffix.is_empty() {
269 t.attr(term::Attr::Bold)?;
270 write!(t, "{}= note: ", prefix_spaces)?;
272 writeln!(t, "{}", error.msg_suffix())?;
280 if !self.internal.borrow().0.is_empty() {
281 t.attr(term::Attr::Bold)?;
282 write!(t, "warning: ")?;
286 "rustfmt may have failed to format. See previous {} errors.\n\n",
287 self.warning_count(),
294 fn target_str(space_len: usize, target_len: usize) -> String {
295 let empty_line = " ".repeat(space_len);
296 let overflowed = "^".repeat(target_len);
297 empty_line + &overflowed
301 impl fmt::Display for FormatReport {
302 // Prints all the formatting errors.
303 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
304 for (file, errors) in &self.internal.borrow().0 {
305 for error in errors {
306 let prefix_space_len = error.line.to_string().len();
307 let prefix_spaces = " ".repeat(1 + prefix_space_len);
309 let error_line_buffer = if error.line_buffer.is_empty() {
312 let (space_len, target_len) = error.format_len();
314 "{}|\n{} | {}\n{}| {}",
319 FormatReport::target_str(space_len, target_len)
323 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
324 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
325 let msg_suffix = error.msg_suffix();
326 let note = if msg_suffix.is_empty() {
329 format!("{}note= ", prefix_spaces)
343 if !self.internal.borrow().0.is_empty() {
346 "warning: rustfmt may have failed to format. See previous {} errors.",
347 self.warning_count(),
354 /// Format the given snippet. The snippet is expected to be *complete* code.
355 /// When we cannot parse the given snippet, this function returns `None`.
356 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
357 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
358 let input = Input::Text(snippet.into());
359 let mut config = config.clone();
360 config.set().emit_mode(config::EmitMode::Stdout);
361 config.set().verbose(Verbosity::Quiet);
362 config.set().hide_parse_errors(true);
364 let mut session = Session::new(config, Some(&mut out));
365 let result = session.format(input);
366 let formatting_error = session.errors.has_macro_format_failure
367 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty();
368 if formatting_error || result.is_err() {
372 String::from_utf8(out).ok()
375 /// Format the given code block. Mainly targeted for code block in comment.
376 /// The code block may be incomplete (i.e. parser may be unable to parse it).
377 /// To avoid panic in parser, we wrap the code block with a dummy function.
378 /// The returned code block does *not* end with newline.
379 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
380 const FN_MAIN_PREFIX: &str = "fn main() {\n";
382 fn enclose_in_main_block(s: &str, config: &Config) -> String {
383 let indent = Indent::from_width(config, config.tab_spaces());
384 let mut result = String::with_capacity(s.len() * 2);
385 result.push_str(FN_MAIN_PREFIX);
386 let mut need_indent = true;
387 for (kind, line) in LineClasses::new(s) {
389 result.push_str(&indent.to_string(config));
391 result.push_str(&line);
393 need_indent = !kind.is_string() || line.ends_with('\\');
399 // Wrap the given code block with `fn main()` if it does not have one.
400 let snippet = enclose_in_main_block(code_snippet, config);
401 let mut result = String::with_capacity(snippet.len());
402 let mut is_first = true;
404 // While formatting the code, ignore the config's newline style setting and always use "\n"
405 // instead of "\r\n" for the newline characters. This is okay because the output here is
406 // not directly outputted by rustfmt command, but used by the comment formatter's input.
407 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
408 let mut config_with_unix_newline = config.clone();
409 config_with_unix_newline
411 .newline_style(NewlineStyle::Unix);
412 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
414 // Trim "fn main() {" on the first line and "}" on the last line,
415 // then unindent the whole code block.
416 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
417 let mut is_indented = true;
418 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
424 let trimmed_line = if !is_indented {
426 } else if line.len() > config.max_width() {
427 // If there are lines that are larger than max width, we cannot tell
428 // whether we have succeeded but have some comments or strings that
429 // are too long, or we have failed to format code block. We will be
430 // conservative and just return `None` in this case.
432 } else if line.len() > config.tab_spaces() {
433 // Make sure that the line has leading whitespaces.
434 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
435 if line.starts_with(indent_str.as_ref()) {
436 let offset = if config.hard_tabs() {
448 result.push_str(trimmed_line);
449 is_indented = !kind.is_string() || line.ends_with('\\');
454 /// A session is a run of rustfmt across a single or multiple inputs.
455 pub struct Session<'b, T: Write + 'b> {
457 pub out: Option<&'b mut T>,
458 pub(crate) errors: ReportedErrors,
459 source_file: SourceFile,
462 impl<'b, T: Write + 'b> Session<'b, T> {
463 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
464 if config.emit_mode() == EmitMode::Checkstyle {
465 println!("{}", checkstyle::header());
471 errors: ReportedErrors::default(),
472 source_file: SourceFile::new(),
476 /// The main entry point for Rustfmt. Formats the given input according to the
477 /// given config. `out` is only necessary if required by the configuration.
478 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
479 self.format_input_inner(input)
482 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
484 F: FnOnce(&mut Session<'b, T>) -> U,
486 mem::swap(&mut config, &mut self.config);
487 let result = f(self);
488 mem::swap(&mut config, &mut self.config);
492 pub fn add_operational_error(&mut self) {
493 self.errors.has_operational_errors = true;
496 pub fn has_operational_errors(&self) -> bool {
497 self.errors.has_operational_errors
500 pub fn has_parsing_errors(&self) -> bool {
501 self.errors.has_parsing_errors
504 pub fn has_formatting_errors(&self) -> bool {
505 self.errors.has_formatting_errors
508 pub fn has_check_errors(&self) -> bool {
509 self.errors.has_check_errors
512 pub fn has_diff(&self) -> bool {
516 pub fn has_no_errors(&self) -> bool {
517 !(self.has_operational_errors()
518 || self.has_parsing_errors()
519 || self.has_formatting_errors()
520 || self.has_check_errors()
522 || self.errors.has_macro_format_failure
526 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
528 if self.config.emit_mode() == EmitMode::Checkstyle {
529 println!("{}", checkstyle::footer());
541 fn is_text(&self) -> bool {
543 Input::File(_) => false,
544 Input::Text(_) => true,
548 fn file_name(&self) -> FileName {
550 Input::File(ref file) => FileName::Real(file.clone()),
551 Input::Text(..) => FileName::Stdin,
561 fn test_no_panic_on_format_snippet_and_format_code_block() {
562 // `format_snippet()` and `format_code_block()` should not panic
563 // even when we cannot parse the given snippet.
565 assert!(format_snippet(snippet, &Config::default()).is_none());
566 assert!(format_code_block(snippet, &Config::default()).is_none());
569 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
571 F: Fn(&str, &Config) -> Option<String>,
573 let output = formatter(input, &Config::default());
574 output.is_some() && output.unwrap() == expected
578 fn test_format_snippet() {
579 let snippet = "fn main() { println!(\"hello, world\"); }";
581 let expected = "fn main() {\n \
582 println!(\"hello, world\");\n\
585 let expected = "fn main() {\r\n \
586 println!(\"hello, world\");\r\n\
588 assert!(test_format_inner(format_snippet, snippet, expected));
592 fn test_format_code_block_fail() {
594 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
595 assert!(format_code_block(code_block, &Config::default()).is_none());
599 fn test_format_code_block() {
601 let code_block = "let x=3;";
602 let expected = "let x = 3;";
603 assert!(test_format_inner(format_code_block, code_block, expected));
605 // more complex code block, taken from chains.rs.
607 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
609 chain_indent(context, shape.add_offset(parent_rewrite.len())),
610 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
612 } else if is_block_expr(context, &parent, &parent_rewrite) {
613 match context.config.indent_style() {
614 // Try to put the first child on the same line with parent's last line
615 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
616 // The parent is a block, so align the rest of the chain with the closing
618 IndentStyle::Visual => (parent_shape, false),
622 chain_indent(context, shape.add_offset(parent_rewrite.len())),
628 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
630 chain_indent(context, shape.add_offset(parent_rewrite.len())),
631 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
633 } else if is_block_expr(context, &parent, &parent_rewrite) {
634 match context.config.indent_style() {
635 // Try to put the first child on the same line with parent's last line
636 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
637 // The parent is a block, so align the rest of the chain with the closing
639 IndentStyle::Visual => (parent_shape, false),
643 chain_indent(context, shape.add_offset(parent_rewrite.len())),
647 assert!(test_format_inner(format_code_block, code_block, expected));