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