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