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)]
15 #![feature(extern_prelude)]
19 extern crate derive_new;
23 extern crate itertools;
26 extern crate lazy_static;
30 extern crate rustc_target;
33 extern crate serde_derive;
34 extern crate serde_json;
36 extern crate syntax_pos;
38 extern crate unicode_segmentation;
40 use std::cell::RefCell;
41 use std::collections::HashMap;
43 use std::io::{self, Write};
45 use std::path::PathBuf;
49 use comment::LineClasses;
51 use formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
56 load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, NewlineStyle, Range,
65 pub(crate) mod checkstyle;
68 pub(crate) mod config;
70 pub(crate) mod formatting;
78 pub(crate) mod modules;
84 pub(crate) mod rustfmt_diff;
86 pub(crate) mod source_file;
87 pub(crate) mod source_map;
94 pub(crate) mod visitor;
96 /// The various errors that can occur during formatting. Note that not all of
97 /// these can currently be propagated to clients.
98 #[derive(Fail, Debug)]
100 /// Line has exceeded character limit (found, maximum).
102 display = "line formatted, but exceeded maximum width \
103 (maximum: {} (see `max_width` option), found: {})",
107 LineOverflow(usize, usize),
108 /// Line ends in whitespace.
109 #[fail(display = "left behind trailing whitespace")]
111 /// TODO or FIXME item without an issue number.
112 #[fail(display = "found {}", _0)]
114 /// License check has failed.
115 #[fail(display = "license check failed")]
117 /// Used deprecated skip attribute.
118 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
120 /// Used a rustfmt:: attribute other than skip.
121 #[fail(display = "invalid attribute")]
123 /// An io error during reading or writing.
124 #[fail(display = "io error: {}", _0)]
126 /// Parse error occured when parsing the Input.
127 #[fail(display = "parse error")]
129 /// The user mandated a version and the current version of Rustfmt does not
130 /// satisfy that requirement.
131 #[fail(display = "version mismatch")]
133 /// If we had formatted the given node, then we would have lost a comment.
134 #[fail(display = "not formatted because a comment would be lost")]
139 fn is_comment(&self) -> bool {
141 ErrorKind::LostComment => true,
147 impl From<io::Error> for ErrorKind {
148 fn from(e: io::Error) -> ErrorKind {
149 ErrorKind::IoError(e)
153 /// Reports on any issues that occurred during a run of Rustfmt.
155 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
157 pub struct FormatReport {
158 // Maps stringified file paths to their associated formatting errors.
159 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
163 fn new() -> FormatReport {
165 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
169 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
170 self.track_errors(&v);
175 .and_modify(|fe| fe.append(&mut v))
179 fn track_errors(&self, new_errors: &[FormattingError]) {
180 let errs = &mut self.internal.borrow_mut().1;
181 if !new_errors.is_empty() {
182 errs.has_formatting_errors = true;
184 if errs.has_operational_errors && errs.has_check_errors {
187 for err in new_errors {
189 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
190 errs.has_operational_errors = true;
192 ErrorKind::BadIssue(_)
193 | ErrorKind::LicenseCheck
194 | ErrorKind::DeprecatedAttr
196 | ErrorKind::VersionMismatch => {
197 errs.has_check_errors = true;
204 fn add_diff(&mut self) {
205 self.internal.borrow_mut().1.has_diff = true;
208 fn add_macro_format_failure(&mut self) {
209 self.internal.borrow_mut().1.has_macro_format_failure = true;
212 fn add_parsing_error(&mut self) {
213 self.internal.borrow_mut().1.has_parsing_errors = true;
216 fn warning_count(&self) -> usize {
221 .map(|(_, errors)| errors.len())
225 /// Whether any warnings or errors are present in the report.
226 pub fn has_warnings(&self) -> bool {
227 self.internal.borrow().1.has_formatting_errors
230 /// Print the report to a terminal using colours and potentially other
234 mut t: Box<term::Terminal<Output = io::Stderr>>,
235 ) -> Result<(), term::Error> {
236 for (file, errors) in &self.internal.borrow().0 {
237 for error in errors {
238 let prefix_space_len = error.line.to_string().len();
239 let prefix_spaces = " ".repeat(1 + prefix_space_len);
241 // First line: the overview of error
242 t.fg(term::color::RED)?;
243 t.attr(term::Attr::Bold)?;
244 write!(t, "{} ", error.msg_prefix())?;
246 t.attr(term::Attr::Bold)?;
247 writeln!(t, "{}", error.kind)?;
249 // Second line: file info
250 write!(t, "{}--> ", &prefix_spaces[1..])?;
252 writeln!(t, "{}:{}", file, error.line)?;
254 // Third to fifth lines: show the line which triggered error, if available.
255 if !error.line_buffer.is_empty() {
256 let (space_len, target_len) = error.format_len();
257 t.attr(term::Attr::Bold)?;
258 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
260 writeln!(t, "{}", error.line_buffer)?;
261 t.attr(term::Attr::Bold)?;
262 write!(t, "{}| ", prefix_spaces)?;
263 t.fg(term::color::RED)?;
264 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
268 // The last line: show note if available.
269 let msg_suffix = error.msg_suffix();
270 if !msg_suffix.is_empty() {
271 t.attr(term::Attr::Bold)?;
272 write!(t, "{}= note: ", prefix_spaces)?;
274 writeln!(t, "{}", error.msg_suffix())?;
282 if !self.internal.borrow().0.is_empty() {
283 t.attr(term::Attr::Bold)?;
284 write!(t, "warning: ")?;
288 "rustfmt may have failed to format. See previous {} errors.\n\n",
289 self.warning_count(),
296 fn target_str(space_len: usize, target_len: usize) -> String {
297 let empty_line = " ".repeat(space_len);
298 let overflowed = "^".repeat(target_len);
299 empty_line + &overflowed
303 impl fmt::Display for FormatReport {
304 // Prints all the formatting errors.
305 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
306 for (file, errors) in &self.internal.borrow().0 {
307 for error in errors {
308 let prefix_space_len = error.line.to_string().len();
309 let prefix_spaces = " ".repeat(1 + prefix_space_len);
311 let error_line_buffer = if error.line_buffer.is_empty() {
314 let (space_len, target_len) = error.format_len();
316 "{}|\n{} | {}\n{}| {}",
321 FormatReport::target_str(space_len, target_len)
325 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
326 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
327 let msg_suffix = error.msg_suffix();
328 let note = if msg_suffix.is_empty() {
331 format!("{}note= ", prefix_spaces)
345 if !self.internal.borrow().0.is_empty() {
348 "warning: rustfmt may have failed to format. See previous {} errors.",
349 self.warning_count(),
356 /// Format the given snippet. The snippet is expected to be *complete* code.
357 /// When we cannot parse the given snippet, this function returns `None`.
358 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
359 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
360 let input = Input::Text(snippet.into());
361 let mut config = config.clone();
362 config.set().emit_mode(config::EmitMode::Stdout);
363 config.set().verbose(Verbosity::Quiet);
364 config.set().hide_parse_errors(true);
366 let mut session = Session::new(config, Some(&mut out));
367 let result = session.format(input);
368 let formatting_error = session.errors.has_macro_format_failure
369 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty();
370 if formatting_error || result.is_err() {
374 String::from_utf8(out).ok()
377 /// Format the given code block. Mainly targeted for code block in comment.
378 /// The code block may be incomplete (i.e. parser may be unable to parse it).
379 /// To avoid panic in parser, we wrap the code block with a dummy function.
380 /// The returned code block does *not* end with newline.
381 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
382 const FN_MAIN_PREFIX: &str = "fn main() {\n";
384 fn enclose_in_main_block(s: &str, config: &Config) -> String {
385 let indent = Indent::from_width(config, config.tab_spaces());
386 let mut result = String::with_capacity(s.len() * 2);
387 result.push_str(FN_MAIN_PREFIX);
388 let mut need_indent = true;
389 for (kind, line) in LineClasses::new(s) {
391 result.push_str(&indent.to_string(config));
393 result.push_str(&line);
395 need_indent = !kind.is_string() || line.ends_with('\\');
401 // Wrap the given code block with `fn main()` if it does not have one.
402 let snippet = enclose_in_main_block(code_snippet, config);
403 let mut result = String::with_capacity(snippet.len());
404 let mut is_first = true;
406 // While formatting the code, ignore the config's newline style setting and always use "\n"
407 // instead of "\r\n" for the newline characters. This is okay because the output here is
408 // not directly outputted by rustfmt command, but used by the comment formatter's input.
409 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
410 let mut config_with_unix_newline = config.clone();
411 config_with_unix_newline
413 .newline_style(NewlineStyle::Unix);
414 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
416 // Trim "fn main() {" on the first line and "}" on the last line,
417 // then unindent the whole code block.
418 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
419 let mut is_indented = true;
420 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
426 let trimmed_line = if !is_indented {
428 } else if line.len() > config.max_width() {
429 // If there are lines that are larger than max width, we cannot tell
430 // whether we have succeeded but have some comments or strings that
431 // are too long, or we have failed to format code block. We will be
432 // conservative and just return `None` in this case.
434 } else if line.len() > config.tab_spaces() {
435 // Make sure that the line has leading whitespaces.
436 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
437 if line.starts_with(indent_str.as_ref()) {
438 let offset = if config.hard_tabs() {
450 result.push_str(trimmed_line);
451 is_indented = !kind.is_string() || line.ends_with('\\');
456 /// A session is a run of rustfmt across a single or multiple inputs.
457 pub struct Session<'b, T: Write + 'b> {
459 pub out: Option<&'b mut T>,
460 pub(crate) errors: ReportedErrors,
461 source_file: SourceFile,
464 impl<'b, T: Write + 'b> Session<'b, T> {
465 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
466 if config.emit_mode() == EmitMode::Checkstyle {
467 println!("{}", checkstyle::header());
473 errors: ReportedErrors::default(),
474 source_file: SourceFile::new(),
478 /// The main entry point for Rustfmt. Formats the given input according to the
479 /// given config. `out` is only necessary if required by the configuration.
480 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
481 self.format_input_inner(input)
484 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
486 F: FnOnce(&mut Session<'b, T>) -> U,
488 mem::swap(&mut config, &mut self.config);
489 let result = f(self);
490 mem::swap(&mut config, &mut self.config);
494 pub fn add_operational_error(&mut self) {
495 self.errors.has_operational_errors = true;
498 pub fn has_operational_errors(&self) -> bool {
499 self.errors.has_operational_errors
502 pub fn has_parsing_errors(&self) -> bool {
503 self.errors.has_parsing_errors
506 pub fn has_formatting_errors(&self) -> bool {
507 self.errors.has_formatting_errors
510 pub fn has_check_errors(&self) -> bool {
511 self.errors.has_check_errors
514 pub fn has_diff(&self) -> bool {
518 pub fn has_no_errors(&self) -> bool {
519 !(self.has_operational_errors()
520 || self.has_parsing_errors()
521 || self.has_formatting_errors()
522 || self.has_check_errors()
524 || self.errors.has_macro_format_failure
528 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
530 if self.config.emit_mode() == EmitMode::Checkstyle {
531 println!("{}", checkstyle::footer());
543 fn is_text(&self) -> bool {
545 Input::File(_) => false,
546 Input::Text(_) => true,
550 fn file_name(&self) -> FileName {
552 Input::File(ref file) => FileName::Real(file.clone()),
553 Input::Text(..) => FileName::Stdin,
563 fn test_no_panic_on_format_snippet_and_format_code_block() {
564 // `format_snippet()` and `format_code_block()` should not panic
565 // even when we cannot parse the given snippet.
567 assert!(format_snippet(snippet, &Config::default()).is_none());
568 assert!(format_code_block(snippet, &Config::default()).is_none());
571 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
573 F: Fn(&str, &Config) -> Option<String>,
575 let output = formatter(input, &Config::default());
576 output.is_some() && output.unwrap() == expected
580 fn test_format_snippet() {
581 let snippet = "fn main() { println!(\"hello, world\"); }";
583 let expected = "fn main() {\n \
584 println!(\"hello, world\");\n\
587 let expected = "fn main() {\r\n \
588 println!(\"hello, world\");\r\n\
590 assert!(test_format_inner(format_snippet, snippet, expected));
594 fn test_format_code_block_fail() {
596 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
597 assert!(format_code_block(code_block, &Config::default()).is_none());
601 fn test_format_code_block() {
603 let code_block = "let x=3;";
604 let expected = "let x = 3;";
605 assert!(test_format_inner(format_code_block, code_block, expected));
607 // more complex code block, taken from chains.rs.
609 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
611 chain_indent(context, shape.add_offset(parent_rewrite.len())),
612 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
614 } else if is_block_expr(context, &parent, &parent_rewrite) {
615 match context.config.indent_style() {
616 // Try to put the first child on the same line with parent's last line
617 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
618 // The parent is a block, so align the rest of the chain with the closing
620 IndentStyle::Visual => (parent_shape, false),
624 chain_indent(context, shape.add_offset(parent_rewrite.len())),
630 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
632 chain_indent(context, shape.add_offset(parent_rewrite.len())),
633 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
635 } else if is_block_expr(context, &parent, &parent_rewrite) {
636 match context.config.indent_style() {
637 // Try to put the first child on the same line with parent's last line
638 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
639 // The parent is a block, so align the rest of the chain with the closing
641 IndentStyle::Visual => (parent_shape, false),
645 chain_indent(context, shape.add_offset(parent_rewrite.len())),
649 assert!(test_format_inner(format_code_block, code_block, expected));