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::{FormatErrorMap, FormattingError, ReportedErrors};
56 pub use config::summary::Summary;
58 load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, NewlineStyle, Range,
67 pub(crate) mod checkstyle;
69 pub(crate) mod codemap;
71 pub(crate) mod config;
73 pub(crate) mod filemap;
74 pub(crate) mod formatting;
82 pub(crate) mod modules;
88 pub(crate) mod rustfmt_diff;
96 pub(crate) mod visitor;
98 /// The various errors that can occur during formatting. Note that not all of
99 /// these can currently be propagated to clients.
100 #[derive(Fail, Debug)]
102 /// Line has exceeded character limit (found, maximum).
104 display = "line formatted, but exceeded maximum width \
105 (maximum: {} (see `max_width` option), found: {})",
109 LineOverflow(usize, usize),
110 /// Line ends in whitespace.
111 #[fail(display = "left behind trailing whitespace")]
113 /// TODO or FIXME item without an issue number.
114 #[fail(display = "found {}", _0)]
116 /// License check has failed.
117 #[fail(display = "license check failed")]
119 /// Used deprecated skip attribute.
120 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
122 /// Used a rustfmt:: attribute other than skip.
123 #[fail(display = "invalid attribute")]
125 /// An io error during reading or writing.
126 #[fail(display = "io error: {}", _0)]
128 /// Parse error occured when parsing the Input.
129 #[fail(display = "parse error")]
131 /// The user mandated a version and the current version of Rustfmt does not
132 /// satisfy that requirement.
133 #[fail(display = "version mismatch")]
135 /// If we had formatted the given node, then we would have lost a comment.
136 #[fail(display = "not formatted because a comment would be lost")]
141 fn is_comment(&self) -> bool {
143 ErrorKind::LostComment => true,
149 impl From<io::Error> for ErrorKind {
150 fn from(e: io::Error) -> ErrorKind {
151 ErrorKind::IoError(e)
155 /// Reports on any issues that occurred during a run of Rustfmt.
157 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
159 pub struct FormatReport {
160 // Maps stringified file paths to their associated formatting errors.
161 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
165 fn new() -> FormatReport {
167 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
171 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
172 self.track_errors(&v);
177 .and_modify(|fe| fe.append(&mut v))
181 fn track_errors(&self, new_errors: &[FormattingError]) {
182 let errs = &mut self.internal.borrow_mut().1;
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 warning_count(&self) -> usize {
208 .map(|(_, errors)| errors.len())
212 /// Whether any warnings or errors are present in the report.
213 pub fn has_warnings(&self) -> bool {
214 self.warning_count() > 0
217 /// Print the report to a terminal using colours and potentially other
221 mut t: Box<term::Terminal<Output = io::Stderr>>,
222 ) -> Result<(), term::Error> {
223 for (file, errors) in &self.internal.borrow().0 {
224 for error in errors {
225 let prefix_space_len = error.line.to_string().len();
226 let prefix_spaces = " ".repeat(1 + prefix_space_len);
228 // First line: the overview of error
229 t.fg(term::color::RED)?;
230 t.attr(term::Attr::Bold)?;
231 write!(t, "{} ", error.msg_prefix())?;
233 t.attr(term::Attr::Bold)?;
234 writeln!(t, "{}", error.kind)?;
236 // Second line: file info
237 write!(t, "{}--> ", &prefix_spaces[1..])?;
239 writeln!(t, "{}:{}", file, error.line)?;
241 // Third to fifth lines: show the line which triggered error, if available.
242 if !error.line_buffer.is_empty() {
243 let (space_len, target_len) = error.format_len();
244 t.attr(term::Attr::Bold)?;
245 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
247 writeln!(t, "{}", error.line_buffer)?;
248 t.attr(term::Attr::Bold)?;
249 write!(t, "{}| ", prefix_spaces)?;
250 t.fg(term::color::RED)?;
251 writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
255 // The last line: show note if available.
256 let msg_suffix = error.msg_suffix();
257 if !msg_suffix.is_empty() {
258 t.attr(term::Attr::Bold)?;
259 write!(t, "{}= note: ", prefix_spaces)?;
261 writeln!(t, "{}", error.msg_suffix())?;
269 if !self.internal.borrow().0.is_empty() {
270 t.attr(term::Attr::Bold)?;
271 write!(t, "warning: ")?;
275 "rustfmt may have failed to format. See previous {} errors.\n\n",
276 self.warning_count(),
283 fn target_str(space_len: usize, target_len: usize) -> String {
284 let empty_line = " ".repeat(space_len);
285 let overflowed = "^".repeat(target_len);
286 empty_line + &overflowed
290 impl fmt::Display for FormatReport {
291 // Prints all the formatting errors.
292 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
293 for (file, errors) in &self.internal.borrow().0 {
294 for error in errors {
295 let prefix_space_len = error.line.to_string().len();
296 let prefix_spaces = " ".repeat(1 + prefix_space_len);
298 let error_line_buffer = if error.line_buffer.is_empty() {
301 let (space_len, target_len) = error.format_len();
303 "{}|\n{} | {}\n{}| {}",
308 FormatReport::target_str(space_len, target_len)
312 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
313 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
314 let msg_suffix = error.msg_suffix();
315 let note = if msg_suffix.is_empty() {
318 format!("{}note= ", prefix_spaces)
332 if !self.internal.borrow().0.is_empty() {
335 "warning: rustfmt may have failed to format. See previous {} errors.",
336 self.warning_count(),
343 /// Format the given snippet. The snippet is expected to be *complete* code.
344 /// When we cannot parse the given snippet, this function returns `None`.
345 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
346 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
347 let input = Input::Text(snippet.into());
348 let mut config = config.clone();
349 config.set().emit_mode(config::EmitMode::Stdout);
350 config.set().verbose(Verbosity::Quiet);
351 config.set().hide_parse_errors(true);
353 let mut session = Session::new(config, Some(&mut out));
354 let result = session.format(input);
355 let formatting_error = session.summary.has_macro_formatting_failure()
356 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty();
357 if formatting_error || result.is_err() {
361 String::from_utf8(out).ok()
364 /// Format the given code block. Mainly targeted for code block in comment.
365 /// The code block may be incomplete (i.e. parser may be unable to parse it).
366 /// To avoid panic in parser, we wrap the code block with a dummy function.
367 /// The returned code block does *not* end with newline.
368 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
369 const FN_MAIN_PREFIX: &str = "fn main() {\n";
371 fn enclose_in_main_block(s: &str, config: &Config) -> String {
372 let indent = Indent::from_width(config, config.tab_spaces());
373 let mut result = String::with_capacity(s.len() * 2);
374 result.push_str(FN_MAIN_PREFIX);
375 let mut need_indent = true;
376 for (kind, line) in LineClasses::new(s) {
378 result.push_str(&indent.to_string(config));
380 result.push_str(&line);
382 need_indent = !kind.is_string() || line.ends_with('\\');
388 // Wrap the given code block with `fn main()` if it does not have one.
389 let snippet = enclose_in_main_block(code_snippet, config);
390 let mut result = String::with_capacity(snippet.len());
391 let mut is_first = true;
393 // While formatting the code, ignore the config's newline style setting and always use "\n"
394 // instead of "\r\n" for the newline characters. This is okay because the output here is
395 // not directly outputted by rustfmt command, but used by the comment formatter's input.
396 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
397 let mut config_with_unix_newline = config.clone();
398 config_with_unix_newline
400 .newline_style(NewlineStyle::Unix);
401 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
403 // Trim "fn main() {" on the first line and "}" on the last line,
404 // then unindent the whole code block.
405 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
406 let mut is_indented = true;
407 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
413 let trimmed_line = if !is_indented {
415 } else if line.len() > config.max_width() {
416 // If there are lines that are larger than max width, we cannot tell
417 // whether we have succeeded but have some comments or strings that
418 // are too long, or we have failed to format code block. We will be
419 // conservative and just return `None` in this case.
421 } else if line.len() > config.tab_spaces() {
422 // Make sure that the line has leading whitespaces.
423 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
424 if line.starts_with(indent_str.as_ref()) {
425 let offset = if config.hard_tabs() {
437 result.push_str(trimmed_line);
438 is_indented = !kind.is_string() || line.ends_with('\\');
443 /// A session is a run of rustfmt across a single or multiple inputs.
444 pub struct Session<'b, T: Write + 'b> {
446 pub out: Option<&'b mut T>,
447 pub summary: Summary,
450 impl<'b, T: Write + 'b> Session<'b, T> {
451 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
452 if config.emit_mode() == EmitMode::Checkstyle {
453 println!("{}", checkstyle::header());
459 summary: Summary::default(),
463 /// The main entry point for Rustfmt. Formats the given input according to the
464 /// given config. `out` is only necessary if required by the configuration.
465 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
466 if !self.config.version_meets_requirement() {
467 return Err(ErrorKind::VersionMismatch);
470 syntax::with_globals(|| self.format_input_inner(input)).map(|tup| tup.1)
473 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
475 F: FnOnce(&mut Session<'b, T>) -> U,
477 mem::swap(&mut config, &mut self.config);
478 let result = f(self);
479 mem::swap(&mut config, &mut self.config);
484 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
486 if self.config.emit_mode() == EmitMode::Checkstyle {
487 println!("{}", checkstyle::footer());
503 fn test_no_panic_on_format_snippet_and_format_code_block() {
504 // `format_snippet()` and `format_code_block()` should not panic
505 // even when we cannot parse the given snippet.
507 assert!(format_snippet(snippet, &Config::default()).is_none());
508 assert!(format_code_block(snippet, &Config::default()).is_none());
511 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
513 F: Fn(&str, &Config) -> Option<String>,
515 let output = formatter(input, &Config::default());
516 output.is_some() && output.unwrap() == expected
520 fn test_format_snippet() {
521 let snippet = "fn main() { println!(\"hello, world\"); }";
523 let expected = "fn main() {\n \
524 println!(\"hello, world\");\n\
527 let expected = "fn main() {\r\n \
528 println!(\"hello, world\");\r\n\
530 assert!(test_format_inner(format_snippet, snippet, expected));
534 fn test_format_code_block_fail() {
536 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
537 assert!(format_code_block(code_block, &Config::default()).is_none());
541 fn test_format_code_block() {
543 let code_block = "let x=3;";
544 let expected = "let x = 3;";
545 assert!(test_format_inner(format_code_block, code_block, expected));
547 // more complex code block, taken from chains.rs.
549 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
551 chain_indent(context, shape.add_offset(parent_rewrite.len())),
552 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
554 } else if is_block_expr(context, &parent, &parent_rewrite) {
555 match context.config.indent_style() {
556 // Try to put the first child on the same line with parent's last line
557 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
558 // The parent is a block, so align the rest of the chain with the closing
560 IndentStyle::Visual => (parent_shape, false),
564 chain_indent(context, shape.add_offset(parent_rewrite.len())),
570 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
572 chain_indent(context, shape.add_offset(parent_rewrite.len())),
573 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
575 } else if is_block_expr(context, &parent, &parent_rewrite) {
576 match context.config.indent_style() {
577 // Try to put the first child on the same line with parent's last line
578 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
579 // The parent is a block, so align the rest of the chain with the closing
581 IndentStyle::Visual => (parent_shape, false),
585 chain_indent(context, shape.add_offset(parent_rewrite.len())),
589 assert!(test_format_inner(format_code_block, code_block, expected));