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