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