1 #![deny(rust_2018_idioms)]
4 extern crate derive_new;
7 extern crate lazy_static;
11 use std::cell::RefCell;
12 use std::collections::HashMap;
14 use std::io::{self, Write};
17 use std::path::PathBuf;
22 use syntax::{ast, parse::DirectoryOwnership};
24 use crate::comment::LineClasses;
25 use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
26 use crate::issues::Issue;
27 use crate::shape::Indent;
28 use crate::utils::indent_next_line;
30 pub use crate::config::{
31 load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
35 pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
37 pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
44 pub(crate) mod checkstyle;
47 pub(crate) mod config;
49 mod format_report_formatter;
50 pub(crate) mod formatting;
59 pub(crate) mod modules;
65 pub(crate) mod rustfmt_diff;
67 pub(crate) mod source_file;
68 pub(crate) mod source_map;
75 pub(crate) mod visitor;
77 /// The various errors that can occur during formatting. Note that not all of
78 /// these can currently be propagated to clients.
79 #[derive(Fail, Debug)]
81 /// Line has exceeded character limit (found, maximum).
83 display = "line formatted, but exceeded maximum width \
84 (maximum: {} (see `max_width` option), found: {})",
87 LineOverflow(usize, usize),
88 /// Line ends in whitespace.
89 #[fail(display = "left behind trailing whitespace")]
91 /// TODO or FIXME item without an issue number.
92 #[fail(display = "found {}", _0)]
94 /// License check has failed.
95 #[fail(display = "license check failed")]
97 /// Used deprecated skip attribute.
98 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
100 /// Used a rustfmt:: attribute other than skip or skip::macros.
101 #[fail(display = "invalid attribute")]
103 /// An io error during reading or writing.
104 #[fail(display = "io error: {}", _0)]
106 /// Parse error occurred when parsing the input.
107 #[fail(display = "parse error")]
109 /// The user mandated a version and the current version of Rustfmt does not
110 /// satisfy that requirement.
111 #[fail(display = "version mismatch")]
113 /// If we had formatted the given node, then we would have lost a comment.
114 #[fail(display = "not formatted because a comment would be lost")]
116 /// Invalid glob pattern in `ignore` configuration option.
117 #[fail(display = "Invalid glob pattern found in ignore list: {}", _0)]
118 InvalidGlobPattern(ignore::Error),
122 fn is_comment(&self) -> bool {
124 ErrorKind::LostComment => true,
130 impl From<io::Error> for ErrorKind {
131 fn from(e: io::Error) -> ErrorKind {
132 ErrorKind::IoError(e)
136 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
137 /// i.e., that got returned as they were originally.
139 struct FormattedSnippet {
141 non_formatted_ranges: Vec<(usize, usize)>,
144 impl FormattedSnippet {
145 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
146 /// non-formatted code.
147 fn unwrap_code_block(&mut self) {
148 self.non_formatted_ranges
150 .for_each(|(low, high)| {
156 /// Returns `true` if the line n did not get formatted.
157 fn is_line_non_formatted(&self, n: usize) -> bool {
158 self.non_formatted_ranges
160 .any(|(low, high)| *low <= n && n <= *high)
164 /// Reports on any issues that occurred during a run of Rustfmt.
166 /// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
168 pub struct FormatReport {
169 // Maps stringified file paths to their associated formatting errors.
170 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
171 non_formatted_ranges: Vec<(usize, usize)>,
175 fn new() -> FormatReport {
177 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
178 non_formatted_ranges: Vec::new(),
182 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
183 self.non_formatted_ranges.append(&mut ranges);
186 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
187 self.track_errors(&v);
192 .and_modify(|fe| fe.append(&mut v))
196 fn track_errors(&self, new_errors: &[FormattingError]) {
197 let errs = &mut self.internal.borrow_mut().1;
198 if !new_errors.is_empty() {
199 errs.has_formatting_errors = true;
201 if errs.has_operational_errors && errs.has_check_errors {
204 for err in new_errors {
206 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
207 errs.has_operational_errors = true;
209 ErrorKind::BadIssue(_)
210 | ErrorKind::LicenseCheck
211 | ErrorKind::DeprecatedAttr
213 | ErrorKind::VersionMismatch => {
214 errs.has_check_errors = true;
221 fn add_diff(&mut self) {
222 self.internal.borrow_mut().1.has_diff = true;
225 fn add_macro_format_failure(&mut self) {
226 self.internal.borrow_mut().1.has_macro_format_failure = true;
229 fn add_parsing_error(&mut self) {
230 self.internal.borrow_mut().1.has_parsing_errors = true;
233 fn warning_count(&self) -> usize {
238 .map(|(_, errors)| errors.len())
242 /// Whether any warnings or errors are present in the report.
243 pub fn has_warnings(&self) -> bool {
244 self.internal.borrow().1.has_formatting_errors
247 /// Print the report to a terminal using colours and potentially other
249 #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
252 mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
253 ) -> Result<(), term::Error> {
257 FormatReportFormatterBuilder::new(&self)
265 #[deprecated(note = "Use FormatReportFormatter instead")]
266 impl fmt::Display for FormatReport {
267 // Prints all the formatting errors.
268 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
269 write!(fmt, "{}", FormatReportFormatterBuilder::new(&self).build())?;
274 /// Format the given snippet. The snippet is expected to be *complete* code.
275 /// When we cannot parse the given snippet, this function returns `None`.
276 fn format_snippet(snippet: &str, config: &Config) -> Option<FormattedSnippet> {
277 let mut config = config.clone();
278 panic::catch_unwind(|| {
279 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
280 config.set().emit_mode(config::EmitMode::Stdout);
281 config.set().verbose(Verbosity::Quiet);
282 config.set().hide_parse_errors(true);
284 let (formatting_error, result) = {
285 let input = Input::Text(snippet.into());
286 let mut session = Session::new(config, Some(&mut out));
287 let result = session.format(input);
289 session.errors.has_macro_format_failure
290 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
295 if formatting_error {
298 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
300 non_formatted_ranges: result.unwrap().non_formatted_ranges,
304 // Discard panics encountered while formatting the snippet
305 // The ? operator is needed to remove the extra Option
309 /// Format the given code block. Mainly targeted for code block in comment.
310 /// The code block may be incomplete (i.e., parser may be unable to parse it).
311 /// To avoid panic in parser, we wrap the code block with a dummy function.
312 /// The returned code block does **not** end with newline.
313 fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSnippet> {
314 const FN_MAIN_PREFIX: &str = "fn main() {\n";
316 fn enclose_in_main_block(s: &str, config: &Config) -> String {
317 let indent = Indent::from_width(config, config.tab_spaces());
318 let mut result = String::with_capacity(s.len() * 2);
319 result.push_str(FN_MAIN_PREFIX);
320 let mut need_indent = true;
321 for (kind, line) in LineClasses::new(s) {
323 result.push_str(&indent.to_string(config));
325 result.push_str(&line);
327 need_indent = indent_next_line(kind, &line, config);
333 // Wrap the given code block with `fn main()` if it does not have one.
334 let snippet = enclose_in_main_block(code_snippet, config);
335 let mut result = String::with_capacity(snippet.len());
336 let mut is_first = true;
338 // While formatting the code, ignore the config's newline style setting and always use "\n"
339 // instead of "\r\n" for the newline characters. This is ok because the output here is
340 // not directly outputted by rustfmt command, but used by the comment formatter's input.
341 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
342 let mut config_with_unix_newline = config.clone();
343 config_with_unix_newline
345 .newline_style(NewlineStyle::Unix);
346 let mut formatted = format_snippet(&snippet, &config_with_unix_newline)?;
347 // Remove wrapping main block
348 formatted.unwrap_code_block();
350 // Trim "fn main() {" on the first line and "}" on the last line,
351 // then unindent the whole code block.
352 let block_len = formatted
355 .unwrap_or_else(|| formatted.snippet.len());
356 let mut is_indented = true;
357 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
363 let trimmed_line = if !is_indented {
365 } else if line.len() > config.max_width() {
366 // If there are lines that are larger than max width, we cannot tell
367 // whether we have succeeded but have some comments or strings that
368 // are too long, or we have failed to format code block. We will be
369 // conservative and just return `None` in this case.
371 } else if line.len() > config.tab_spaces() {
372 // Make sure that the line has leading whitespaces.
373 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
374 if line.starts_with(indent_str.as_ref()) {
375 let offset = if config.hard_tabs() {
387 result.push_str(trimmed_line);
388 is_indented = indent_next_line(kind, line, config);
390 Some(FormattedSnippet {
392 non_formatted_ranges: formatted.non_formatted_ranges,
396 /// A session is a run of rustfmt across a single or multiple inputs.
397 pub struct Session<'b, T: Write> {
399 pub out: Option<&'b mut T>,
400 pub(crate) errors: ReportedErrors,
401 source_file: SourceFile,
404 impl<'b, T: Write + 'b> Session<'b, T> {
405 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
406 if config.emit_mode() == EmitMode::Checkstyle {
407 println!("{}", checkstyle::header());
413 errors: ReportedErrors::default(),
414 source_file: SourceFile::new(),
418 /// The main entry point for Rustfmt. Formats the given input according to the
419 /// given config. `out` is only necessary if required by the configuration.
420 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
421 self.format_input_inner(input)
424 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
426 F: FnOnce(&mut Session<'b, T>) -> U,
428 mem::swap(&mut config, &mut self.config);
429 let result = f(self);
430 mem::swap(&mut config, &mut self.config);
434 pub fn add_operational_error(&mut self) {
435 self.errors.has_operational_errors = true;
438 pub fn has_operational_errors(&self) -> bool {
439 self.errors.has_operational_errors
442 pub fn has_parsing_errors(&self) -> bool {
443 self.errors.has_parsing_errors
446 pub fn has_formatting_errors(&self) -> bool {
447 self.errors.has_formatting_errors
450 pub fn has_check_errors(&self) -> bool {
451 self.errors.has_check_errors
454 pub fn has_diff(&self) -> bool {
458 pub fn has_no_errors(&self) -> bool {
459 !(self.has_operational_errors()
460 || self.has_parsing_errors()
461 || self.has_formatting_errors()
462 || self.has_check_errors()
464 || self.errors.has_macro_format_failure
468 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
470 if self.config.emit_mode() == EmitMode::Checkstyle {
471 println!("{}", checkstyle::footer());
483 fn is_text(&self) -> bool {
485 Input::File(_) => false,
486 Input::Text(_) => true,
490 fn file_name(&self) -> FileName {
492 Input::File(ref file) => FileName::Real(file.clone()),
493 Input::Text(..) => FileName::Stdin,
497 fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
499 Input::File(ref file) => {
500 // If there exists a directory with the same name as an input,
501 // then the input should be parsed as a sub module.
502 let file_stem = file.file_stem()?;
503 if file.parent()?.to_path_buf().join(file_stem).is_dir() {
504 Some(DirectoryOwnership::Owned {
505 relative: file_stem.to_str().map(ast::Ident::from_str),
521 fn test_no_panic_on_format_snippet_and_format_code_block() {
522 // `format_snippet()` and `format_code_block()` should not panic
523 // even when we cannot parse the given snippet.
525 assert!(format_snippet(snippet, &Config::default()).is_none());
526 assert!(format_code_block(snippet, &Config::default()).is_none());
529 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
531 F: Fn(&str, &Config) -> Option<FormattedSnippet>,
533 let output = formatter(input, &Config::default());
534 output.is_some() && output.unwrap().snippet == expected
538 fn test_format_snippet() {
539 let snippet = "fn main() { println!(\"hello, world\"); }";
541 let expected = "fn main() {\n \
542 println!(\"hello, world\");\n\
545 let expected = "fn main() {\r\n \
546 println!(\"hello, world\");\r\n\
548 assert!(test_format_inner(format_snippet, snippet, expected));
552 fn test_format_code_block_fail() {
554 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
555 assert!(format_code_block(code_block, &Config::default()).is_none());
559 fn test_format_code_block() {
561 let code_block = "let x=3;";
562 let expected = "let x = 3;";
563 assert!(test_format_inner(format_code_block, code_block, expected));
565 // more complex code block, taken from chains.rs.
567 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
569 chain_indent(context, shape.add_offset(parent_rewrite.len())),
570 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
572 } else if is_block_expr(context, &parent, &parent_rewrite) {
573 match context.config.indent_style() {
574 // Try to put the first child on the same line with parent's last line
575 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
576 // The parent is a block, so align the rest of the chain with the closing
578 IndentStyle::Visual => (parent_shape, false),
582 chain_indent(context, shape.add_offset(parent_rewrite.len())),
588 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
590 chain_indent(context, shape.add_offset(parent_rewrite.len())),
591 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
593 } else if is_block_expr(context, &parent, &parent_rewrite) {
594 match context.config.indent_style() {
595 // Try to put the first child on the same line with parent's last line
596 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
597 // The parent is a block, so align the rest of the chain with the closing
599 IndentStyle::Visual => (parent_shape, false),
603 chain_indent(context, shape.add_offset(parent_rewrite.len())),
607 assert!(test_format_inner(format_code_block, code_block, expected));