]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/lib.rs
Merge commit '35d9c6bf256968e1b40e0d554607928bdf9cebea' into sync_cg_clif-2022-02-23
[rust.git] / src / tools / rustfmt / src / lib.rs
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
8 #[macro_use]
9 extern crate derive_new;
10 #[cfg(test)]
11 #[macro_use]
12 extern crate lazy_static;
13 #[macro_use]
14 extern crate log;
15
16 // N.B. these crates are loaded from the sysroot, so they need extern crate.
17 extern crate rustc_ast;
18 extern crate rustc_ast_pretty;
19 extern crate rustc_builtin_macros;
20 extern crate rustc_data_structures;
21 extern crate rustc_errors;
22 extern crate rustc_expand;
23 extern crate rustc_parse;
24 extern crate rustc_session;
25 extern crate rustc_span;
26
27 use std::cell::RefCell;
28 use std::collections::HashMap;
29 use std::fmt;
30 use std::io::{self, Write};
31 use std::mem;
32 use std::panic;
33 use std::path::PathBuf;
34 use std::rc::Rc;
35
36 use rustc_ast::ast;
37 use rustc_span::symbol;
38 use thiserror::Error;
39
40 use crate::comment::LineClasses;
41 use crate::emitter::Emitter;
42 use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
43 use crate::issues::Issue;
44 use crate::modules::ModuleResolutionError;
45 use crate::parse::parser::DirectoryOwnership;
46 use crate::shape::Indent;
47 use crate::utils::indent_next_line;
48
49 pub use crate::config::{
50     load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
51     Range, Verbosity,
52 };
53
54 pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
55
56 pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
57
58 #[macro_use]
59 mod utils;
60
61 mod attr;
62 mod chains;
63 mod closures;
64 mod comment;
65 pub(crate) mod config;
66 mod coverage;
67 mod emitter;
68 mod expr;
69 mod format_report_formatter;
70 pub(crate) mod formatting;
71 mod ignore_path;
72 mod imports;
73 mod issues;
74 mod items;
75 mod lists;
76 mod macros;
77 mod matches;
78 mod missed_spans;
79 pub(crate) mod modules;
80 mod overflow;
81 mod pairs;
82 mod parse;
83 mod patterns;
84 mod release_channel;
85 mod reorder;
86 mod rewrite;
87 pub(crate) mod rustfmt_diff;
88 mod shape;
89 mod skip;
90 pub(crate) mod source_file;
91 pub(crate) mod source_map;
92 mod spanned;
93 mod stmt;
94 mod string;
95 #[cfg(test)]
96 mod test;
97 mod types;
98 mod vertical;
99 pub(crate) mod visitor;
100
101 /// The various errors that can occur during formatting. Note that not all of
102 /// these can currently be propagated to clients.
103 #[derive(Error, Debug)]
104 pub enum ErrorKind {
105     /// Line has exceeded character limit (found, maximum).
106     #[error(
107         "line formatted, but exceeded maximum width \
108          (maximum: {1} (see `max_width` option), found: {0})"
109     )]
110     LineOverflow(usize, usize),
111     /// Line ends in whitespace.
112     #[error("left behind trailing whitespace")]
113     TrailingWhitespace,
114     /// TODO or FIXME item without an issue number.
115     #[error("found {0}")]
116     BadIssue(Issue),
117     /// License check has failed.
118     #[error("license check failed")]
119     LicenseCheck,
120     /// Used deprecated skip attribute.
121     #[error("`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
122     DeprecatedAttr,
123     /// Used a rustfmt:: attribute other than skip or skip::macros.
124     #[error("invalid attribute")]
125     BadAttr,
126     /// An io error during reading or writing.
127     #[error("io error: {0}")]
128     IoError(io::Error),
129     /// Error during module resolution.
130     #[error("{0}")]
131     ModuleResolutionError(#[from] ModuleResolutionError),
132     /// Parse error occurred when parsing the input.
133     #[error("parse error")]
134     ParseError,
135     /// The user mandated a version and the current version of Rustfmt does not
136     /// satisfy that requirement.
137     #[error("version mismatch")]
138     VersionMismatch,
139     /// If we had formatted the given node, then we would have lost a comment.
140     #[error("not formatted because a comment would be lost")]
141     LostComment,
142     /// Invalid glob pattern in `ignore` configuration option.
143     #[error("Invalid glob pattern found in ignore list: {0}")]
144     InvalidGlobPattern(ignore::Error),
145 }
146
147 impl ErrorKind {
148     fn is_comment(&self) -> bool {
149         matches!(self, ErrorKind::LostComment)
150     }
151 }
152
153 impl From<io::Error> for ErrorKind {
154     fn from(e: io::Error) -> ErrorKind {
155         ErrorKind::IoError(e)
156     }
157 }
158
159 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
160 /// i.e., that got returned as they were originally.
161 #[derive(Debug)]
162 struct FormattedSnippet {
163     snippet: String,
164     non_formatted_ranges: Vec<(usize, usize)>,
165 }
166
167 impl FormattedSnippet {
168     /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
169     /// non-formatted code.
170     fn unwrap_code_block(&mut self) {
171         self.non_formatted_ranges
172             .iter_mut()
173             .for_each(|(low, high)| {
174                 *low -= 1;
175                 *high -= 1;
176             });
177     }
178
179     /// Returns `true` if the line n did not get formatted.
180     fn is_line_non_formatted(&self, n: usize) -> bool {
181         self.non_formatted_ranges
182             .iter()
183             .any(|(low, high)| *low <= n && n <= *high)
184     }
185 }
186
187 /// Reports on any issues that occurred during a run of Rustfmt.
188 ///
189 /// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
190 #[derive(Clone)]
191 pub struct FormatReport {
192     // Maps stringified file paths to their associated formatting errors.
193     internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
194     non_formatted_ranges: Vec<(usize, usize)>,
195 }
196
197 impl FormatReport {
198     fn new() -> FormatReport {
199         FormatReport {
200             internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
201             non_formatted_ranges: Vec::new(),
202         }
203     }
204
205     fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
206         self.non_formatted_ranges.append(&mut ranges);
207     }
208
209     fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
210         self.track_errors(&v);
211         self.internal
212             .borrow_mut()
213             .0
214             .entry(f)
215             .and_modify(|fe| fe.append(&mut v))
216             .or_insert(v);
217     }
218
219     fn track_errors(&self, new_errors: &[FormattingError]) {
220         let errs = &mut self.internal.borrow_mut().1;
221         if !new_errors.is_empty() {
222             errs.has_formatting_errors = true;
223         }
224         if errs.has_operational_errors && errs.has_check_errors && errs.has_unformatted_code_errors
225         {
226             return;
227         }
228         for err in new_errors {
229             match err.kind {
230                 ErrorKind::LineOverflow(..) => {
231                     errs.has_operational_errors = true;
232                 }
233                 ErrorKind::TrailingWhitespace => {
234                     errs.has_operational_errors = true;
235                     errs.has_unformatted_code_errors = true;
236                 }
237                 ErrorKind::LostComment => {
238                     errs.has_unformatted_code_errors = true;
239                 }
240                 ErrorKind::BadIssue(_)
241                 | ErrorKind::LicenseCheck
242                 | ErrorKind::DeprecatedAttr
243                 | ErrorKind::BadAttr
244                 | ErrorKind::VersionMismatch => {
245                     errs.has_check_errors = true;
246                 }
247                 _ => {}
248             }
249         }
250     }
251
252     fn add_diff(&mut self) {
253         self.internal.borrow_mut().1.has_diff = true;
254     }
255
256     fn add_macro_format_failure(&mut self) {
257         self.internal.borrow_mut().1.has_macro_format_failure = true;
258     }
259
260     fn add_parsing_error(&mut self) {
261         self.internal.borrow_mut().1.has_parsing_errors = true;
262     }
263
264     fn warning_count(&self) -> usize {
265         self.internal
266             .borrow()
267             .0
268             .iter()
269             .map(|(_, errors)| errors.len())
270             .sum()
271     }
272
273     /// Whether any warnings or errors are present in the report.
274     pub fn has_warnings(&self) -> bool {
275         self.internal.borrow().1.has_formatting_errors
276     }
277
278     /// Print the report to a terminal using colours and potentially other
279     /// fancy output.
280     #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
281     pub fn fancy_print(
282         &self,
283         mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
284     ) -> Result<(), term::Error> {
285         writeln!(
286             t,
287             "{}",
288             FormatReportFormatterBuilder::new(self)
289                 .enable_colors(true)
290                 .build()
291         )?;
292         Ok(())
293     }
294 }
295
296 /// Deprecated - Use FormatReportFormatter instead
297 // https://github.com/rust-lang/rust/issues/78625
298 // https://github.com/rust-lang/rust/issues/39935
299 impl fmt::Display for FormatReport {
300     // Prints all the formatting errors.
301     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
302         write!(fmt, "{}", FormatReportFormatterBuilder::new(self).build())?;
303         Ok(())
304     }
305 }
306
307 /// Format the given snippet. The snippet is expected to be *complete* code.
308 /// When we cannot parse the given snippet, this function returns `None`.
309 fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool) -> Option<FormattedSnippet> {
310     let mut config = config.clone();
311     panic::catch_unwind(|| {
312         let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
313         config.set().emit_mode(config::EmitMode::Stdout);
314         config.set().verbose(Verbosity::Quiet);
315         config.set().hide_parse_errors(true);
316         if is_macro_def {
317             config.set().error_on_unformatted(true);
318         }
319
320         let (formatting_error, result) = {
321             let input = Input::Text(snippet.into());
322             let mut session = Session::new(config, Some(&mut out));
323             let result = session.format_input_inner(input, is_macro_def);
324             (
325                 session.errors.has_macro_format_failure
326                     || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
327                     || result.is_err()
328                     || (is_macro_def && session.has_unformatted_code_errors()),
329                 result,
330             )
331         };
332         if formatting_error {
333             None
334         } else {
335             String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
336                 snippet,
337                 non_formatted_ranges: result.unwrap().non_formatted_ranges,
338             })
339         }
340     })
341     // Discard panics encountered while formatting the snippet
342     // The ? operator is needed to remove the extra Option
343     .ok()?
344 }
345
346 /// Format the given code block. Mainly targeted for code block in comment.
347 /// The code block may be incomplete (i.e., parser may be unable to parse it).
348 /// To avoid panic in parser, we wrap the code block with a dummy function.
349 /// The returned code block does **not** end with newline.
350 fn format_code_block(
351     code_snippet: &str,
352     config: &Config,
353     is_macro_def: bool,
354 ) -> Option<FormattedSnippet> {
355     const FN_MAIN_PREFIX: &str = "fn main() {\n";
356
357     fn enclose_in_main_block(s: &str, config: &Config) -> String {
358         let indent = Indent::from_width(config, config.tab_spaces());
359         let mut result = String::with_capacity(s.len() * 2);
360         result.push_str(FN_MAIN_PREFIX);
361         let mut need_indent = true;
362         for (kind, line) in LineClasses::new(s) {
363             if need_indent {
364                 result.push_str(&indent.to_string(config));
365             }
366             result.push_str(&line);
367             result.push('\n');
368             need_indent = indent_next_line(kind, &line, config);
369         }
370         result.push('}');
371         result
372     }
373
374     // Wrap the given code block with `fn main()` if it does not have one.
375     let snippet = enclose_in_main_block(code_snippet, config);
376     let mut result = String::with_capacity(snippet.len());
377     let mut is_first = true;
378
379     // While formatting the code, ignore the config's newline style setting and always use "\n"
380     // instead of "\r\n" for the newline characters. This is ok because the output here is
381     // not directly outputted by rustfmt command, but used by the comment formatter's input.
382     // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
383     let mut config_with_unix_newline = config.clone();
384     config_with_unix_newline
385         .set()
386         .newline_style(NewlineStyle::Unix);
387     let mut formatted = format_snippet(&snippet, &config_with_unix_newline, is_macro_def)?;
388     // Remove wrapping main block
389     formatted.unwrap_code_block();
390
391     // Trim "fn main() {" on the first line and "}" on the last line,
392     // then unindent the whole code block.
393     let block_len = formatted
394         .snippet
395         .rfind('}')
396         .unwrap_or_else(|| formatted.snippet.len());
397     let mut is_indented = true;
398     let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
399     for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
400         if !is_first {
401             result.push('\n');
402         } else {
403             is_first = false;
404         }
405         let trimmed_line = if !is_indented {
406             line
407         } else if line.len() > config.max_width() {
408             // If there are lines that are larger than max width, we cannot tell
409             // whether we have succeeded but have some comments or strings that
410             // are too long, or we have failed to format code block. We will be
411             // conservative and just return `None` in this case.
412             return None;
413         } else if line.len() > indent_str.len() {
414             // Make sure that the line has leading whitespaces.
415             if line.starts_with(indent_str.as_ref()) {
416                 let offset = if config.hard_tabs() {
417                     1
418                 } else {
419                     config.tab_spaces()
420                 };
421                 &line[offset..]
422             } else {
423                 line
424             }
425         } else {
426             line
427         };
428         result.push_str(trimmed_line);
429         is_indented = indent_next_line(kind, line, config);
430     }
431     Some(FormattedSnippet {
432         snippet: result,
433         non_formatted_ranges: formatted.non_formatted_ranges,
434     })
435 }
436
437 /// A session is a run of rustfmt across a single or multiple inputs.
438 pub struct Session<'b, T: Write> {
439     pub config: Config,
440     pub out: Option<&'b mut T>,
441     pub(crate) errors: ReportedErrors,
442     source_file: SourceFile,
443     emitter: Box<dyn Emitter + 'b>,
444 }
445
446 impl<'b, T: Write + 'b> Session<'b, T> {
447     pub fn new(config: Config, mut out: Option<&'b mut T>) -> Session<'b, T> {
448         let emitter = create_emitter(&config);
449
450         if let Some(ref mut out) = out {
451             let _ = emitter.emit_header(out);
452         }
453
454         Session {
455             config,
456             out,
457             emitter,
458             errors: ReportedErrors::default(),
459             source_file: SourceFile::new(),
460         }
461     }
462
463     /// The main entry point for Rustfmt. Formats the given input according to the
464     /// given config. `out` is only necessary if required by the configuration.
465     pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
466         self.format_input_inner(input, false)
467     }
468
469     pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
470     where
471         F: FnOnce(&mut Session<'b, T>) -> U,
472     {
473         mem::swap(&mut config, &mut self.config);
474         let result = f(self);
475         mem::swap(&mut config, &mut self.config);
476         result
477     }
478
479     pub fn add_operational_error(&mut self) {
480         self.errors.has_operational_errors = true;
481     }
482
483     pub fn has_operational_errors(&self) -> bool {
484         self.errors.has_operational_errors
485     }
486
487     pub fn has_parsing_errors(&self) -> bool {
488         self.errors.has_parsing_errors
489     }
490
491     pub fn has_formatting_errors(&self) -> bool {
492         self.errors.has_formatting_errors
493     }
494
495     pub fn has_check_errors(&self) -> bool {
496         self.errors.has_check_errors
497     }
498
499     pub fn has_diff(&self) -> bool {
500         self.errors.has_diff
501     }
502
503     pub fn has_unformatted_code_errors(&self) -> bool {
504         self.errors.has_unformatted_code_errors
505     }
506
507     pub fn has_no_errors(&self) -> bool {
508         !(self.has_operational_errors()
509             || self.has_parsing_errors()
510             || self.has_formatting_errors()
511             || self.has_check_errors()
512             || self.has_diff()
513             || self.has_unformatted_code_errors()
514             || self.errors.has_macro_format_failure)
515     }
516 }
517
518 pub(crate) fn create_emitter<'a>(config: &Config) -> Box<dyn Emitter + 'a> {
519     match config.emit_mode() {
520         EmitMode::Files if config.make_backup() => {
521             Box::new(emitter::FilesWithBackupEmitter::default())
522         }
523         EmitMode::Files => Box::new(emitter::FilesEmitter::new(
524             config.print_misformatted_file_names(),
525         )),
526         EmitMode::Stdout | EmitMode::Coverage => {
527             Box::new(emitter::StdoutEmitter::new(config.verbose()))
528         }
529         EmitMode::Json => Box::new(emitter::JsonEmitter::default()),
530         EmitMode::ModifiedLines => Box::new(emitter::ModifiedLinesEmitter::default()),
531         EmitMode::Checkstyle => Box::new(emitter::CheckstyleEmitter::default()),
532         EmitMode::Diff => Box::new(emitter::DiffEmitter::new(config.clone())),
533     }
534 }
535
536 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
537     fn drop(&mut self) {
538         if let Some(ref mut out) = self.out {
539             let _ = self.emitter.emit_footer(out);
540         }
541     }
542 }
543
544 #[derive(Debug)]
545 pub enum Input {
546     File(PathBuf),
547     Text(String),
548 }
549
550 impl Input {
551     fn file_name(&self) -> FileName {
552         match *self {
553             Input::File(ref file) => FileName::Real(file.clone()),
554             Input::Text(..) => FileName::Stdin,
555         }
556     }
557
558     fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
559         match self {
560             Input::File(ref file) => {
561                 // If there exists a directory with the same name as an input,
562                 // then the input should be parsed as a sub module.
563                 let file_stem = file.file_stem()?;
564                 if file.parent()?.to_path_buf().join(file_stem).is_dir() {
565                     Some(DirectoryOwnership::Owned {
566                         relative: file_stem.to_str().map(symbol::Ident::from_str),
567                     })
568                 } else {
569                     None
570                 }
571             }
572             _ => None,
573         }
574     }
575 }
576
577 #[cfg(test)]
578 mod unit_tests {
579     use super::*;
580
581     #[test]
582     fn test_no_panic_on_format_snippet_and_format_code_block() {
583         // `format_snippet()` and `format_code_block()` should not panic
584         // even when we cannot parse the given snippet.
585         let snippet = "let";
586         assert!(format_snippet(snippet, &Config::default(), false).is_none());
587         assert!(format_code_block(snippet, &Config::default(), false).is_none());
588     }
589
590     fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
591     where
592         F: Fn(&str, &Config, bool) -> Option<FormattedSnippet>,
593     {
594         let output = formatter(input, &Config::default(), false);
595         output.is_some() && output.unwrap().snippet == expected
596     }
597
598     #[test]
599     fn test_format_snippet() {
600         let snippet = "fn main() { println!(\"hello, world\"); }";
601         #[cfg(not(windows))]
602         let expected = "fn main() {\n    \
603                         println!(\"hello, world\");\n\
604                         }\n";
605         #[cfg(windows)]
606         let expected = "fn main() {\r\n    \
607                         println!(\"hello, world\");\r\n\
608                         }\r\n";
609         assert!(test_format_inner(format_snippet, snippet, expected));
610     }
611
612     #[test]
613     fn test_format_code_block_fail() {
614         #[rustfmt::skip]
615         let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
616         assert!(format_code_block(code_block, &Config::default(), false).is_none());
617     }
618
619     #[test]
620     fn test_format_code_block() {
621         // simple code block
622         let code_block = "let x=3;";
623         let expected = "let x = 3;";
624         assert!(test_format_inner(format_code_block, code_block, expected));
625
626         // more complex code block, taken from chains.rs.
627         let code_block =
628 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
629 (
630 chain_indent(context, shape.add_offset(parent_rewrite.len())),
631 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
632 )
633 } else if is_block_expr(context, &parent, &parent_rewrite) {
634 match context.config.indent_style() {
635 // Try to put the first child on the same line with parent's last line
636 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
637 // The parent is a block, so align the rest of the chain with the closing
638 // brace.
639 IndentStyle::Visual => (parent_shape, false),
640 }
641 } else {
642 (
643 chain_indent(context, shape.add_offset(parent_rewrite.len())),
644 false,
645 )
646 };
647 ";
648         let expected =
649 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
650     (
651         chain_indent(context, shape.add_offset(parent_rewrite.len())),
652         context.config.indent_style() == IndentStyle::Visual || is_small_parent,
653     )
654 } else if is_block_expr(context, &parent, &parent_rewrite) {
655     match context.config.indent_style() {
656         // Try to put the first child on the same line with parent's last line
657         IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
658         // The parent is a block, so align the rest of the chain with the closing
659         // brace.
660         IndentStyle::Visual => (parent_shape, false),
661     }
662 } else {
663     (
664         chain_indent(context, shape.add_offset(parent_rewrite.len())),
665         false,
666     )
667 };";
668         assert!(test_format_inner(format_code_block, code_block, expected));
669     }
670 }