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(tool_attributes)]
12 #![feature(decl_macro)]
13 #![allow(unused_attributes)]
14 #![feature(type_ascription)]
15 #![feature(unicode_internals)]
16 #![feature(extern_prelude)]
20 extern crate derive_new;
24 extern crate itertools;
27 extern crate lazy_static;
31 extern crate rustc_target;
34 extern crate serde_derive;
35 extern crate serde_json;
37 extern crate syntax_pos;
39 extern crate unicode_segmentation;
41 use std::cell::RefCell;
42 use std::collections::HashMap;
44 use std::io::{self, Write};
46 use std::path::PathBuf;
50 use comment::LineClasses;
52 use formatting::{FileMap, FormatErrorMap, FormattingError, ReportedErrors};
57 load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, NewlineStyle, Range,
66 pub(crate) mod checkstyle;
68 pub(crate) mod codemap;
70 pub(crate) mod config;
72 pub(crate) mod filemap;
73 pub(crate) mod formatting;
81 pub(crate) mod modules;
87 pub(crate) mod rustfmt_diff;
95 pub(crate) mod visitor;
97 /// The various errors that can occur during formatting. Note that not all of
98 /// these can currently be propagated to clients.
99 #[derive(Fail, Debug)]
101 /// Line has exceeded character limit (found, maximum).
103 display = "line formatted, but exceeded maximum width \
104 (maximum: {} (see `max_width` option), found: {})",
108 LineOverflow(usize, usize),
109 /// Line ends in whitespace.
110 #[fail(display = "left behind trailing whitespace")]
112 /// TODO or FIXME item without an issue number.
113 #[fail(display = "found {}", _0)]
115 /// License check has failed.
116 #[fail(display = "license check failed")]
118 /// Used deprecated skip attribute.
119 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
121 /// Used a rustfmt:: attribute other than skip.
122 #[fail(display = "invalid attribute")]
124 /// An io error during reading or writing.
125 #[fail(display = "io error: {}", _0)]
127 /// Parse error occured when parsing the Input.
128 #[fail(display = "parse error")]
130 /// The user mandated a version and the current version of Rustfmt does not
131 /// satisfy that requirement.
132 #[fail(display = "version mismatch")]
134 /// If we had formatted the given node, then we would have lost a comment.
135 #[fail(display = "not formatted because a comment would be lost")]
140 fn is_comment(&self) -> bool {
142 ErrorKind::LostComment => true,
148 impl From<io::Error> for ErrorKind {
149 fn from(e: io::Error) -> ErrorKind {
150 ErrorKind::IoError(e)
154 /// Reports on any issues that occurred during a run of Rustfmt.
156 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
158 pub struct FormatReport {
159 // Maps stringified file paths to their associated formatting errors.
160 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
164 fn new() -> FormatReport {
166 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
170 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
171 self.track_errors(&v);
176 .and_modify(|fe| fe.append(&mut v))
180 fn track_errors(&self, new_errors: &[FormattingError]) {
181 let errs = &mut self.internal.borrow_mut().1;
182 if !new_errors.is_empty() {
183 errs.has_formatting_errors = true;
185 if errs.has_operational_errors && errs.has_check_errors {
188 for err in new_errors {
190 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
191 errs.has_operational_errors = true;
193 ErrorKind::BadIssue(_)
194 | ErrorKind::LicenseCheck
195 | ErrorKind::DeprecatedAttr
197 | ErrorKind::VersionMismatch => {
198 errs.has_check_errors = true;
205 fn add_diff(&mut self) {
206 self.internal.borrow_mut().1.has_diff = true;
209 fn add_macro_format_failure(&mut self) {
210 self.internal.borrow_mut().1.has_macro_format_failure = true;
213 fn add_parsing_error(&mut self) {
214 self.internal.borrow_mut().1.has_parsing_errors = true;
217 fn warning_count(&self) -> usize {
222 .map(|(_, errors)| errors.len())
226 /// Whether any warnings or errors are present in the report.
227 pub fn has_warnings(&self) -> bool {
228 self.internal.borrow().1.has_formatting_errors
231 /// Print the report to a terminal using colours and potentially other
235 mut t: Box<term::Terminal<Output = io::Stderr>>,
236 ) -> Result<(), term::Error> {
237 for (file, errors) in &self.internal.borrow().0 {
238 for error in errors {
239 let prefix_space_len = error.line.to_string().len();
240 let prefix_spaces = " ".repeat(1 + prefix_space_len);
242 // First line: the overview of error
243 t.fg(term::color::RED)?;
244 t.attr(term::Attr::Bold)?;
245 write!(t, "{} ", error.msg_prefix())?;
247 t.attr(term::Attr::Bold)?;
248 writeln!(t, "{}", error.kind)?;
250 // Second line: file info
251 write!(t, "{}--> ", &prefix_spaces[1..])?;
253 writeln!(t, "{}:{}", file, error.line)?;
255 // Third to fifth lines: show the line which triggered error, if available.
256 if !error.line_buffer.is_empty() {
257 let (space_len, target_len) = error.format_len();
258 t.attr(term::Attr::Bold)?;
259 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
261 writeln!(t, "{}", error.line_buffer)?;
262 t.attr(term::Attr::Bold)?;
263 write!(t, "{}| ", prefix_spaces)?;
264 t.fg(term::color::RED)?;
265 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
269 // The last line: show note if available.
270 let msg_suffix = error.msg_suffix();
271 if !msg_suffix.is_empty() {
272 t.attr(term::Attr::Bold)?;
273 write!(t, "{}= note: ", prefix_spaces)?;
275 writeln!(t, "{}", error.msg_suffix())?;
283 if !self.internal.borrow().0.is_empty() {
284 t.attr(term::Attr::Bold)?;
285 write!(t, "warning: ")?;
289 "rustfmt may have failed to format. See previous {} errors.\n\n",
290 self.warning_count(),
297 fn target_str(space_len: usize, target_len: usize) -> String {
298 let empty_line = " ".repeat(space_len);
299 let overflowed = "^".repeat(target_len);
300 empty_line + &overflowed
304 impl fmt::Display for FormatReport {
305 // Prints all the formatting errors.
306 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
307 for (file, errors) in &self.internal.borrow().0 {
308 for error in errors {
309 let prefix_space_len = error.line.to_string().len();
310 let prefix_spaces = " ".repeat(1 + prefix_space_len);
312 let error_line_buffer = if error.line_buffer.is_empty() {
315 let (space_len, target_len) = error.format_len();
317 "{}|\n{} | {}\n{}| {}",
322 FormatReport::target_str(space_len, target_len)
326 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
327 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
328 let msg_suffix = error.msg_suffix();
329 let note = if msg_suffix.is_empty() {
332 format!("{}note= ", prefix_spaces)
346 if !self.internal.borrow().0.is_empty() {
349 "warning: rustfmt may have failed to format. See previous {} errors.",
350 self.warning_count(),
357 /// Format the given snippet. The snippet is expected to be *complete* code.
358 /// When we cannot parse the given snippet, this function returns `None`.
359 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
360 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
361 let input = Input::Text(snippet.into());
362 let mut config = config.clone();
363 config.set().emit_mode(config::EmitMode::Stdout);
364 config.set().verbose(Verbosity::Quiet);
365 config.set().hide_parse_errors(true);
367 let mut session = Session::new(config, Some(&mut out));
368 let result = session.format(input);
369 let formatting_error = session.errors.has_macro_format_failure
370 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty();
371 if formatting_error || result.is_err() {
375 String::from_utf8(out).ok()
378 /// Format the given code block. Mainly targeted for code block in comment.
379 /// The code block may be incomplete (i.e. parser may be unable to parse it).
380 /// To avoid panic in parser, we wrap the code block with a dummy function.
381 /// The returned code block does *not* end with newline.
382 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
383 const FN_MAIN_PREFIX: &str = "fn main() {\n";
385 fn enclose_in_main_block(s: &str, config: &Config) -> String {
386 let indent = Indent::from_width(config, config.tab_spaces());
387 let mut result = String::with_capacity(s.len() * 2);
388 result.push_str(FN_MAIN_PREFIX);
389 let mut need_indent = true;
390 for (kind, line) in LineClasses::new(s) {
392 result.push_str(&indent.to_string(config));
394 result.push_str(&line);
396 need_indent = !kind.is_string() || line.ends_with('\\');
402 // Wrap the given code block with `fn main()` if it does not have one.
403 let snippet = enclose_in_main_block(code_snippet, config);
404 let mut result = String::with_capacity(snippet.len());
405 let mut is_first = true;
407 // While formatting the code, ignore the config's newline style setting and always use "\n"
408 // instead of "\r\n" for the newline characters. This is okay because the output here is
409 // not directly outputted by rustfmt command, but used by the comment formatter's input.
410 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
411 let mut config_with_unix_newline = config.clone();
412 config_with_unix_newline
414 .newline_style(NewlineStyle::Unix);
415 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
417 // Trim "fn main() {" on the first line and "}" on the last line,
418 // then unindent the whole code block.
419 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
420 let mut is_indented = true;
421 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
427 let trimmed_line = if !is_indented {
429 } else if line.len() > config.max_width() {
430 // If there are lines that are larger than max width, we cannot tell
431 // whether we have succeeded but have some comments or strings that
432 // are too long, or we have failed to format code block. We will be
433 // conservative and just return `None` in this case.
435 } else if line.len() > config.tab_spaces() {
436 // Make sure that the line has leading whitespaces.
437 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
438 if line.starts_with(indent_str.as_ref()) {
439 let offset = if config.hard_tabs() {
451 result.push_str(trimmed_line);
452 is_indented = !kind.is_string() || line.ends_with('\\');
457 /// A session is a run of rustfmt across a single or multiple inputs.
458 pub struct Session<'b, T: Write + 'b> {
460 pub out: Option<&'b mut T>,
461 pub(crate) errors: ReportedErrors,
465 impl<'b, T: Write + 'b> Session<'b, T> {
466 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
467 if config.emit_mode() == EmitMode::Checkstyle {
468 println!("{}", checkstyle::header());
474 errors: ReportedErrors::default(),
475 filemap: FileMap::new(),
479 /// The main entry point for Rustfmt. Formats the given input according to the
480 /// given config. `out` is only necessary if required by the configuration.
481 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
482 self.format_input_inner(input)
485 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
487 F: FnOnce(&mut Session<'b, T>) -> U,
489 mem::swap(&mut config, &mut self.config);
490 let result = f(self);
491 mem::swap(&mut config, &mut self.config);
495 pub fn add_operational_error(&mut self) {
496 self.errors.has_operational_errors = true;
499 pub fn has_operational_errors(&self) -> bool {
500 self.errors.has_operational_errors
503 pub fn has_parsing_errors(&self) -> bool {
504 self.errors.has_parsing_errors
507 pub fn has_formatting_errors(&self) -> bool {
508 self.errors.has_formatting_errors
511 pub fn has_check_errors(&self) -> bool {
512 self.errors.has_check_errors
515 pub fn has_diff(&self) -> bool {
519 pub fn has_no_errors(&self) -> bool {
520 !(self.has_operational_errors()
521 || self.has_parsing_errors()
522 || self.has_formatting_errors()
523 || self.has_check_errors()
525 || self.errors.has_macro_format_failure
529 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
531 if self.config.emit_mode() == EmitMode::Checkstyle {
532 println!("{}", checkstyle::footer());
544 fn is_text(&self) -> bool {
546 Input::File(_) => false,
547 Input::Text(_) => true,
551 fn file_name(&self) -> FileName {
553 Input::File(ref file) => FileName::Real(file.clone()),
554 Input::Text(..) => FileName::Stdin,
564 fn test_no_panic_on_format_snippet_and_format_code_block() {
565 // `format_snippet()` and `format_code_block()` should not panic
566 // even when we cannot parse the given snippet.
568 assert!(format_snippet(snippet, &Config::default()).is_none());
569 assert!(format_code_block(snippet, &Config::default()).is_none());
572 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
574 F: Fn(&str, &Config) -> Option<String>,
576 let output = formatter(input, &Config::default());
577 output.is_some() && output.unwrap() == expected
581 fn test_format_snippet() {
582 let snippet = "fn main() { println!(\"hello, world\"); }";
584 let expected = "fn main() {\n \
585 println!(\"hello, world\");\n\
588 let expected = "fn main() {\r\n \
589 println!(\"hello, world\");\r\n\
591 assert!(test_format_inner(format_snippet, snippet, expected));
595 fn test_format_code_block_fail() {
597 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
598 assert!(format_code_block(code_block, &Config::default()).is_none());
602 fn test_format_code_block() {
604 let code_block = "let x=3;";
605 let expected = "let x = 3;";
606 assert!(test_format_inner(format_code_block, code_block, expected));
608 // more complex code block, taken from chains.rs.
610 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
612 chain_indent(context, shape.add_offset(parent_rewrite.len())),
613 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
615 } else if is_block_expr(context, &parent, &parent_rewrite) {
616 match context.config.indent_style() {
617 // Try to put the first child on the same line with parent's last line
618 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
619 // The parent is a block, so align the rest of the chain with the closing
621 IndentStyle::Visual => (parent_shape, false),
625 chain_indent(context, shape.add_offset(parent_rewrite.len())),
631 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
633 chain_indent(context, shape.add_offset(parent_rewrite.len())),
634 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
636 } else if is_block_expr(context, &parent, &parent_rewrite) {
637 match context.config.indent_style() {
638 // Try to put the first child on the same line with parent's last line
639 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
640 // The parent is a block, so align the rest of the chain with the closing
642 IndentStyle::Visual => (parent_shape, false),
646 chain_indent(context, shape.add_offset(parent_rewrite.len())),
650 assert!(test_format_inner(format_code_block, code_block, expected));