]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Rollup merge of #86274 - alexander-melentyev:spaces, r=bjorn3
[rust.git] / src / lib.rs
1 #![feature(rustc_private)]
2 #![deny(rust_2018_idioms)]
3 #![warn(unreachable_pub)]
4
5 #[macro_use]
6 extern crate derive_new;
7 #[cfg(test)]
8 #[macro_use]
9 extern crate lazy_static;
10 #[macro_use]
11 extern crate log;
12
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;
22
23 use std::cell::RefCell;
24 use std::collections::HashMap;
25 use std::fmt;
26 use std::io::{self, Write};
27 use std::mem;
28 use std::panic;
29 use std::path::PathBuf;
30 use std::rc::Rc;
31
32 use ignore;
33 use rustc_ast::ast;
34 use rustc_span::{symbol, DUMMY_SP};
35 use thiserror::Error;
36
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;
45
46 pub use crate::config::{
47     load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
48     Range, Verbosity,
49 };
50
51 pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
52
53 pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
54
55 #[macro_use]
56 mod utils;
57
58 mod attr;
59 mod chains;
60 mod closures;
61 mod comment;
62 pub(crate) mod config;
63 mod coverage;
64 mod emitter;
65 mod expr;
66 mod format_report_formatter;
67 pub(crate) mod formatting;
68 mod ignore_path;
69 mod imports;
70 mod issues;
71 mod items;
72 mod lists;
73 mod macros;
74 mod matches;
75 mod missed_spans;
76 pub(crate) mod modules;
77 mod overflow;
78 mod pairs;
79 mod patterns;
80 mod release_channel;
81 mod reorder;
82 mod rewrite;
83 pub(crate) mod rustfmt_diff;
84 mod shape;
85 mod skip;
86 pub(crate) mod source_file;
87 pub(crate) mod source_map;
88 mod spanned;
89 mod stmt;
90 mod string;
91 mod syntux;
92 #[cfg(test)]
93 mod test;
94 mod types;
95 mod vertical;
96 pub(crate) mod visitor;
97
98 const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
99     kind: ast::VisibilityKind::Inherited,
100     span: DUMMY_SP,
101     tokens: None,
102 };
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)]
106 pub enum ErrorKind {
107     /// Line has exceeded character limit (found, maximum).
108     #[error(
109         "line formatted, but exceeded maximum width \
110          (maximum: {1} (see `max_width` option), found: {0})"
111     )]
112     LineOverflow(usize, usize),
113     /// Line ends in whitespace.
114     #[error("left behind trailing whitespace")]
115     TrailingWhitespace,
116     /// TODO or FIXME item without an issue number.
117     #[error("found {0}")]
118     BadIssue(Issue),
119     /// License check has failed.
120     #[error("license check failed")]
121     LicenseCheck,
122     /// Used deprecated skip attribute.
123     #[error("`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
124     DeprecatedAttr,
125     /// Used a rustfmt:: attribute other than skip or skip::macros.
126     #[error("invalid attribute")]
127     BadAttr,
128     /// An io error during reading or writing.
129     #[error("io error: {0}")]
130     IoError(io::Error),
131     /// Error during module resolution.
132     #[error("{0}")]
133     ModuleResolutionError(#[from] ModuleResolutionError),
134     /// Parse error occurred when parsing the input.
135     #[error("parse error")]
136     ParseError,
137     /// The user mandated a version and the current version of Rustfmt does not
138     /// satisfy that requirement.
139     #[error("version mismatch")]
140     VersionMismatch,
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")]
143     LostComment,
144     /// Invalid glob pattern in `ignore` configuration option.
145     #[error("Invalid glob pattern found in ignore list: {0}")]
146     InvalidGlobPattern(ignore::Error),
147 }
148
149 impl ErrorKind {
150     fn is_comment(&self) -> bool {
151         match self {
152             ErrorKind::LostComment => true,
153             _ => false,
154         }
155     }
156 }
157
158 impl From<io::Error> for ErrorKind {
159     fn from(e: io::Error) -> ErrorKind {
160         ErrorKind::IoError(e)
161     }
162 }
163
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.
166 #[derive(Debug)]
167 struct FormattedSnippet {
168     snippet: String,
169     non_formatted_ranges: Vec<(usize, usize)>,
170 }
171
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
177             .iter_mut()
178             .for_each(|(low, high)| {
179                 *low -= 1;
180                 *high -= 1;
181             });
182     }
183
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
187             .iter()
188             .any(|(low, high)| *low <= n && n <= *high)
189     }
190 }
191
192 /// Reports on any issues that occurred during a run of Rustfmt.
193 ///
194 /// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
195 #[derive(Clone)]
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)>,
200 }
201
202 impl FormatReport {
203     fn new() -> FormatReport {
204         FormatReport {
205             internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
206             non_formatted_ranges: Vec::new(),
207         }
208     }
209
210     fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
211         self.non_formatted_ranges.append(&mut ranges);
212     }
213
214     fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
215         self.track_errors(&v);
216         self.internal
217             .borrow_mut()
218             .0
219             .entry(f)
220             .and_modify(|fe| fe.append(&mut v))
221             .or_insert(v);
222     }
223
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;
228         }
229         if errs.has_operational_errors && errs.has_check_errors && errs.has_unformatted_code_errors
230         {
231             return;
232         }
233         for err in new_errors {
234             match err.kind {
235                 ErrorKind::LineOverflow(..) => {
236                     errs.has_operational_errors = true;
237                 }
238                 ErrorKind::TrailingWhitespace => {
239                     errs.has_operational_errors = true;
240                     errs.has_unformatted_code_errors = true;
241                 }
242                 ErrorKind::LostComment => {
243                     errs.has_unformatted_code_errors = true;
244                 }
245                 ErrorKind::BadIssue(_)
246                 | ErrorKind::LicenseCheck
247                 | ErrorKind::DeprecatedAttr
248                 | ErrorKind::BadAttr
249                 | ErrorKind::VersionMismatch => {
250                     errs.has_check_errors = true;
251                 }
252                 _ => {}
253             }
254         }
255     }
256
257     fn add_diff(&mut self) {
258         self.internal.borrow_mut().1.has_diff = true;
259     }
260
261     fn add_macro_format_failure(&mut self) {
262         self.internal.borrow_mut().1.has_macro_format_failure = true;
263     }
264
265     fn add_parsing_error(&mut self) {
266         self.internal.borrow_mut().1.has_parsing_errors = true;
267     }
268
269     fn warning_count(&self) -> usize {
270         self.internal
271             .borrow()
272             .0
273             .iter()
274             .map(|(_, errors)| errors.len())
275             .sum()
276     }
277
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
281     }
282
283     /// Print the report to a terminal using colours and potentially other
284     /// fancy output.
285     #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
286     pub fn fancy_print(
287         &self,
288         mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
289     ) -> Result<(), term::Error> {
290         writeln!(
291             t,
292             "{}",
293             FormatReportFormatterBuilder::new(&self)
294                 .enable_colors(true)
295                 .build()
296         )?;
297         Ok(())
298     }
299 }
300
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())?;
308         Ok(())
309     }
310 }
311
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);
321         if is_macro_def {
322             config.set().error_on_unformatted(true);
323         }
324
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);
329             (
330                 session.errors.has_macro_format_failure
331                     || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
332                     || result.is_err()
333                     || (is_macro_def && session.has_unformatted_code_errors()),
334                 result,
335             )
336         };
337         if formatting_error {
338             None
339         } else {
340             String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
341                 snippet,
342                 non_formatted_ranges: result.unwrap().non_formatted_ranges,
343             })
344         }
345     })
346     // Discard panics encountered while formatting the snippet
347     // The ? operator is needed to remove the extra Option
348     .ok()?
349 }
350
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(
356     code_snippet: &str,
357     config: &Config,
358     is_macro_def: bool,
359 ) -> Option<FormattedSnippet> {
360     const FN_MAIN_PREFIX: &str = "fn main() {\n";
361
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) {
368             if need_indent {
369                 result.push_str(&indent.to_string(config));
370             }
371             result.push_str(&line);
372             result.push('\n');
373             need_indent = indent_next_line(kind, &line, config);
374         }
375         result.push('}');
376         result
377     }
378
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;
383
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
390         .set()
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();
395
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
399         .snippet
400         .rfind('}')
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]) {
405         if !is_first {
406             result.push('\n');
407         } else {
408             is_first = false;
409         }
410         let trimmed_line = if !is_indented {
411             line
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.
417             return None;
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() {
422                     1
423                 } else {
424                     config.tab_spaces()
425                 };
426                 &line[offset..]
427             } else {
428                 line
429             }
430         } else {
431             line
432         };
433         result.push_str(trimmed_line);
434         is_indented = indent_next_line(kind, line, config);
435     }
436     Some(FormattedSnippet {
437         snippet: result,
438         non_formatted_ranges: formatted.non_formatted_ranges,
439     })
440 }
441
442 /// A session is a run of rustfmt across a single or multiple inputs.
443 pub struct Session<'b, T: Write> {
444     pub config: Config,
445     pub out: Option<&'b mut T>,
446     pub(crate) errors: ReportedErrors,
447     source_file: SourceFile,
448     emitter: Box<dyn Emitter + 'b>,
449 }
450
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);
454
455         if let Some(ref mut out) = out {
456             let _ = emitter.emit_header(out);
457         }
458
459         Session {
460             config,
461             out,
462             emitter,
463             errors: ReportedErrors::default(),
464             source_file: SourceFile::new(),
465         }
466     }
467
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)
472     }
473
474     pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
475     where
476         F: FnOnce(&mut Session<'b, T>) -> U,
477     {
478         mem::swap(&mut config, &mut self.config);
479         let result = f(self);
480         mem::swap(&mut config, &mut self.config);
481         result
482     }
483
484     pub fn add_operational_error(&mut self) {
485         self.errors.has_operational_errors = true;
486     }
487
488     pub fn has_operational_errors(&self) -> bool {
489         self.errors.has_operational_errors
490     }
491
492     pub fn has_parsing_errors(&self) -> bool {
493         self.errors.has_parsing_errors
494     }
495
496     pub fn has_formatting_errors(&self) -> bool {
497         self.errors.has_formatting_errors
498     }
499
500     pub fn has_check_errors(&self) -> bool {
501         self.errors.has_check_errors
502     }
503
504     pub fn has_diff(&self) -> bool {
505         self.errors.has_diff
506     }
507
508     pub fn has_unformatted_code_errors(&self) -> bool {
509         self.errors.has_unformatted_code_errors
510     }
511
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()
517             || self.has_diff()
518             || self.has_unformatted_code_errors()
519             || self.errors.has_macro_format_failure)
520     }
521 }
522
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())
527         }
528         EmitMode::Files => Box::new(emitter::FilesEmitter::new(
529             config.print_misformatted_file_names(),
530         )),
531         EmitMode::Stdout | EmitMode::Coverage => {
532             Box::new(emitter::StdoutEmitter::new(config.verbose()))
533         }
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())),
538     }
539 }
540
541 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
542     fn drop(&mut self) {
543         if let Some(ref mut out) = self.out {
544             let _ = self.emitter.emit_footer(out);
545         }
546     }
547 }
548
549 #[derive(Debug)]
550 pub enum Input {
551     File(PathBuf),
552     Text(String),
553 }
554
555 impl Input {
556     fn file_name(&self) -> FileName {
557         match *self {
558             Input::File(ref file) => FileName::Real(file.clone()),
559             Input::Text(..) => FileName::Stdin,
560         }
561     }
562
563     fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
564         match self {
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),
572                     })
573                 } else {
574                     None
575                 }
576             }
577             _ => None,
578         }
579     }
580 }
581
582 #[cfg(test)]
583 mod unit_tests {
584     use super::*;
585
586     #[test]
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.
590         let snippet = "let";
591         assert!(format_snippet(snippet, &Config::default(), false).is_none());
592         assert!(format_code_block(snippet, &Config::default(), false).is_none());
593     }
594
595     fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
596     where
597         F: Fn(&str, &Config, bool) -> Option<FormattedSnippet>,
598     {
599         let output = formatter(input, &Config::default(), false);
600         output.is_some() && output.unwrap().snippet == expected
601     }
602
603     #[test]
604     fn test_format_snippet() {
605         let snippet = "fn main() { println!(\"hello, world\"); }";
606         #[cfg(not(windows))]
607         let expected = "fn main() {\n    \
608                         println!(\"hello, world\");\n\
609                         }\n";
610         #[cfg(windows)]
611         let expected = "fn main() {\r\n    \
612                         println!(\"hello, world\");\r\n\
613                         }\r\n";
614         assert!(test_format_inner(format_snippet, snippet, expected));
615     }
616
617     #[test]
618     fn test_format_code_block_fail() {
619         #[rustfmt::skip]
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());
622     }
623
624     #[test]
625     fn test_format_code_block() {
626         // simple 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));
630
631         // more complex code block, taken from chains.rs.
632         let code_block =
633 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
634 (
635 chain_indent(context, shape.add_offset(parent_rewrite.len())),
636 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
637 )
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
643 // brace.
644 IndentStyle::Visual => (parent_shape, false),
645 }
646 } else {
647 (
648 chain_indent(context, shape.add_offset(parent_rewrite.len())),
649 false,
650 )
651 };
652 ";
653         let expected =
654 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
655     (
656         chain_indent(context, shape.add_offset(parent_rewrite.len())),
657         context.config.indent_style() == IndentStyle::Visual || is_small_parent,
658     )
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
664         // brace.
665         IndentStyle::Visual => (parent_shape, false),
666     }
667 } else {
668     (
669         chain_indent(context, shape.add_offset(parent_rewrite.len())),
670         false,
671     )
672 };";
673         assert!(test_format_inner(format_code_block, code_block, expected));
674     }
675 }