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