1 #![deny(rust_2018_idioms)]
2 #![warn(unreachable_pub)]
5 extern crate derive_new;
8 extern crate lazy_static;
12 use std::cell::RefCell;
13 use std::collections::HashMap;
15 use std::io::{self, Write};
18 use std::path::PathBuf;
23 use syntax::{ast, parse::DirectoryOwnership};
25 use crate::comment::LineClasses;
26 use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
27 use crate::issues::Issue;
28 use crate::shape::Indent;
29 use crate::utils::indent_next_line;
31 pub use crate::config::{
32 load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
36 pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
38 pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
48 pub(crate) mod checkstyle;
51 pub(crate) mod config;
53 mod format_report_formatter;
54 pub(crate) mod formatting;
63 pub(crate) mod modules;
69 pub(crate) mod rustfmt_diff;
71 pub(crate) mod source_file;
72 pub(crate) mod source_map;
79 pub(crate) mod visitor;
81 /// The various errors that can occur during formatting. Note that not all of
82 /// these can currently be propagated to clients.
83 #[derive(Fail, Debug)]
85 /// Line has exceeded character limit (found, maximum).
87 display = "line formatted, but exceeded maximum width \
88 (maximum: {} (see `max_width` option), found: {})",
91 LineOverflow(usize, usize),
92 /// Line ends in whitespace.
93 #[fail(display = "left behind trailing whitespace")]
95 /// TODO or FIXME item without an issue number.
96 #[fail(display = "found {}", _0)]
98 /// License check has failed.
99 #[fail(display = "license check failed")]
101 /// Used deprecated skip attribute.
102 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
104 /// Used a rustfmt:: attribute other than skip or skip::macros.
105 #[fail(display = "invalid attribute")]
107 /// An io error during reading or writing.
108 #[fail(display = "io error: {}", _0)]
110 /// Parse error occurred when parsing the input.
111 #[fail(display = "parse error")]
113 /// The user mandated a version and the current version of Rustfmt does not
114 /// satisfy that requirement.
115 #[fail(display = "version mismatch")]
117 /// If we had formatted the given node, then we would have lost a comment.
118 #[fail(display = "not formatted because a comment would be lost")]
120 /// Invalid glob pattern in `ignore` configuration option.
121 #[fail(display = "Invalid glob pattern found in ignore list: {}", _0)]
122 InvalidGlobPattern(ignore::Error),
126 fn is_comment(&self) -> bool {
128 ErrorKind::LostComment => true,
134 impl From<io::Error> for ErrorKind {
135 fn from(e: io::Error) -> ErrorKind {
136 ErrorKind::IoError(e)
140 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
141 /// i.e., that got returned as they were originally.
143 struct FormattedSnippet {
145 non_formatted_ranges: Vec<(usize, usize)>,
148 impl FormattedSnippet {
149 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
150 /// non-formatted code.
151 fn unwrap_code_block(&mut self) {
152 self.non_formatted_ranges
154 .for_each(|(low, high)| {
160 /// Returns `true` if the line n did not get formatted.
161 fn is_line_non_formatted(&self, n: usize) -> bool {
162 self.non_formatted_ranges
164 .any(|(low, high)| *low <= n && n <= *high)
168 /// Reports on any issues that occurred during a run of Rustfmt.
170 /// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
172 pub struct FormatReport {
173 // Maps stringified file paths to their associated formatting errors.
174 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
175 non_formatted_ranges: Vec<(usize, usize)>,
179 fn new() -> FormatReport {
181 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
182 non_formatted_ranges: Vec::new(),
186 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
187 self.non_formatted_ranges.append(&mut ranges);
190 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
191 self.track_errors(&v);
196 .and_modify(|fe| fe.append(&mut v))
200 fn track_errors(&self, new_errors: &[FormattingError]) {
201 let errs = &mut self.internal.borrow_mut().1;
202 if !new_errors.is_empty() {
203 errs.has_formatting_errors = true;
205 if errs.has_operational_errors && errs.has_check_errors {
208 for err in new_errors {
210 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
211 errs.has_operational_errors = true;
213 ErrorKind::BadIssue(_)
214 | ErrorKind::LicenseCheck
215 | ErrorKind::DeprecatedAttr
217 | ErrorKind::VersionMismatch => {
218 errs.has_check_errors = true;
225 fn add_diff(&mut self) {
226 self.internal.borrow_mut().1.has_diff = true;
229 fn add_macro_format_failure(&mut self) {
230 self.internal.borrow_mut().1.has_macro_format_failure = true;
233 fn add_parsing_error(&mut self) {
234 self.internal.borrow_mut().1.has_parsing_errors = true;
237 fn warning_count(&self) -> usize {
242 .map(|(_, errors)| errors.len())
246 /// Whether any warnings or errors are present in the report.
247 pub fn has_warnings(&self) -> bool {
248 self.internal.borrow().1.has_formatting_errors
251 /// Print the report to a terminal using colours and potentially other
253 #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
256 mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
257 ) -> Result<(), term::Error> {
261 FormatReportFormatterBuilder::new(&self)
269 #[deprecated(note = "Use FormatReportFormatter instead")]
270 impl fmt::Display for FormatReport {
271 // Prints all the formatting errors.
272 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
273 write!(fmt, "{}", FormatReportFormatterBuilder::new(&self).build())?;
278 /// Format the given snippet. The snippet is expected to be *complete* code.
279 /// When we cannot parse the given snippet, this function returns `None`.
280 fn format_snippet(snippet: &str, config: &Config) -> Option<FormattedSnippet> {
281 let mut config = config.clone();
282 panic::catch_unwind(|| {
283 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
284 config.set().emit_mode(config::EmitMode::Stdout);
285 config.set().verbose(Verbosity::Quiet);
286 config.set().hide_parse_errors(true);
288 let (formatting_error, result) = {
289 let input = Input::Text(snippet.into());
290 let mut session = Session::new(config, Some(&mut out));
291 let result = session.format(input);
293 session.errors.has_macro_format_failure
294 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
299 if formatting_error {
302 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
304 non_formatted_ranges: result.unwrap().non_formatted_ranges,
308 // Discard panics encountered while formatting the snippet
309 // The ? operator is needed to remove the extra Option
313 /// Format the given code block. Mainly targeted for code block in comment.
314 /// The code block may be incomplete (i.e., parser may be unable to parse it).
315 /// To avoid panic in parser, we wrap the code block with a dummy function.
316 /// The returned code block does **not** end with newline.
317 fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSnippet> {
318 const FN_MAIN_PREFIX: &str = "fn main() {\n";
320 fn enclose_in_main_block(s: &str, config: &Config) -> String {
321 let indent = Indent::from_width(config, config.tab_spaces());
322 let mut result = String::with_capacity(s.len() * 2);
323 result.push_str(FN_MAIN_PREFIX);
324 let mut need_indent = true;
325 for (kind, line) in LineClasses::new(s) {
327 result.push_str(&indent.to_string(config));
329 result.push_str(&line);
331 need_indent = indent_next_line(kind, &line, config);
337 // Wrap the given code block with `fn main()` if it does not have one.
338 let snippet = enclose_in_main_block(code_snippet, config);
339 let mut result = String::with_capacity(snippet.len());
340 let mut is_first = true;
342 // While formatting the code, ignore the config's newline style setting and always use "\n"
343 // instead of "\r\n" for the newline characters. This is ok because the output here is
344 // not directly outputted by rustfmt command, but used by the comment formatter's input.
345 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
346 let mut config_with_unix_newline = config.clone();
347 config_with_unix_newline
349 .newline_style(NewlineStyle::Unix);
350 let mut formatted = format_snippet(&snippet, &config_with_unix_newline)?;
351 // Remove wrapping main block
352 formatted.unwrap_code_block();
354 // Trim "fn main() {" on the first line and "}" on the last line,
355 // then unindent the whole code block.
356 let block_len = formatted
359 .unwrap_or_else(|| formatted.snippet.len());
360 let mut is_indented = true;
361 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
367 let trimmed_line = if !is_indented {
369 } else if line.len() > config.max_width() {
370 // If there are lines that are larger than max width, we cannot tell
371 // whether we have succeeded but have some comments or strings that
372 // are too long, or we have failed to format code block. We will be
373 // conservative and just return `None` in this case.
375 } else if line.len() > config.tab_spaces() {
376 // Make sure that the line has leading whitespaces.
377 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
378 if line.starts_with(indent_str.as_ref()) {
379 let offset = if config.hard_tabs() {
391 result.push_str(trimmed_line);
392 is_indented = indent_next_line(kind, line, config);
394 Some(FormattedSnippet {
396 non_formatted_ranges: formatted.non_formatted_ranges,
400 /// A session is a run of rustfmt across a single or multiple inputs.
401 pub struct Session<'b, T: Write> {
403 pub out: Option<&'b mut T>,
404 pub(crate) errors: ReportedErrors,
405 source_file: SourceFile,
408 impl<'b, T: Write + 'b> Session<'b, T> {
409 pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
410 if config.emit_mode() == EmitMode::Checkstyle {
411 println!("{}", checkstyle::header());
417 errors: ReportedErrors::default(),
418 source_file: SourceFile::new(),
422 /// The main entry point for Rustfmt. Formats the given input according to the
423 /// given config. `out` is only necessary if required by the configuration.
424 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
425 self.format_input_inner(input)
428 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
430 F: FnOnce(&mut Session<'b, T>) -> U,
432 mem::swap(&mut config, &mut self.config);
433 let result = f(self);
434 mem::swap(&mut config, &mut self.config);
438 pub fn add_operational_error(&mut self) {
439 self.errors.has_operational_errors = true;
442 pub fn has_operational_errors(&self) -> bool {
443 self.errors.has_operational_errors
446 pub fn has_parsing_errors(&self) -> bool {
447 self.errors.has_parsing_errors
450 pub fn has_formatting_errors(&self) -> bool {
451 self.errors.has_formatting_errors
454 pub fn has_check_errors(&self) -> bool {
455 self.errors.has_check_errors
458 pub fn has_diff(&self) -> bool {
462 pub fn has_no_errors(&self) -> bool {
463 !(self.has_operational_errors()
464 || self.has_parsing_errors()
465 || self.has_formatting_errors()
466 || self.has_check_errors()
468 || self.errors.has_macro_format_failure
472 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
474 if self.config.emit_mode() == EmitMode::Checkstyle {
475 println!("{}", checkstyle::footer());
487 fn is_text(&self) -> bool {
489 Input::File(_) => false,
490 Input::Text(_) => true,
494 fn file_name(&self) -> FileName {
496 Input::File(ref file) => FileName::Real(file.clone()),
497 Input::Text(..) => FileName::Stdin,
501 fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
503 Input::File(ref file) => {
504 // If there exists a directory with the same name as an input,
505 // then the input should be parsed as a sub module.
506 let file_stem = file.file_stem()?;
507 if file.parent()?.to_path_buf().join(file_stem).is_dir() {
508 Some(DirectoryOwnership::Owned {
509 relative: file_stem.to_str().map(ast::Ident::from_str),
525 fn test_no_panic_on_format_snippet_and_format_code_block() {
526 // `format_snippet()` and `format_code_block()` should not panic
527 // even when we cannot parse the given snippet.
529 assert!(format_snippet(snippet, &Config::default()).is_none());
530 assert!(format_code_block(snippet, &Config::default()).is_none());
533 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
535 F: Fn(&str, &Config) -> Option<FormattedSnippet>,
537 let output = formatter(input, &Config::default());
538 output.is_some() && output.unwrap().snippet == expected
542 fn test_format_snippet() {
543 let snippet = "fn main() { println!(\"hello, world\"); }";
545 let expected = "fn main() {\n \
546 println!(\"hello, world\");\n\
549 let expected = "fn main() {\r\n \
550 println!(\"hello, world\");\r\n\
552 assert!(test_format_inner(format_snippet, snippet, expected));
556 fn test_format_code_block_fail() {
558 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
559 assert!(format_code_block(code_block, &Config::default()).is_none());
563 fn test_format_code_block() {
565 let code_block = "let x=3;";
566 let expected = "let x = 3;";
567 assert!(test_format_inner(format_code_block, code_block, expected));
569 // more complex code block, taken from chains.rs.
571 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
573 chain_indent(context, shape.add_offset(parent_rewrite.len())),
574 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
576 } else if is_block_expr(context, &parent, &parent_rewrite) {
577 match context.config.indent_style() {
578 // Try to put the first child on the same line with parent's last line
579 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
580 // The parent is a block, so align the rest of the chain with the closing
582 IndentStyle::Visual => (parent_shape, false),
586 chain_indent(context, shape.add_offset(parent_rewrite.len())),
592 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
594 chain_indent(context, shape.add_offset(parent_rewrite.len())),
595 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
597 } else if is_block_expr(context, &parent, &parent_rewrite) {
598 match context.config.indent_style() {
599 // Try to put the first child on the same line with parent's last line
600 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
601 // The parent is a block, so align the rest of the chain with the closing
603 IndentStyle::Visual => (parent_shape, false),
607 chain_indent(context, shape.add_offset(parent_rewrite.len())),
611 assert!(test_format_inner(format_code_block, code_block, expected));