1 #![feature(rustc_private)]
2 #![deny(rust_2018_idioms)]
3 #![warn(unreachable_pub)]
6 extern crate derive_new;
9 extern crate lazy_static;
13 // N.B. these crates are loaded from the sysroot, so they need extern crate.
14 extern crate rustc_ast;
15 extern crate rustc_ast_pretty;
16 extern crate rustc_data_structures;
17 extern crate rustc_errors;
18 extern crate rustc_expand;
19 extern crate rustc_parse;
20 extern crate rustc_session;
21 extern crate rustc_span;
23 use std::cell::RefCell;
24 use std::collections::HashMap;
26 use std::io::{self, Write};
29 use std::path::PathBuf;
34 use rustc_span::{symbol, DUMMY_SP};
37 use crate::comment::LineClasses;
38 use crate::emitter::Emitter;
39 use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
40 use crate::issues::Issue;
41 use crate::modules::ModuleResolutionError;
42 use crate::shape::Indent;
43 use crate::syntux::parser::DirectoryOwnership;
44 use crate::utils::indent_next_line;
46 pub use crate::config::{
47 load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
51 pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
53 pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
62 pub(crate) mod config;
66 mod format_report_formatter;
67 pub(crate) mod formatting;
76 pub(crate) mod modules;
83 pub(crate) mod rustfmt_diff;
86 pub(crate) mod source_file;
87 pub(crate) mod source_map;
96 pub(crate) mod visitor;
98 const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
99 kind: ast::VisibilityKind::Inherited,
103 /// The various errors that can occur during formatting. Note that not all of
104 /// these can currently be propagated to clients.
105 #[derive(Error, Debug)]
107 /// Line has exceeded character limit (found, maximum).
109 "line formatted, but exceeded maximum width \
110 (maximum: {1} (see `max_width` option), found: {0})"
112 LineOverflow(usize, usize),
113 /// Line ends in whitespace.
114 #[error("left behind trailing whitespace")]
116 /// TODO or FIXME item without an issue number.
117 #[error("found {0}")]
119 /// License check has failed.
120 #[error("license check failed")]
122 /// Used deprecated skip attribute.
123 #[error("`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
125 /// Used a rustfmt:: attribute other than skip or skip::macros.
126 #[error("invalid attribute")]
128 /// An io error during reading or writing.
129 #[error("io error: {0}")]
131 /// Error during module resolution.
133 ModuleResolutionError(#[from] ModuleResolutionError),
134 /// Parse error occurred when parsing the input.
135 #[error("parse error")]
137 /// The user mandated a version and the current version of Rustfmt does not
138 /// satisfy that requirement.
139 #[error("version mismatch")]
141 /// If we had formatted the given node, then we would have lost a comment.
142 #[error("not formatted because a comment would be lost")]
144 /// Invalid glob pattern in `ignore` configuration option.
145 #[error("Invalid glob pattern found in ignore list: {0}")]
146 InvalidGlobPattern(ignore::Error),
150 fn is_comment(&self) -> bool {
152 ErrorKind::LostComment => true,
158 impl From<io::Error> for ErrorKind {
159 fn from(e: io::Error) -> ErrorKind {
160 ErrorKind::IoError(e)
164 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
165 /// i.e., that got returned as they were originally.
167 struct FormattedSnippet {
169 non_formatted_ranges: Vec<(usize, usize)>,
172 impl FormattedSnippet {
173 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
174 /// non-formatted code.
175 fn unwrap_code_block(&mut self) {
176 self.non_formatted_ranges
178 .for_each(|(low, high)| {
184 /// Returns `true` if the line n did not get formatted.
185 fn is_line_non_formatted(&self, n: usize) -> bool {
186 self.non_formatted_ranges
188 .any(|(low, high)| *low <= n && n <= *high)
192 /// Reports on any issues that occurred during a run of Rustfmt.
194 /// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
196 pub struct FormatReport {
197 // Maps stringified file paths to their associated formatting errors.
198 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
199 non_formatted_ranges: Vec<(usize, usize)>,
203 fn new() -> FormatReport {
205 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
206 non_formatted_ranges: Vec::new(),
210 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
211 self.non_formatted_ranges.append(&mut ranges);
214 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
215 self.track_errors(&v);
220 .and_modify(|fe| fe.append(&mut v))
224 fn track_errors(&self, new_errors: &[FormattingError]) {
225 let errs = &mut self.internal.borrow_mut().1;
226 if !new_errors.is_empty() {
227 errs.has_formatting_errors = true;
229 if errs.has_operational_errors && errs.has_check_errors && errs.has_unformatted_code_errors
233 for err in new_errors {
235 ErrorKind::LineOverflow(..) => {
236 errs.has_operational_errors = true;
238 ErrorKind::TrailingWhitespace => {
239 errs.has_operational_errors = true;
240 errs.has_unformatted_code_errors = true;
242 ErrorKind::LostComment => {
243 errs.has_unformatted_code_errors = true;
245 ErrorKind::BadIssue(_)
246 | ErrorKind::LicenseCheck
247 | ErrorKind::DeprecatedAttr
249 | ErrorKind::VersionMismatch => {
250 errs.has_check_errors = true;
257 fn add_diff(&mut self) {
258 self.internal.borrow_mut().1.has_diff = true;
261 fn add_macro_format_failure(&mut self) {
262 self.internal.borrow_mut().1.has_macro_format_failure = true;
265 fn add_parsing_error(&mut self) {
266 self.internal.borrow_mut().1.has_parsing_errors = true;
269 fn warning_count(&self) -> usize {
274 .map(|(_, errors)| errors.len())
278 /// Whether any warnings or errors are present in the report.
279 pub fn has_warnings(&self) -> bool {
280 self.internal.borrow().1.has_formatting_errors
283 /// Print the report to a terminal using colours and potentially other
285 #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
288 mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
289 ) -> Result<(), term::Error> {
293 FormatReportFormatterBuilder::new(&self)
301 /// Deprecated - Use FormatReportFormatter instead
302 // https://github.com/rust-lang/rust/issues/78625
303 // https://github.com/rust-lang/rust/issues/39935
304 impl fmt::Display for FormatReport {
305 // Prints all the formatting errors.
306 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
307 write!(fmt, "{}", FormatReportFormatterBuilder::new(&self).build())?;
312 /// Format the given snippet. The snippet is expected to be *complete* code.
313 /// When we cannot parse the given snippet, this function returns `None`.
314 fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool) -> Option<FormattedSnippet> {
315 let mut config = config.clone();
316 panic::catch_unwind(|| {
317 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
318 config.set().emit_mode(config::EmitMode::Stdout);
319 config.set().verbose(Verbosity::Quiet);
320 config.set().hide_parse_errors(true);
322 config.set().error_on_unformatted(true);
325 let (formatting_error, result) = {
326 let input = Input::Text(snippet.into());
327 let mut session = Session::new(config, Some(&mut out));
328 let result = session.format_input_inner(input, is_macro_def);
330 session.errors.has_macro_format_failure
331 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
333 || (is_macro_def && session.has_unformatted_code_errors()),
337 if formatting_error {
340 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
342 non_formatted_ranges: result.unwrap().non_formatted_ranges,
346 // Discard panics encountered while formatting the snippet
347 // The ? operator is needed to remove the extra Option
351 /// Format the given code block. Mainly targeted for code block in comment.
352 /// The code block may be incomplete (i.e., parser may be unable to parse it).
353 /// To avoid panic in parser, we wrap the code block with a dummy function.
354 /// The returned code block does **not** end with newline.
355 fn format_code_block(
359 ) -> Option<FormattedSnippet> {
360 const FN_MAIN_PREFIX: &str = "fn main() {\n";
362 fn enclose_in_main_block(s: &str, config: &Config) -> String {
363 let indent = Indent::from_width(config, config.tab_spaces());
364 let mut result = String::with_capacity(s.len() * 2);
365 result.push_str(FN_MAIN_PREFIX);
366 let mut need_indent = true;
367 for (kind, line) in LineClasses::new(s) {
369 result.push_str(&indent.to_string(config));
371 result.push_str(&line);
373 need_indent = indent_next_line(kind, &line, config);
379 // Wrap the given code block with `fn main()` if it does not have one.
380 let snippet = enclose_in_main_block(code_snippet, config);
381 let mut result = String::with_capacity(snippet.len());
382 let mut is_first = true;
384 // While formatting the code, ignore the config's newline style setting and always use "\n"
385 // instead of "\r\n" for the newline characters. This is ok because the output here is
386 // not directly outputted by rustfmt command, but used by the comment formatter's input.
387 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
388 let mut config_with_unix_newline = config.clone();
389 config_with_unix_newline
391 .newline_style(NewlineStyle::Unix);
392 let mut formatted = format_snippet(&snippet, &config_with_unix_newline, is_macro_def)?;
393 // Remove wrapping main block
394 formatted.unwrap_code_block();
396 // Trim "fn main() {" on the first line and "}" on the last line,
397 // then unindent the whole code block.
398 let block_len = formatted
401 .unwrap_or_else(|| formatted.snippet.len());
402 let mut is_indented = true;
403 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
404 for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
410 let trimmed_line = if !is_indented {
412 } else if line.len() > config.max_width() {
413 // If there are lines that are larger than max width, we cannot tell
414 // whether we have succeeded but have some comments or strings that
415 // are too long, or we have failed to format code block. We will be
416 // conservative and just return `None` in this case.
418 } else if line.len() > indent_str.len() {
419 // Make sure that the line has leading whitespaces.
420 if line.starts_with(indent_str.as_ref()) {
421 let offset = if config.hard_tabs() {
433 result.push_str(trimmed_line);
434 is_indented = indent_next_line(kind, line, config);
436 Some(FormattedSnippet {
438 non_formatted_ranges: formatted.non_formatted_ranges,
442 /// A session is a run of rustfmt across a single or multiple inputs.
443 pub struct Session<'b, T: Write> {
445 pub out: Option<&'b mut T>,
446 pub(crate) errors: ReportedErrors,
447 source_file: SourceFile,
448 emitter: Box<dyn Emitter + 'b>,
451 impl<'b, T: Write + 'b> Session<'b, T> {
452 pub fn new(config: Config, mut out: Option<&'b mut T>) -> Session<'b, T> {
453 let emitter = create_emitter(&config);
455 if let Some(ref mut out) = out {
456 let _ = emitter.emit_header(out);
463 errors: ReportedErrors::default(),
464 source_file: SourceFile::new(),
468 /// The main entry point for Rustfmt. Formats the given input according to the
469 /// given config. `out` is only necessary if required by the configuration.
470 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
471 self.format_input_inner(input, false)
474 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
476 F: FnOnce(&mut Session<'b, T>) -> U,
478 mem::swap(&mut config, &mut self.config);
479 let result = f(self);
480 mem::swap(&mut config, &mut self.config);
484 pub fn add_operational_error(&mut self) {
485 self.errors.has_operational_errors = true;
488 pub fn has_operational_errors(&self) -> bool {
489 self.errors.has_operational_errors
492 pub fn has_parsing_errors(&self) -> bool {
493 self.errors.has_parsing_errors
496 pub fn has_formatting_errors(&self) -> bool {
497 self.errors.has_formatting_errors
500 pub fn has_check_errors(&self) -> bool {
501 self.errors.has_check_errors
504 pub fn has_diff(&self) -> bool {
508 pub fn has_unformatted_code_errors(&self) -> bool {
509 self.errors.has_unformatted_code_errors
512 pub fn has_no_errors(&self) -> bool {
513 !(self.has_operational_errors()
514 || self.has_parsing_errors()
515 || self.has_formatting_errors()
516 || self.has_check_errors()
518 || self.has_unformatted_code_errors()
519 || self.errors.has_macro_format_failure)
523 pub(crate) fn create_emitter<'a>(config: &Config) -> Box<dyn Emitter + 'a> {
524 match config.emit_mode() {
525 EmitMode::Files if config.make_backup() => {
526 Box::new(emitter::FilesWithBackupEmitter::default())
528 EmitMode::Files => Box::new(emitter::FilesEmitter::new(
529 config.print_misformatted_file_names(),
531 EmitMode::Stdout | EmitMode::Coverage => {
532 Box::new(emitter::StdoutEmitter::new(config.verbose()))
534 EmitMode::Json => Box::new(emitter::JsonEmitter::default()),
535 EmitMode::ModifiedLines => Box::new(emitter::ModifiedLinesEmitter::default()),
536 EmitMode::Checkstyle => Box::new(emitter::CheckstyleEmitter::default()),
537 EmitMode::Diff => Box::new(emitter::DiffEmitter::new(config.clone())),
541 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
543 if let Some(ref mut out) = self.out {
544 let _ = self.emitter.emit_footer(out);
556 fn file_name(&self) -> FileName {
558 Input::File(ref file) => FileName::Real(file.clone()),
559 Input::Text(..) => FileName::Stdin,
563 fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
565 Input::File(ref file) => {
566 // If there exists a directory with the same name as an input,
567 // then the input should be parsed as a sub module.
568 let file_stem = file.file_stem()?;
569 if file.parent()?.to_path_buf().join(file_stem).is_dir() {
570 Some(DirectoryOwnership::Owned {
571 relative: file_stem.to_str().map(symbol::Ident::from_str),
587 fn test_no_panic_on_format_snippet_and_format_code_block() {
588 // `format_snippet()` and `format_code_block()` should not panic
589 // even when we cannot parse the given snippet.
591 assert!(format_snippet(snippet, &Config::default(), false).is_none());
592 assert!(format_code_block(snippet, &Config::default(), false).is_none());
595 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
597 F: Fn(&str, &Config, bool) -> Option<FormattedSnippet>,
599 let output = formatter(input, &Config::default(), false);
600 output.is_some() && output.unwrap().snippet == expected
604 fn test_format_snippet() {
605 let snippet = "fn main() { println!(\"hello, world\"); }";
607 let expected = "fn main() {\n \
608 println!(\"hello, world\");\n\
611 let expected = "fn main() {\r\n \
612 println!(\"hello, world\");\r\n\
614 assert!(test_format_inner(format_snippet, snippet, expected));
618 fn test_format_code_block_fail() {
620 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
621 assert!(format_code_block(code_block, &Config::default(), false).is_none());
625 fn test_format_code_block() {
627 let code_block = "let x=3;";
628 let expected = "let x = 3;";
629 assert!(test_format_inner(format_code_block, code_block, expected));
631 // more complex code block, taken from chains.rs.
633 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
635 chain_indent(context, shape.add_offset(parent_rewrite.len())),
636 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
638 } else if is_block_expr(context, &parent, &parent_rewrite) {
639 match context.config.indent_style() {
640 // Try to put the first child on the same line with parent's last line
641 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
642 // The parent is a block, so align the rest of the chain with the closing
644 IndentStyle::Visual => (parent_shape, false),
648 chain_indent(context, shape.add_offset(parent_rewrite.len())),
654 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
656 chain_indent(context, shape.add_offset(parent_rewrite.len())),
657 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
659 } else if is_block_expr(context, &parent, &parent_rewrite) {
660 match context.config.indent_style() {
661 // Try to put the first child on the same line with parent's last line
662 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
663 // The parent is a block, so align the rest of the chain with the closing
665 IndentStyle::Visual => (parent_shape, false),
669 chain_indent(context, shape.add_offset(parent_rewrite.len())),
673 assert!(test_format_inner(format_code_block, code_block, expected));