1#![feature(rustc_private)]
2#![deny(rust_2018_idioms)]
3#![warn(unreachable_pub)]
4#![recursion_limit = "256"]
5#![allow(clippy::match_like_matches_macro)]
6#![allow(unreachable_pub)]
7
8extern crate rustc_ast;
10extern crate rustc_ast_pretty;
11extern crate rustc_data_structures;
12extern crate rustc_errors;
13extern crate rustc_expand;
14extern crate rustc_feature;
15extern crate rustc_parse;
16extern crate rustc_session;
17extern crate rustc_span;
18extern crate thin_vec;
19
20#[allow(unused_extern_crates)]
23extern crate rustc_driver;
24
25use std::cell::RefCell;
26use std::cmp::min;
27use std::collections::HashMap;
28use std::fmt;
29use std::io::{self, Write};
30use std::mem;
31use std::panic;
32use std::path::PathBuf;
33use std::rc::Rc;
34
35use rustc_ast::ast;
36use rustc_span::symbol;
37use thiserror::Error;
38
39use crate::comment::LineClasses;
40use crate::emitter::Emitter;
41use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
42use crate::modules::ModuleResolutionError;
43use crate::parse::parser::DirectoryOwnership;
44use crate::shape::Indent;
45use crate::utils::indent_next_line;
46
47pub use crate::config::{
48 CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle, Range,
49 StyleEdition, Verbosity, Version, load_config,
50};
51
52pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
53
54pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
55
56#[macro_use]
57mod utils;
58
59macro_rules! static_regex {
60 ($re:literal) => {{
61 static RE: ::std::sync::OnceLock<::regex::Regex> = ::std::sync::OnceLock::new();
62 RE.get_or_init(|| ::regex::Regex::new($re).unwrap())
63 }};
64}
65
66mod attr;
67mod chains;
68mod closures;
69mod comment;
70pub(crate) mod config;
71mod coverage;
72mod emitter;
73mod expr;
74mod format_report_formatter;
75pub(crate) mod formatting;
76pub(crate) mod header;
77mod ignore_path;
78mod imports;
79mod items;
80mod lists;
81mod macros;
82mod matches;
83mod missed_spans;
84pub(crate) mod modules;
85mod overflow;
86mod pairs;
87mod parse;
88mod patterns;
89mod range;
90mod release_channel;
91mod reorder;
92mod rewrite;
93pub(crate) mod rustfmt_diff;
94mod shape;
95mod skip;
96mod sort;
97pub(crate) mod source_file;
98pub(crate) mod source_map;
99mod spanned;
100mod stmt;
101mod string;
102#[cfg(test)]
103mod test;
104mod types;
105mod vertical;
106pub(crate) mod visitor;
107
108#[derive(Error, Debug)]
111pub enum ErrorKind {
112 #[error(
114 "line formatted, but exceeded maximum width \
115 (maximum: {1} (see `max_width` option), found: {0})"
116 )]
117 LineOverflow(usize, usize),
118 #[error("left behind trailing whitespace")]
120 TrailingWhitespace,
121 #[error("`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
123 DeprecatedAttr,
124 #[error("invalid attribute")]
126 BadAttr,
127 #[error("io error: {0}")]
129 IoError(io::Error),
130 #[error("{0}")]
132 ModuleResolutionError(#[from] ModuleResolutionError),
133 #[error("parse error")]
135 ParseError,
136 #[error("version mismatch")]
139 VersionMismatch,
140 #[error("not formatted because a comment would be lost")]
142 LostComment,
143 #[error("Invalid glob pattern found in ignore list: {0}")]
145 InvalidGlobPattern(ignore::Error),
146}
147
148impl ErrorKind {
149 fn is_comment(&self) -> bool {
150 matches!(self, ErrorKind::LostComment)
151 }
152}
153
154impl From<io::Error> for ErrorKind {
155 fn from(e: io::Error) -> ErrorKind {
156 ErrorKind::IoError(e)
157 }
158}
159
160#[derive(Debug)]
163struct FormattedSnippet {
164 snippet: String,
165 non_formatted_ranges: Vec<(usize, usize)>,
166}
167
168impl FormattedSnippet {
169 fn unwrap_code_block(&mut self) {
172 self.non_formatted_ranges
173 .iter_mut()
174 .for_each(|(low, high)| {
175 *low -= 1;
176 *high -= 1;
177 });
178 }
179
180 fn is_line_non_formatted(&self, n: usize) -> bool {
182 self.non_formatted_ranges
183 .iter()
184 .any(|(low, high)| *low <= n && n <= *high)
185 }
186}
187
188#[derive(Clone)]
192pub struct FormatReport {
193 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
195 non_formatted_ranges: Vec<(usize, usize)>,
196}
197
198impl FormatReport {
199 fn new() -> FormatReport {
200 FormatReport {
201 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
202 non_formatted_ranges: Vec::new(),
203 }
204 }
205
206 fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
207 self.non_formatted_ranges.append(&mut ranges);
208 }
209
210 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
211 self.track_errors(&v);
212 self.internal
213 .borrow_mut()
214 .0
215 .entry(f)
216 .and_modify(|fe| fe.append(&mut v))
217 .or_insert(v);
218 }
219
220 fn track_errors(&self, new_errors: &[FormattingError]) {
221 let errs = &mut self.internal.borrow_mut().1;
222 if !new_errors.is_empty() {
223 errs.has_formatting_errors = true;
224 }
225 if errs.has_operational_errors && errs.has_check_errors && errs.has_unformatted_code_errors
226 {
227 return;
228 }
229 for err in new_errors {
230 match err.kind {
231 ErrorKind::LineOverflow(..) => {
232 errs.has_operational_errors = true;
233 }
234 ErrorKind::TrailingWhitespace => {
235 errs.has_operational_errors = true;
236 errs.has_unformatted_code_errors = true;
237 }
238 ErrorKind::LostComment => {
239 errs.has_unformatted_code_errors = true;
240 }
241 ErrorKind::DeprecatedAttr | ErrorKind::BadAttr | ErrorKind::VersionMismatch => {
242 errs.has_check_errors = true;
243 }
244 _ => {}
245 }
246 }
247 }
248
249 fn add_diff(&mut self) {
250 self.internal.borrow_mut().1.has_diff = true;
251 }
252
253 fn add_macro_format_failure(&mut self) {
254 self.internal.borrow_mut().1.has_macro_format_failure = true;
255 }
256
257 fn add_parsing_error(&mut self) {
258 self.internal.borrow_mut().1.has_parsing_errors = true;
259 }
260
261 fn warning_count(&self) -> usize {
262 self.internal
263 .borrow()
264 .0
265 .values()
266 .map(|errors| errors.len())
267 .sum()
268 }
269
270 pub fn has_warnings(&self) -> bool {
272 self.internal.borrow().1.has_formatting_errors
273 }
274
275 #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
278 pub fn fancy_print(
279 &self,
280 mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
281 ) -> Result<(), term::Error> {
282 writeln!(
283 t,
284 "{}",
285 FormatReportFormatterBuilder::new(self)
286 .enable_colors(true)
287 .build()
288 )?;
289 Ok(())
290 }
291}
292
293impl fmt::Display for FormatReport {
297 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
299 write!(fmt, "{}", FormatReportFormatterBuilder::new(self).build())?;
300 Ok(())
301 }
302}
303
304fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool) -> Option<FormattedSnippet> {
307 let mut config = config.clone();
308 panic::catch_unwind(|| {
309 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
310 config.set().emit_mode(config::EmitMode::Stdout);
311 config.set().verbose(Verbosity::Quiet);
312 config.set().show_parse_errors(false);
313 if is_macro_def {
314 config.set().error_on_unformatted(true);
315 }
316
317 let (formatting_error, result) = {
318 let input = Input::Text(snippet.into());
319 let mut session = Session::new(config, Some(&mut out));
320 let result = session.format_input_inner(input, is_macro_def);
321 (
322 session.errors.has_macro_format_failure
323 || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
324 || result.is_err()
325 || (is_macro_def && session.has_unformatted_code_errors()),
326 result,
327 )
328 };
329 if formatting_error {
330 None
331 } else {
332 String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
333 snippet,
334 non_formatted_ranges: result.unwrap().non_formatted_ranges,
335 })
336 }
337 })
338 .ok()?
341}
342
343fn format_code_block(
348 code_snippet: &str,
349 config: &Config,
350 is_macro_def: bool,
351) -> Option<FormattedSnippet> {
352 const FN_MAIN_PREFIX: &str = "fn main() {\n";
353
354 fn enclose_in_main_block(s: &str, config: &Config) -> String {
355 let indent = Indent::from_width(config, config.tab_spaces());
356 let mut result = String::with_capacity(s.len() * 2);
357 result.push_str(FN_MAIN_PREFIX);
358 let mut need_indent = true;
359 for (kind, line) in LineClasses::new(s) {
360 if need_indent {
361 result.push_str(&indent.to_string(config));
362 }
363 result.push_str(&line);
364 result.push('\n');
365 need_indent = indent_next_line(kind, &line, config);
366 }
367 result.push('}');
368 result
369 }
370
371 let snippet = enclose_in_main_block(code_snippet, config);
373 let mut result = String::with_capacity(snippet.len());
374 let mut is_first = true;
375
376 let mut config_with_unix_newline = config.clone();
381 config_with_unix_newline
382 .set()
383 .newline_style(NewlineStyle::Unix);
384 let mut formatted = format_snippet(&snippet, &config_with_unix_newline, is_macro_def)?;
385 formatted.unwrap_code_block();
387
388 let block_len = formatted
391 .snippet
392 .rfind('}')
393 .unwrap_or_else(|| formatted.snippet.len());
394
395 let block_start = min(FN_MAIN_PREFIX.len(), block_len);
399
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[block_start..block_len]) {
403 if !is_first {
404 result.push('\n');
405 } else {
406 is_first = false;
407 }
408 let trimmed_line = if !is_indented {
409 line
410 } else if line.len() > config.max_width() {
411 return None;
416 } else if line.len() > indent_str.len() {
417 if line.starts_with(indent_str.as_ref()) {
419 let offset = if config.hard_tabs() {
420 1
421 } else {
422 config.tab_spaces()
423 };
424 &line[offset..]
425 } else {
426 line
427 }
428 } else {
429 line
430 };
431 result.push_str(trimmed_line);
432 is_indented = indent_next_line(kind, line, config);
433 }
434 Some(FormattedSnippet {
435 snippet: result,
436 non_formatted_ranges: formatted.non_formatted_ranges,
437 })
438}
439
440pub struct Session<'b, T: Write> {
442 pub config: Config,
443 pub out: Option<&'b mut T>,
444 pub(crate) errors: ReportedErrors,
445 source_file: SourceFile,
446 emitter: Box<dyn Emitter + 'b>,
447}
448
449impl<'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);
452
453 if let Some(ref mut out) = out {
454 let _ = emitter.emit_header(out);
455 }
456
457 Session {
458 config,
459 out,
460 emitter,
461 errors: ReportedErrors::default(),
462 source_file: SourceFile::new(),
463 }
464 }
465
466 pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
469 self.format_input_inner(input, false)
470 }
471
472 pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
473 where
474 F: FnOnce(&mut Session<'b, T>) -> U,
475 {
476 mem::swap(&mut config, &mut self.config);
477 let result = f(self);
478 mem::swap(&mut config, &mut self.config);
479 result
480 }
481
482 pub fn add_operational_error(&mut self) {
483 self.errors.has_operational_errors = true;
484 }
485
486 pub fn has_operational_errors(&self) -> bool {
487 self.errors.has_operational_errors
488 }
489
490 pub fn has_parsing_errors(&self) -> bool {
491 self.errors.has_parsing_errors
492 }
493
494 pub fn has_formatting_errors(&self) -> bool {
495 self.errors.has_formatting_errors
496 }
497
498 pub fn has_check_errors(&self) -> bool {
499 self.errors.has_check_errors
500 }
501
502 pub fn has_diff(&self) -> bool {
503 self.errors.has_diff
504 }
505
506 pub fn has_unformatted_code_errors(&self) -> bool {
507 self.errors.has_unformatted_code_errors
508 }
509
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()
515 || self.has_diff()
516 || self.has_unformatted_code_errors()
517 || self.errors.has_macro_format_failure)
518 }
519}
520
521pub(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())
525 }
526 EmitMode::Files => Box::new(emitter::FilesEmitter::new(
527 config.print_misformatted_file_names(),
528 )),
529 EmitMode::Stdout | EmitMode::Coverage => {
530 Box::new(emitter::StdoutEmitter::new(config.verbose()))
531 }
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())),
536 }
537}
538
539impl<'b, T: Write + 'b> Drop for Session<'b, T> {
540 fn drop(&mut self) {
541 if let Some(ref mut out) = self.out {
542 let _ = self.emitter.emit_footer(out);
543 }
544 }
545}
546
547#[derive(Debug)]
548pub enum Input {
549 File(PathBuf),
550 Text(String),
551}
552
553impl Input {
554 fn file_name(&self) -> FileName {
555 match *self {
556 Input::File(ref file) => FileName::Real(file.clone()),
557 Input::Text(..) => FileName::Stdin,
558 }
559 }
560
561 fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
562 match self {
563 Input::File(ref file) => {
564 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),
570 })
571 } else {
572 None
573 }
574 }
575 _ => None,
576 }
577 }
578}
579
580#[cfg(test)]
581mod unit_tests {
582 use super::*;
583
584 #[test]
585 fn test_no_panic_on_format_snippet_and_format_code_block() {
586 let snippet = "let";
589 assert!(format_snippet(snippet, &Config::default(), false).is_none());
590 assert!(format_code_block(snippet, &Config::default(), false).is_none());
591 }
592
593 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
594 where
595 F: Fn(&str, &Config, bool) -> Option<FormattedSnippet>,
596 {
597 let output = formatter(input, &Config::default(), false);
598 output.is_some() && output.unwrap().snippet == expected
599 }
600
601 #[test]
602 fn test_format_snippet() {
603 let snippet = "fn main() { println!(\"hello, world\"); }";
604 #[cfg(not(windows))]
605 let expected = "fn main() {\n \
606 println!(\"hello, world\");\n\
607 }\n";
608 #[cfg(windows)]
609 let expected = "fn main() {\r\n \
610 println!(\"hello, world\");\r\n\
611 }\r\n";
612 assert!(test_format_inner(format_snippet, snippet, expected));
613 }
614
615 #[test]
616 fn test_format_code_block_fail() {
617 #[rustfmt::skip]
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());
620 }
621
622 #[test]
623 fn test_format_code_block() {
624 let code_block = "let x=3;";
626 let expected = "let x = 3;";
627 assert!(test_format_inner(format_code_block, code_block, expected));
628
629 let code_block =
631"let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
632(
633chain_indent(context, shape.add_offset(parent_rewrite.len())),
634context.config.indent_style() == IndentStyle::Visual || is_small_parent,
635)
636} else if is_block_expr(context, &parent, &parent_rewrite) {
637match context.config.indent_style() {
638// Try to put the first child on the same line with parent's last line
639IndentStyle::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
641// brace.
642IndentStyle::Visual => (parent_shape, false),
643}
644} else {
645(
646chain_indent(context, shape.add_offset(parent_rewrite.len())),
647false,
648)
649};
650";
651 let expected =
652"let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
653 (
654 chain_indent(context, shape.add_offset(parent_rewrite.len())),
655 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
656 )
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
662 // brace.
663 IndentStyle::Visual => (parent_shape, false),
664 }
665} else {
666 (
667 chain_indent(context, shape.add_offset(parent_rewrite.len())),
668 false,
669 )
670};";
671 assert!(test_format_inner(format_code_block, code_block, expected));
672 }
673}