1 #![feature(rustc_private)]
2 #![deny(rust_2018_idioms)]
3 #![warn(unreachable_pub)]
4 #![recursion_limit = "256"]
5 #![allow(clippy::match_like_matches_macro)]
8 extern crate derive_new;
11 extern crate lazy_static;
15 // N.B. these crates are loaded from the sysroot, so they need extern crate.
16 extern crate rustc_ast;
17 extern crate rustc_ast_pretty;
18 extern crate rustc_data_structures;
19 extern crate rustc_errors;
20 extern crate rustc_expand;
21 extern crate rustc_parse;
22 extern crate rustc_session;
23 extern crate rustc_span;
25 use std::cell::RefCell;
26 use std::collections::HashMap;
28 use std::io::{self, Write};
31 use std::path::PathBuf;
35 use rustc_span::symbol;
38 use crate::comment::LineClasses;
39 use crate::emitter::Emitter;
40 use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
41 use crate::issues::Issue;
42 use crate::modules::ModuleResolutionError;
43 use crate::shape::Indent;
44 use crate::syntux::parser::DirectoryOwnership;
45 use crate::utils::indent_next_line;
47 pub use crate::config::{
48 load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
52 pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
54 pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
63 pub(crate) mod config;
67 mod format_report_formatter;
68 pub(crate) mod formatting;
77 pub(crate) mod modules;
84 pub(crate) mod rustfmt_diff;
87 pub(crate) mod source_file;
88 pub(crate) mod source_map;
97 pub(crate) mod visitor;
99 /// The various errors that can occur during formatting. Note that not all of
100 /// these can currently be propagated to clients.
101 #[derive(Error, Debug)]
103 /// Line has exceeded character limit (found, maximum).
105 "line formatted, but exceeded maximum width \
106 (maximum: {1} (see `max_width` option), found: {0})"
108 LineOverflow(usize, usize),
109 /// Line ends in whitespace.
110 #[error("left behind trailing whitespace")]
112 /// TODO or FIXME item without an issue number.
113 #[error("found {0}")]
115 /// License check has failed.
116 #[error("license check failed")]
118 /// Used deprecated skip attribute.
119 #[error("`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
121 /// Used a rustfmt:: attribute other than skip or skip::macros.
122 #[error("invalid attribute")]
124 /// An io error during reading or writing.
125 #[error("io error: {0}")]
127 /// Error during module resolution.
129 ModuleResolutionError(#[from] ModuleResolutionError),
130 /// Parse error occurred when parsing the input.
131 #[error("parse error")]
133 /// The user mandated a version and the current version of Rustfmt does not
134 /// satisfy that requirement.
135 #[error("version mismatch")]
137 /// If we had formatted the given node, then we would have lost a comment.
138 #[error("not formatted because a comment would be lost")]
140 /// Invalid glob pattern in `ignore` configuration option.
141 #[error("Invalid glob pattern found in ignore list: {0}")]
142 InvalidGlobPattern(ignore::Error),
146 fn is_comment(&self) -> bool {
147 matches!(self, ErrorKind::LostComment)
151 impl From<io::Error> for ErrorKind {
152 fn from(e: io::Error) -> ErrorKind {
153 ErrorKind::IoError(e)
157 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
158 /// i.e., that got returned as they were originally.
160 struct FormattedSnippet {
162 non_formatted_ranges: Vec<(usize, usize)>,
165 impl FormattedSnippet {
166 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
167 /// non-formatted code.
168 fn unwrap_code_block(&mut self) {
169 self.non_formatted_ranges
171 .for_each(|(low, high)| {
177 /// Returns `true` if the line n did not get formatted.
178 fn is_line_non_formatted(&self, n: usize) -> bool {
179 self.non_formatted_ranges
181 .any(|(low, high)| *low <= n && n <= *high)
185 /// Reports on any issues that occurred during a run of Rustfmt.
187 /// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
189 pub struct FormatReport {
190 // Maps stringified file paths to their associated formatting errors.
191 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
192 non_formatted_ranges: Vec<(usize, usize)>,
196 fn new() -> FormatReport {
198 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
199 non_formatted_ranges: Vec::new(),
203 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
204 self.non_formatted_ranges.append(&mut ranges);
207 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
208 self.track_errors(&v);
213 .and_modify(|fe| fe.append(&mut v))
217 fn track_errors(&self, new_errors: &[FormattingError]) {
218 let errs = &mut self.internal.borrow_mut().1;
219 if !new_errors.is_empty() {
220 errs.has_formatting_errors = true;
222 if errs.has_operational_errors && errs.has_check_errors && errs.has_unformatted_code_errors
226 for err in new_errors {
228 ErrorKind::LineOverflow(..) => {
229 errs.has_operational_errors = true;
231 ErrorKind::TrailingWhitespace => {
232 errs.has_operational_errors = true;
233 errs.has_unformatted_code_errors = true;
235 ErrorKind::LostComment => {
236 errs.has_unformatted_code_errors = true;
238 ErrorKind::BadIssue(_)
239 | ErrorKind::LicenseCheck
240 | ErrorKind::DeprecatedAttr
242 | ErrorKind::VersionMismatch => {
243 errs.has_check_errors = true;
250 fn add_diff(&mut self) {
251 self.internal.borrow_mut().1.has_diff = true;
254 fn add_macro_format_failure(&mut self) {
255 self.internal.borrow_mut().1.has_macro_format_failure = true;
258 fn add_parsing_error(&mut self) {
259 self.internal.borrow_mut().1.has_parsing_errors = true;
262 fn warning_count(&self) -> usize {
267 .map(|(_, errors)| errors.len())
271 /// Whether any warnings or errors are present in the report.
272 pub fn has_warnings(&self) -> bool {
273 self.internal.borrow().1.has_formatting_errors
276 /// Print the report to a terminal using colours and potentially other
278 #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
281 mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
282 ) -> Result<(), term::Error> {
286 FormatReportFormatterBuilder::new(self)
294 /// Deprecated - Use FormatReportFormatter instead
295 // https://github.com/rust-lang/rust/issues/78625
296 // https://github.com/rust-lang/rust/issues/39935
297 impl fmt::Display for FormatReport {
298 // Prints all the formatting errors.
299 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
300 write!(fmt, "{}", FormatReportFormatterBuilder::new(self).build())?;
305 /// Format the given snippet. The snippet is expected to be *complete* code.
306 /// When we cannot parse the given snippet, this function returns `None`.
307 fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool) -> Option<FormattedSnippet> {
308 let mut config = config.clone();
309 panic::catch_unwind(|| {
310 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
311 config.set().emit_mode(config::EmitMode::Stdout);
312 config.set().verbose(Verbosity::Quiet);
313 config.set().hide_parse_errors(true);
315 config.set().error_on_unformatted(true);
318 let (formatting_error, result) = {
319 let input = Input::Text(snippet.into());
320 let mut session = Session::new(config, Some(&mut out));
321 let result = session.format_input_inner(input, is_macro_def);
323 session.errors.has_macro_format_failure
324 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
326 || (is_macro_def && session.has_unformatted_code_errors()),
330 if formatting_error {
333 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
335 non_formatted_ranges: result.unwrap().non_formatted_ranges,
339 // Discard panics encountered while formatting the snippet
340 // The ? operator is needed to remove the extra Option
344 /// Format the given code block. Mainly targeted for code block in comment.
345 /// The code block may be incomplete (i.e., parser may be unable to parse it).
346 /// To avoid panic in parser, we wrap the code block with a dummy function.
347 /// The returned code block does **not** end with newline.
348 fn format_code_block(
352 ) -> Option<FormattedSnippet> {
353 const FN_MAIN_PREFIX: &str = "fn main() {\n";
355 fn enclose_in_main_block(s: &str, config: &Config) -> String {
356 let indent = Indent::from_width(config, config.tab_spaces());
357 let mut result = String::with_capacity(s.len() * 2);
358 result.push_str(FN_MAIN_PREFIX);
359 let mut need_indent = true;
360 for (kind, line) in LineClasses::new(s) {
362 result.push_str(&indent.to_string(config));
364 result.push_str(&line);
366 need_indent = indent_next_line(kind, &line, config);
372 // Wrap the given code block with `fn main()` if it does not have one.
373 let snippet = enclose_in_main_block(code_snippet, config);
374 let mut result = String::with_capacity(snippet.len());
375 let mut is_first = true;
377 // While formatting the code, ignore the config's newline style setting and always use "\n"
378 // instead of "\r\n" for the newline characters. This is ok because the output here is
379 // not directly outputted by rustfmt command, but used by the comment formatter's input.
380 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
381 let mut config_with_unix_newline = config.clone();
382 config_with_unix_newline
384 .newline_style(NewlineStyle::Unix);
385 let mut formatted = format_snippet(&snippet, &config_with_unix_newline, is_macro_def)?;
386 // Remove wrapping main block
387 formatted.unwrap_code_block();
389 // Trim "fn main() {" on the first line and "}" on the last line,
390 // then unindent the whole code block.
391 let block_len = formatted
394 .unwrap_or_else(|| formatted.snippet.len());
395 let mut is_indented = true;
396 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
397 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
403 let trimmed_line = if !is_indented {
405 } else if line.len() > config.max_width() {
406 // If there are lines that are larger than max width, we cannot tell
407 // whether we have succeeded but have some comments or strings that
408 // are too long, or we have failed to format code block. We will be
409 // conservative and just return `None` in this case.
411 } else if line.len() > indent_str.len() {
412 // Make sure that the line has leading whitespaces.
413 if line.starts_with(indent_str.as_ref()) {
414 let offset = if config.hard_tabs() {
426 result.push_str(trimmed_line);
427 is_indented = indent_next_line(kind, line, config);
429 Some(FormattedSnippet {
431 non_formatted_ranges: formatted.non_formatted_ranges,
435 /// A session is a run of rustfmt across a single or multiple inputs.
436 pub struct Session<'b, T: Write> {
438 pub out: Option<&'b mut T>,
439 pub(crate) errors: ReportedErrors,
440 source_file: SourceFile,
441 emitter: Box<dyn Emitter + 'b>,
444 impl<'b, T: Write + 'b> Session<'b, T> {
445 pub fn new(config: Config, mut out: Option<&'b mut T>) -> Session<'b, T> {
446 let emitter = create_emitter(&config);
448 if let Some(ref mut out) = out {
449 let _ = emitter.emit_header(out);
456 errors: ReportedErrors::default(),
457 source_file: SourceFile::new(),
461 /// The main entry point for Rustfmt. Formats the given input according to the
462 /// given config. `out` is only necessary if required by the configuration.
463 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
464 self.format_input_inner(input, false)
467 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
469 F: FnOnce(&mut Session<'b, T>) -> U,
471 mem::swap(&mut config, &mut self.config);
472 let result = f(self);
473 mem::swap(&mut config, &mut self.config);
477 pub fn add_operational_error(&mut self) {
478 self.errors.has_operational_errors = true;
481 pub fn has_operational_errors(&self) -> bool {
482 self.errors.has_operational_errors
485 pub fn has_parsing_errors(&self) -> bool {
486 self.errors.has_parsing_errors
489 pub fn has_formatting_errors(&self) -> bool {
490 self.errors.has_formatting_errors
493 pub fn has_check_errors(&self) -> bool {
494 self.errors.has_check_errors
497 pub fn has_diff(&self) -> bool {
501 pub fn has_unformatted_code_errors(&self) -> bool {
502 self.errors.has_unformatted_code_errors
505 pub fn has_no_errors(&self) -> bool {
506 !(self.has_operational_errors()
507 || self.has_parsing_errors()
508 || self.has_formatting_errors()
509 || self.has_check_errors()
511 || self.has_unformatted_code_errors()
512 || self.errors.has_macro_format_failure)
516 pub(crate) fn create_emitter<'a>(config: &Config) -> Box<dyn Emitter + 'a> {
517 match config.emit_mode() {
518 EmitMode::Files if config.make_backup() => {
519 Box::new(emitter::FilesWithBackupEmitter::default())
521 EmitMode::Files => Box::new(emitter::FilesEmitter::new(
522 config.print_misformatted_file_names(),
524 EmitMode::Stdout | EmitMode::Coverage => {
525 Box::new(emitter::StdoutEmitter::new(config.verbose()))
527 EmitMode::Json => Box::new(emitter::JsonEmitter::default()),
528 EmitMode::ModifiedLines => Box::new(emitter::ModifiedLinesEmitter::default()),
529 EmitMode::Checkstyle => Box::new(emitter::CheckstyleEmitter::default()),
530 EmitMode::Diff => Box::new(emitter::DiffEmitter::new(config.clone())),
534 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
536 if let Some(ref mut out) = self.out {
537 let _ = self.emitter.emit_footer(out);
549 fn file_name(&self) -> FileName {
551 Input::File(ref file) => FileName::Real(file.clone()),
552 Input::Text(..) => FileName::Stdin,
556 fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
558 Input::File(ref file) => {
559 // If there exists a directory with the same name as an input,
560 // then the input should be parsed as a sub module.
561 let file_stem = file.file_stem()?;
562 if file.parent()?.to_path_buf().join(file_stem).is_dir() {
563 Some(DirectoryOwnership::Owned {
564 relative: file_stem.to_str().map(symbol::Ident::from_str),
580 fn test_no_panic_on_format_snippet_and_format_code_block() {
581 // `format_snippet()` and `format_code_block()` should not panic
582 // even when we cannot parse the given snippet.
584 assert!(format_snippet(snippet, &Config::default(), false).is_none());
585 assert!(format_code_block(snippet, &Config::default(), false).is_none());
588 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
590 F: Fn(&str, &Config, bool) -> Option<FormattedSnippet>,
592 let output = formatter(input, &Config::default(), false);
593 output.is_some() && output.unwrap().snippet == expected
597 fn test_format_snippet() {
598 let snippet = "fn main() { println!(\"hello, world\"); }";
600 let expected = "fn main() {\n \
601 println!(\"hello, world\");\n\
604 let expected = "fn main() {\r\n \
605 println!(\"hello, world\");\r\n\
607 assert!(test_format_inner(format_snippet, snippet, expected));
611 fn test_format_code_block_fail() {
613 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
614 assert!(format_code_block(code_block, &Config::default(), false).is_none());
618 fn test_format_code_block() {
620 let code_block = "let x=3;";
621 let expected = "let x = 3;";
622 assert!(test_format_inner(format_code_block, code_block, expected));
624 // more complex code block, taken from chains.rs.
626 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
628 chain_indent(context, shape.add_offset(parent_rewrite.len())),
629 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
631 } else if is_block_expr(context, &parent, &parent_rewrite) {
632 match context.config.indent_style() {
633 // Try to put the first child on the same line with parent's last line
634 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
635 // The parent is a block, so align the rest of the chain with the closing
637 IndentStyle::Visual => (parent_shape, false),
641 chain_indent(context, shape.add_offset(parent_rewrite.len())),
647 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
649 chain_indent(context, shape.add_offset(parent_rewrite.len())),
650 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
652 } else if is_block_expr(context, &parent, &parent_rewrite) {
653 match context.config.indent_style() {
654 // Try to put the first child on the same line with parent's last line
655 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
656 // The parent is a block, so align the rest of the chain with the closing
658 IndentStyle::Visual => (parent_shape, false),
662 chain_indent(context, shape.add_offset(parent_rewrite.len())),
666 assert!(test_format_inner(format_code_block, code_block, expected));