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;
20 extern crate bytecount;
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: {})",
106 LineOverflow(usize, usize),
107 /// Line ends in whitespace.
108 #[fail(display = "left behind trailing whitespace")]
110 /// TODO or FIXME item without an issue number.
111 #[fail(display = "found {}", _0)]
113 /// License check has failed.
114 #[fail(display = "license check failed")]
116 /// Used deprecated skip attribute.
117 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
119 /// Used a rustfmt:: attribute other than skip.
120 #[fail(display = "invalid attribute")]
122 /// An io error during reading or writing.
123 #[fail(display = "io error: {}", _0)]
125 /// Parse error occured when parsing the Input.
126 #[fail(display = "parse error")]
128 /// The user mandated a version and the current version of Rustfmt does not
129 /// satisfy that requirement.
130 #[fail(display = "version mismatch")]
132 /// If we had formatted the given node, then we would have lost a comment.
133 #[fail(display = "not formatted because a comment would be lost")]
138 fn is_comment(&self) -> bool {
140 ErrorKind::LostComment => true,
146 impl From<io::Error> for ErrorKind {
147 fn from(e: io::Error) -> ErrorKind {
148 ErrorKind::IoError(e)
152 /// Reports on any issues that occurred during a run of Rustfmt.
154 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
156 pub struct FormatReport {
157 // Maps stringified file paths to their associated formatting errors.
158 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
162 fn new() -> FormatReport {
164 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
168 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
169 self.track_errors(&v);
174 .and_modify(|fe| fe.append(&mut v))
178 fn track_errors(&self, new_errors: &[FormattingError]) {
179 let errs = &mut self.internal.borrow_mut().1;
180 if !new_errors.is_empty() {
181 errs.has_formatting_errors = true;
183 if errs.has_operational_errors && errs.has_check_errors {
186 for err in new_errors {
188 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
189 errs.has_operational_errors = true;
191 ErrorKind::BadIssue(_)
192 | ErrorKind::LicenseCheck
193 | ErrorKind::DeprecatedAttr
195 | ErrorKind::VersionMismatch => {
196 errs.has_check_errors = true;
203 fn add_diff(&mut self) {
204 self.internal.borrow_mut().1.has_diff = true;
207 fn add_macro_format_failure(&mut self) {
208 self.internal.borrow_mut().1.has_macro_format_failure = true;
211 fn add_parsing_error(&mut self) {
212 self.internal.borrow_mut().1.has_parsing_errors = true;
215 fn warning_count(&self) -> usize {
220 .map(|(_, errors)| errors.len())
224 /// Whether any warnings or errors are present in the report.
225 pub fn has_warnings(&self) -> bool {
226 self.internal.borrow().1.has_formatting_errors
229 /// Print the report to a terminal using colours and potentially other
233 mut t: Box<term::Terminal<Output = io::Stderr>>,
234 ) -> Result<(), term::Error> {
235 for (file, errors) in &self.internal.borrow().0 {
236 for error in errors {
237 let prefix_space_len = error.line.to_string().len();
238 let prefix_spaces = " ".repeat(1 + prefix_space_len);
240 // First line: the overview of error
241 t.fg(term::color::RED)?;
242 t.attr(term::Attr::Bold)?;
243 write!(t, "{} ", error.msg_prefix())?;
245 t.attr(term::Attr::Bold)?;
246 writeln!(t, "{}", error.kind)?;
248 // Second line: file info
249 write!(t, "{}--> ", &prefix_spaces[1..])?;
251 writeln!(t, "{}:{}", file, error.line)?;
253 // Third to fifth lines: show the line which triggered error, if available.
254 if !error.line_buffer.is_empty() {
255 let (space_len, target_len) = error.format_len();
256 t.attr(term::Attr::Bold)?;
257 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
259 writeln!(t, "{}", error.line_buffer)?;
260 t.attr(term::Attr::Bold)?;
261 write!(t, "{}| ", prefix_spaces)?;
262 t.fg(term::color::RED)?;
263 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
267 // The last line: show note if available.
268 let msg_suffix = error.msg_suffix();
269 if !msg_suffix.is_empty() {
270 t.attr(term::Attr::Bold)?;
271 write!(t, "{}= note: ", prefix_spaces)?;
273 writeln!(t, "{}", error.msg_suffix())?;
281 if !self.internal.borrow().0.is_empty() {
282 t.attr(term::Attr::Bold)?;
283 write!(t, "warning: ")?;
287 "rustfmt may have failed to format. See previous {} errors.\n\n",
288 self.warning_count(),
295 fn target_str(space_len: usize, target_len: usize) -> String {
296 let empty_line = " ".repeat(space_len);
297 let overflowed = "^".repeat(target_len);
298 empty_line + &overflowed
302 impl fmt::Display for FormatReport {
303 // Prints all the formatting errors.
304 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
305 for (file, errors) in &self.internal.borrow().0 {
306 for error in errors {
307 let prefix_space_len = error.line.to_string().len();
308 let prefix_spaces = " ".repeat(1 + prefix_space_len);
310 let error_line_buffer = if error.line_buffer.is_empty() {
313 let (space_len, target_len) = error.format_len();
315 "{}|\n{} | {}\n{}| {}",
320 FormatReport::target_str(space_len, target_len)
324 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
325 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
326 let msg_suffix = error.msg_suffix();
327 let note = if msg_suffix.is_empty() {
330 format!("{}note= ", prefix_spaces)
344 if !self.internal.borrow().0.is_empty() {
347 "warning: rustfmt may have failed to format. See previous {} errors.",
348 self.warning_count(),
355 /// Format the given snippet. The snippet is expected to be *complete* code.
356 /// When we cannot parse the given snippet, this function returns `None`.
357 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
358 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
359 let input = Input::Text(snippet.into());
360 let mut config = config.clone();
361 config.set().emit_mode(config::EmitMode::Stdout);
362 config.set().verbose(Verbosity::Quiet);
363 config.set().hide_parse_errors(true);
365 let mut session = Session::new(config, Some(&mut out));
366 let result = session.format(input);
367 let formatting_error = session.errors.has_macro_format_failure
368 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty();
369 if formatting_error || result.is_err() {
373 String::from_utf8(out).ok()
376 /// Format the given code block. Mainly targeted for code block in comment.
377 /// The code block may be incomplete (i.e. parser may be unable to parse it).
378 /// To avoid panic in parser, we wrap the code block with a dummy function.
379 /// The returned code block does *not* end with newline.
380 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
381 const FN_MAIN_PREFIX: &str = "fn main() {\n";
383 fn enclose_in_main_block(s: &str, config: &Config) -> String {
384 let indent = Indent::from_width(config, config.tab_spaces());
385 let mut result = String::with_capacity(s.len() * 2);
386 result.push_str(FN_MAIN_PREFIX);
387 let mut need_indent = true;
388 for (kind, line) in LineClasses::new(s) {
390 result.push_str(&indent.to_string(config));
392 result.push_str(&line);
394 need_indent = !kind.is_string() || line.ends_with('\\');
400 // Wrap the given code block with `fn main()` if it does not have one.
401 let snippet = enclose_in_main_block(code_snippet, config);
402 let mut result = String::with_capacity(snippet.len());
403 let mut is_first = true;
405 // While formatting the code, ignore the config's newline style setting and always use "\n"
406 // instead of "\r\n" for the newline characters. This is okay because the output here is
407 // not directly outputted by rustfmt command, but used by the comment formatter's input.
408 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
409 let mut config_with_unix_newline = config.clone();
410 config_with_unix_newline
412 .newline_style(NewlineStyle::Unix);
413 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
415 // Trim "fn main() {" on the first line and "}" on the last line,
416 // then unindent the whole code block.
417 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
418 let mut is_indented = true;
419 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
425 let trimmed_line = if !is_indented {
427 } else if line.len() > config.max_width() {
428 // If there are lines that are larger than max width, we cannot tell
429 // whether we have succeeded but have some comments or strings that
430 // are too long, or we have failed to format code block. We will be
431 // conservative and just return `None` in this case.
433 } else if line.len() > config.tab_spaces() {
434 // Make sure that the line has leading whitespaces.
435 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
436 if line.starts_with(indent_str.as_ref()) {
437 let offset = if config.hard_tabs() {
449 result.push_str(trimmed_line);
450 is_indented = !kind.is_string() || line.ends_with('\\');
455 /// A session is a run of rustfmt across a single or multiple inputs.
456 pub struct Session<'b, T: Write + 'b> {
458 pub out: Option<&'b mut T>,
459 pub(crate) errors: ReportedErrors,
460 source_file: SourceFile,
463 impl<'b, T: Write + 'b> Session<'b, T> {
464 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
465 if config.emit_mode() == EmitMode::Checkstyle {
466 println!("{}", checkstyle::header());
472 errors: ReportedErrors::default(),
473 source_file: SourceFile::new(),
477 /// The main entry point for Rustfmt. Formats the given input according to the
478 /// given config. `out` is only necessary if required by the configuration.
479 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
480 self.format_input_inner(input)
483 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
485 F: FnOnce(&mut Session<'b, T>) -> U,
487 mem::swap(&mut config, &mut self.config);
488 let result = f(self);
489 mem::swap(&mut config, &mut self.config);
493 pub fn add_operational_error(&mut self) {
494 self.errors.has_operational_errors = true;
497 pub fn has_operational_errors(&self) -> bool {
498 self.errors.has_operational_errors
501 pub fn has_parsing_errors(&self) -> bool {
502 self.errors.has_parsing_errors
505 pub fn has_formatting_errors(&self) -> bool {
506 self.errors.has_formatting_errors
509 pub fn has_check_errors(&self) -> bool {
510 self.errors.has_check_errors
513 pub fn has_diff(&self) -> bool {
517 pub fn has_no_errors(&self) -> bool {
518 !(self.has_operational_errors()
519 || self.has_parsing_errors()
520 || self.has_formatting_errors()
521 || self.has_check_errors()
523 || self.errors.has_macro_format_failure
527 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
529 if self.config.emit_mode() == EmitMode::Checkstyle {
530 println!("{}", checkstyle::footer());
542 fn is_text(&self) -> bool {
544 Input::File(_) => false,
545 Input::Text(_) => true,
549 fn file_name(&self) -> FileName {
551 Input::File(ref file) => FileName::Real(file.clone()),
552 Input::Text(..) => FileName::Stdin,
562 fn test_no_panic_on_format_snippet_and_format_code_block() {
563 // `format_snippet()` and `format_code_block()` should not panic
564 // even when we cannot parse the given snippet.
566 assert!(format_snippet(snippet, &Config::default()).is_none());
567 assert!(format_code_block(snippet, &Config::default()).is_none());
570 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
572 F: Fn(&str, &Config) -> Option<String>,
574 let output = formatter(input, &Config::default());
575 output.is_some() && output.unwrap() == expected
579 fn test_format_snippet() {
580 let snippet = "fn main() { println!(\"hello, world\"); }";
582 let expected = "fn main() {\n \
583 println!(\"hello, world\");\n\
586 let expected = "fn main() {\r\n \
587 println!(\"hello, world\");\r\n\
589 assert!(test_format_inner(format_snippet, snippet, expected));
593 fn test_format_code_block_fail() {
595 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
596 assert!(format_code_block(code_block, &Config::default()).is_none());
600 fn test_format_code_block() {
602 let code_block = "let x=3;";
603 let expected = "let x = 3;";
604 assert!(test_format_inner(format_code_block, code_block, expected));
606 // more complex code block, taken from chains.rs.
608 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
610 chain_indent(context, shape.add_offset(parent_rewrite.len())),
611 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
613 } else if is_block_expr(context, &parent, &parent_rewrite) {
614 match context.config.indent_style() {
615 // Try to put the first child on the same line with parent's last line
616 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
617 // The parent is a block, so align the rest of the chain with the closing
619 IndentStyle::Visual => (parent_shape, false),
623 chain_indent(context, shape.add_offset(parent_rewrite.len())),
629 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
631 chain_indent(context, shape.add_offset(parent_rewrite.len())),
632 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
634 } else if is_block_expr(context, &parent, &parent_rewrite) {
635 match context.config.indent_style() {
636 // Try to put the first child on the same line with parent's last line
637 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
638 // The parent is a block, so align the rest of the chain with the closing
640 IndentStyle::Visual => (parent_shape, false),
644 chain_indent(context, shape.add_offset(parent_rewrite.len())),
648 assert!(test_format_inner(format_code_block, code_block, expected));