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