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, DUMMY_SP};
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 const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
100 kind: ast::VisibilityKind::Inherited,
104 /// The various errors that can occur during formatting. Note that not all of
105 /// these can currently be propagated to clients.
106 #[derive(Error, Debug)]
108 /// Line has exceeded character limit (found, maximum).
110 "line formatted, but exceeded maximum width \
111 (maximum: {1} (see `max_width` option), found: {0})"
113 LineOverflow(usize, usize),
114 /// Line ends in whitespace.
115 #[error("left behind trailing whitespace")]
117 /// TODO or FIXME item without an issue number.
118 #[error("found {0}")]
120 /// License check has failed.
121 #[error("license check failed")]
123 /// Used deprecated skip attribute.
124 #[error("`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
126 /// Used a rustfmt:: attribute other than skip or skip::macros.
127 #[error("invalid attribute")]
129 /// An io error during reading or writing.
130 #[error("io error: {0}")]
132 /// Error during module resolution.
134 ModuleResolutionError(#[from] ModuleResolutionError),
135 /// Parse error occurred when parsing the input.
136 #[error("parse error")]
138 /// The user mandated a version and the current version of Rustfmt does not
139 /// satisfy that requirement.
140 #[error("version mismatch")]
142 /// If we had formatted the given node, then we would have lost a comment.
143 #[error("not formatted because a comment would be lost")]
145 /// Invalid glob pattern in `ignore` configuration option.
146 #[error("Invalid glob pattern found in ignore list: {0}")]
147 InvalidGlobPattern(ignore::Error),
151 fn is_comment(&self) -> bool {
152 matches!(self, ErrorKind::LostComment)
156 impl From<io::Error> for ErrorKind {
157 fn from(e: io::Error) -> ErrorKind {
158 ErrorKind::IoError(e)
162 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
163 /// i.e., that got returned as they were originally.
165 struct FormattedSnippet {
167 non_formatted_ranges: Vec<(usize, usize)>,
170 impl FormattedSnippet {
171 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
172 /// non-formatted code.
173 fn unwrap_code_block(&mut self) {
174 self.non_formatted_ranges
176 .for_each(|(low, high)| {
182 /// Returns `true` if the line n did not get formatted.
183 fn is_line_non_formatted(&self, n: usize) -> bool {
184 self.non_formatted_ranges
186 .any(|(low, high)| *low <= n && n <= *high)
190 /// Reports on any issues that occurred during a run of Rustfmt.
192 /// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
194 pub struct FormatReport {
195 // Maps stringified file paths to their associated formatting errors.
196 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
197 non_formatted_ranges: Vec<(usize, usize)>,
201 fn new() -> FormatReport {
203 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
204 non_formatted_ranges: Vec::new(),
208 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
209 self.non_formatted_ranges.append(&mut ranges);
212 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
213 self.track_errors(&v);
218 .and_modify(|fe| fe.append(&mut v))
222 fn track_errors(&self, new_errors: &[FormattingError]) {
223 let errs = &mut self.internal.borrow_mut().1;
224 if !new_errors.is_empty() {
225 errs.has_formatting_errors = true;
227 if errs.has_operational_errors && errs.has_check_errors && errs.has_unformatted_code_errors
231 for err in new_errors {
233 ErrorKind::LineOverflow(..) => {
234 errs.has_operational_errors = true;
236 ErrorKind::TrailingWhitespace => {
237 errs.has_operational_errors = true;
238 errs.has_unformatted_code_errors = true;
240 ErrorKind::LostComment => {
241 errs.has_unformatted_code_errors = true;
243 ErrorKind::BadIssue(_)
244 | ErrorKind::LicenseCheck
245 | ErrorKind::DeprecatedAttr
247 | ErrorKind::VersionMismatch => {
248 errs.has_check_errors = true;
255 fn add_diff(&mut self) {
256 self.internal.borrow_mut().1.has_diff = true;
259 fn add_macro_format_failure(&mut self) {
260 self.internal.borrow_mut().1.has_macro_format_failure = true;
263 fn add_parsing_error(&mut self) {
264 self.internal.borrow_mut().1.has_parsing_errors = true;
267 fn warning_count(&self) -> usize {
272 .map(|(_, errors)| errors.len())
276 /// Whether any warnings or errors are present in the report.
277 pub fn has_warnings(&self) -> bool {
278 self.internal.borrow().1.has_formatting_errors
281 /// Print the report to a terminal using colours and potentially other
283 #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
286 mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
287 ) -> Result<(), term::Error> {
291 FormatReportFormatterBuilder::new(&self)
299 /// Deprecated - Use FormatReportFormatter instead
300 // https://github.com/rust-lang/rust/issues/78625
301 // https://github.com/rust-lang/rust/issues/39935
302 impl fmt::Display for FormatReport {
303 // Prints all the formatting errors.
304 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
305 write!(fmt, "{}", FormatReportFormatterBuilder::new(&self).build())?;
310 /// Format the given snippet. The snippet is expected to be *complete* code.
311 /// When we cannot parse the given snippet, this function returns `None`.
312 fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool) -> Option<FormattedSnippet> {
313 let mut config = config.clone();
314 panic::catch_unwind(|| {
315 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
316 config.set().emit_mode(config::EmitMode::Stdout);
317 config.set().verbose(Verbosity::Quiet);
318 config.set().hide_parse_errors(true);
320 config.set().error_on_unformatted(true);
323 let (formatting_error, result) = {
324 let input = Input::Text(snippet.into());
325 let mut session = Session::new(config, Some(&mut out));
326 let result = session.format_input_inner(input, is_macro_def);
328 session.errors.has_macro_format_failure
329 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
331 || (is_macro_def && session.has_unformatted_code_errors()),
335 if formatting_error {
338 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
340 non_formatted_ranges: result.unwrap().non_formatted_ranges,
344 // Discard panics encountered while formatting the snippet
345 // The ? operator is needed to remove the extra Option
349 /// Format the given code block. Mainly targeted for code block in comment.
350 /// The code block may be incomplete (i.e., parser may be unable to parse it).
351 /// To avoid panic in parser, we wrap the code block with a dummy function.
352 /// The returned code block does **not** end with newline.
353 fn format_code_block(
357 ) -> Option<FormattedSnippet> {
358 const FN_MAIN_PREFIX: &str = "fn main() {\n";
360 fn enclose_in_main_block(s: &str, config: &Config) -> String {
361 let indent = Indent::from_width(config, config.tab_spaces());
362 let mut result = String::with_capacity(s.len() * 2);
363 result.push_str(FN_MAIN_PREFIX);
364 let mut need_indent = true;
365 for (kind, line) in LineClasses::new(s) {
367 result.push_str(&indent.to_string(config));
369 result.push_str(&line);
371 need_indent = indent_next_line(kind, &line, config);
377 // Wrap the given code block with `fn main()` if it does not have one.
378 let snippet = enclose_in_main_block(code_snippet, config);
379 let mut result = String::with_capacity(snippet.len());
380 let mut is_first = true;
382 // While formatting the code, ignore the config's newline style setting and always use "\n"
383 // instead of "\r\n" for the newline characters. This is ok because the output here is
384 // not directly outputted by rustfmt command, but used by the comment formatter's input.
385 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
386 let mut config_with_unix_newline = config.clone();
387 config_with_unix_newline
389 .newline_style(NewlineStyle::Unix);
390 let mut formatted = format_snippet(&snippet, &config_with_unix_newline, is_macro_def)?;
391 // Remove wrapping main block
392 formatted.unwrap_code_block();
394 // Trim "fn main() {" on the first line and "}" on the last line,
395 // then unindent the whole code block.
396 let block_len = formatted
399 .unwrap_or_else(|| formatted.snippet.len());
400 let mut is_indented = true;
401 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
402 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
408 let trimmed_line = if !is_indented {
410 } else if line.len() > config.max_width() {
411 // If there are lines that are larger than max width, we cannot tell
412 // whether we have succeeded but have some comments or strings that
413 // are too long, or we have failed to format code block. We will be
414 // conservative and just return `None` in this case.
416 } else if line.len() > indent_str.len() {
417 // Make sure that the line has leading whitespaces.
418 if line.starts_with(indent_str.as_ref()) {
419 let offset = if config.hard_tabs() {
431 result.push_str(trimmed_line);
432 is_indented = indent_next_line(kind, line, config);
434 Some(FormattedSnippet {
436 non_formatted_ranges: formatted.non_formatted_ranges,
440 /// A session is a run of rustfmt across a single or multiple inputs.
441 pub struct Session<'b, T: Write> {
443 pub out: Option<&'b mut T>,
444 pub(crate) errors: ReportedErrors,
445 source_file: SourceFile,
446 emitter: Box<dyn Emitter + 'b>,
449 impl<'b, T: Write + 'b> Session<'b, T> {
450 pub fn new(config: Config, mut out: Option<&'b mut T>) -> Session<'b, T> {
451 let emitter = create_emitter(&config);
453 if let Some(ref mut out) = out {
454 let _ = emitter.emit_header(out);
461 errors: ReportedErrors::default(),
462 source_file: SourceFile::new(),
466 /// The main entry point for Rustfmt. Formats the given input according to the
467 /// given config. `out` is only necessary if required by the configuration.
468 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
469 self.format_input_inner(input, false)
472 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
474 F: FnOnce(&mut Session<'b, T>) -> U,
476 mem::swap(&mut config, &mut self.config);
477 let result = f(self);
478 mem::swap(&mut config, &mut self.config);
482 pub fn add_operational_error(&mut self) {
483 self.errors.has_operational_errors = true;
486 pub fn has_operational_errors(&self) -> bool {
487 self.errors.has_operational_errors
490 pub fn has_parsing_errors(&self) -> bool {
491 self.errors.has_parsing_errors
494 pub fn has_formatting_errors(&self) -> bool {
495 self.errors.has_formatting_errors
498 pub fn has_check_errors(&self) -> bool {
499 self.errors.has_check_errors
502 pub fn has_diff(&self) -> bool {
506 pub fn has_unformatted_code_errors(&self) -> bool {
507 self.errors.has_unformatted_code_errors
510 pub fn has_no_errors(&self) -> bool {
511 !(self.has_operational_errors()
512 || self.has_parsing_errors()
513 || self.has_formatting_errors()
514 || self.has_check_errors()
516 || self.has_unformatted_code_errors()
517 || self.errors.has_macro_format_failure)
521 pub(crate) fn create_emitter<'a>(config: &Config) -> Box<dyn Emitter + 'a> {
522 match config.emit_mode() {
523 EmitMode::Files if config.make_backup() => {
524 Box::new(emitter::FilesWithBackupEmitter::default())
526 EmitMode::Files => Box::new(emitter::FilesEmitter::new(
527 config.print_misformatted_file_names(),
529 EmitMode::Stdout | EmitMode::Coverage => {
530 Box::new(emitter::StdoutEmitter::new(config.verbose()))
532 EmitMode::Json => Box::new(emitter::JsonEmitter::default()),
533 EmitMode::ModifiedLines => Box::new(emitter::ModifiedLinesEmitter::default()),
534 EmitMode::Checkstyle => Box::new(emitter::CheckstyleEmitter::default()),
535 EmitMode::Diff => Box::new(emitter::DiffEmitter::new(config.clone())),
539 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
541 if let Some(ref mut out) = self.out {
542 let _ = self.emitter.emit_footer(out);
554 fn file_name(&self) -> FileName {
556 Input::File(ref file) => FileName::Real(file.clone()),
557 Input::Text(..) => FileName::Stdin,
561 fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
563 Input::File(ref file) => {
564 // If there exists a directory with the same name as an input,
565 // then the input should be parsed as a sub module.
566 let file_stem = file.file_stem()?;
567 if file.parent()?.to_path_buf().join(file_stem).is_dir() {
568 Some(DirectoryOwnership::Owned {
569 relative: file_stem.to_str().map(symbol::Ident::from_str),
585 fn test_no_panic_on_format_snippet_and_format_code_block() {
586 // `format_snippet()` and `format_code_block()` should not panic
587 // even when we cannot parse the given snippet.
589 assert!(format_snippet(snippet, &Config::default(), false).is_none());
590 assert!(format_code_block(snippet, &Config::default(), false).is_none());
593 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
595 F: Fn(&str, &Config, bool) -> Option<FormattedSnippet>,
597 let output = formatter(input, &Config::default(), false);
598 output.is_some() && output.unwrap().snippet == expected
602 fn test_format_snippet() {
603 let snippet = "fn main() { println!(\"hello, world\"); }";
605 let expected = "fn main() {\n \
606 println!(\"hello, world\");\n\
609 let expected = "fn main() {\r\n \
610 println!(\"hello, world\");\r\n\
612 assert!(test_format_inner(format_snippet, snippet, expected));
616 fn test_format_code_block_fail() {
618 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
619 assert!(format_code_block(code_block, &Config::default(), false).is_none());
623 fn test_format_code_block() {
625 let code_block = "let x=3;";
626 let expected = "let x = 3;";
627 assert!(test_format_inner(format_code_block, code_block, expected));
629 // more complex code block, taken from chains.rs.
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())),
652 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
654 chain_indent(context, shape.add_offset(parent_rewrite.len())),
655 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
657 } else if is_block_expr(context, &parent, &parent_rewrite) {
658 match context.config.indent_style() {
659 // Try to put the first child on the same line with parent's last line
660 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
661 // The parent is a block, so align the rest of the chain with the closing
663 IndentStyle::Visual => (parent_shape, false),
667 chain_indent(context, shape.add_offset(parent_rewrite.len())),
671 assert!(test_format_inner(format_code_block, code_block, expected));