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