]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
deny rust_2018_idioms
[rust.git] / src / lib.rs
1 // Copyright 2015-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![deny(rust_2018_idioms)]
12
13 #[macro_use]
14 extern crate derive_new;
15 #[cfg(test)]
16 #[macro_use]
17 extern crate lazy_static;
18 #[macro_use]
19 extern crate log;
20 #[macro_use]
21 extern crate serde_derive;
22
23 use std::cell::RefCell;
24 use std::collections::HashMap;
25 use std::fmt;
26 use std::io::{self, Write};
27 use std::mem;
28 use std::panic;
29 use std::path::PathBuf;
30 use std::rc::Rc;
31
32 use failure::Fail;
33 use syntax::ast;
34
35 use crate::comment::LineClasses;
36 use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
37 use crate::issues::Issue;
38 use crate::shape::Indent;
39
40 pub use crate::config::{
41     load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
42     Range, Verbosity,
43 };
44
45 #[macro_use]
46 mod utils;
47
48 mod attr;
49 mod chains;
50 pub(crate) mod checkstyle;
51 mod closures;
52 mod comment;
53 pub(crate) mod config;
54 mod expr;
55 pub(crate) mod formatting;
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.
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 }
121
122 impl ErrorKind {
123     fn is_comment(&self) -> bool {
124         match self {
125             ErrorKind::LostComment => true,
126             _ => false,
127         }
128     }
129 }
130
131 impl From<io::Error> for ErrorKind {
132     fn from(e: io::Error) -> ErrorKind {
133         ErrorKind::IoError(e)
134     }
135 }
136
137 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
138 /// i.e., that got returned as they were originally.
139 #[derive(Debug)]
140 struct FormattedSnippet {
141     snippet: String,
142     non_formatted_ranges: Vec<(usize, usize)>,
143 }
144
145 impl FormattedSnippet {
146     /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
147     /// non-formatted code.
148     fn unwrap_code_block(&mut self) {
149         self.non_formatted_ranges
150             .iter_mut()
151             .for_each(|(low, high)| {
152                 *low -= 1;
153                 *high -= 1;
154             });
155     }
156
157     /// Returns true if the line n did not get formatted.
158     fn is_line_non_formatted(&self, n: usize) -> bool {
159         self.non_formatted_ranges
160             .iter()
161             .any(|(low, high)| *low <= n && n <= *high)
162     }
163 }
164
165 /// Reports on any issues that occurred during a run of Rustfmt.
166 ///
167 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
168 #[derive(Clone)]
169 pub struct FormatReport {
170     // Maps stringified file paths to their associated formatting errors.
171     internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
172     non_formatted_ranges: Vec<(usize, usize)>,
173 }
174
175 impl FormatReport {
176     fn new() -> FormatReport {
177         FormatReport {
178             internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
179             non_formatted_ranges: Vec::new(),
180         }
181     }
182
183     fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
184         self.non_formatted_ranges.append(&mut ranges);
185     }
186
187     fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
188         self.track_errors(&v);
189         self.internal
190             .borrow_mut()
191             .0
192             .entry(f)
193             .and_modify(|fe| fe.append(&mut v))
194             .or_insert(v);
195     }
196
197     fn track_errors(&self, new_errors: &[FormattingError]) {
198         let errs = &mut self.internal.borrow_mut().1;
199         if !new_errors.is_empty() {
200             errs.has_formatting_errors = true;
201         }
202         if errs.has_operational_errors && errs.has_check_errors {
203             return;
204         }
205         for err in new_errors {
206             match err.kind {
207                 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
208                     errs.has_operational_errors = true;
209                 }
210                 ErrorKind::BadIssue(_)
211                 | ErrorKind::LicenseCheck
212                 | ErrorKind::DeprecatedAttr
213                 | ErrorKind::BadAttr
214                 | ErrorKind::VersionMismatch => {
215                     errs.has_check_errors = true;
216                 }
217                 _ => {}
218             }
219         }
220     }
221
222     fn add_diff(&mut self) {
223         self.internal.borrow_mut().1.has_diff = true;
224     }
225
226     fn add_macro_format_failure(&mut self) {
227         self.internal.borrow_mut().1.has_macro_format_failure = true;
228     }
229
230     fn add_parsing_error(&mut self) {
231         self.internal.borrow_mut().1.has_parsing_errors = true;
232     }
233
234     fn warning_count(&self) -> usize {
235         self.internal
236             .borrow()
237             .0
238             .iter()
239             .map(|(_, errors)| errors.len())
240             .sum()
241     }
242
243     /// Whether any warnings or errors are present in the report.
244     pub fn has_warnings(&self) -> bool {
245         self.internal.borrow().1.has_formatting_errors
246     }
247
248     /// Print the report to a terminal using colours and potentially other
249     /// fancy output.
250     pub fn fancy_print(
251         &self,
252         mut t: Box<term::Terminal<Output = io::Stderr>>,
253     ) -> Result<(), term::Error> {
254         for (file, errors) in &self.internal.borrow().0 {
255             for error in errors {
256                 let prefix_space_len = error.line.to_string().len();
257                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
258
259                 // First line: the overview of error
260                 t.fg(term::color::RED)?;
261                 t.attr(term::Attr::Bold)?;
262                 write!(t, "{} ", error.msg_prefix())?;
263                 t.reset()?;
264                 t.attr(term::Attr::Bold)?;
265                 writeln!(t, "{}", error.kind)?;
266
267                 // Second line: file info
268                 write!(t, "{}--> ", &prefix_spaces[1..])?;
269                 t.reset()?;
270                 writeln!(t, "{}:{}", file, error.line)?;
271
272                 // Third to fifth lines: show the line which triggered error, if available.
273                 if !error.line_buffer.is_empty() {
274                     let (space_len, target_len) = error.format_len();
275                     t.attr(term::Attr::Bold)?;
276                     write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
277                     t.reset()?;
278                     writeln!(t, "{}", error.line_buffer)?;
279                     t.attr(term::Attr::Bold)?;
280                     write!(t, "{}| ", prefix_spaces)?;
281                     t.fg(term::color::RED)?;
282                     writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
283                     t.reset()?;
284                 }
285
286                 // The last line: show note if available.
287                 let msg_suffix = error.msg_suffix();
288                 if !msg_suffix.is_empty() {
289                     t.attr(term::Attr::Bold)?;
290                     write!(t, "{}= note: ", prefix_spaces)?;
291                     t.reset()?;
292                     writeln!(t, "{}", error.msg_suffix())?;
293                 } else {
294                     writeln!(t)?;
295                 }
296                 t.reset()?;
297             }
298         }
299
300         if !self.internal.borrow().0.is_empty() {
301             t.attr(term::Attr::Bold)?;
302             write!(t, "warning: ")?;
303             t.reset()?;
304             write!(
305                 t,
306                 "rustfmt may have failed to format. See previous {} errors.\n\n",
307                 self.warning_count(),
308             )?;
309         }
310
311         Ok(())
312     }
313
314     fn target_str(space_len: usize, target_len: usize) -> String {
315         let empty_line = " ".repeat(space_len);
316         let overflowed = "^".repeat(target_len);
317         empty_line + &overflowed
318     }
319 }
320
321 impl fmt::Display for FormatReport {
322     // Prints all the formatting errors.
323     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
324         for (file, errors) in &self.internal.borrow().0 {
325             for error in errors {
326                 let prefix_space_len = error.line.to_string().len();
327                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
328
329                 let error_line_buffer = if error.line_buffer.is_empty() {
330                     String::from(" ")
331                 } else {
332                     let (space_len, target_len) = error.format_len();
333                     format!(
334                         "{}|\n{} | {}\n{}| {}",
335                         prefix_spaces,
336                         error.line,
337                         error.line_buffer,
338                         prefix_spaces,
339                         FormatReport::target_str(space_len, target_len)
340                     )
341                 };
342
343                 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
344                 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
345                 let msg_suffix = error.msg_suffix();
346                 let note = if msg_suffix.is_empty() {
347                     String::new()
348                 } else {
349                     format!("{}note= ", prefix_spaces)
350                 };
351
352                 writeln!(
353                     fmt,
354                     "{}\n{}\n{}\n{}{}",
355                     error_info,
356                     file_info,
357                     error_line_buffer,
358                     note,
359                     error.msg_suffix()
360                 )?;
361             }
362         }
363         if !self.internal.borrow().0.is_empty() {
364             writeln!(
365                 fmt,
366                 "warning: rustfmt may have failed to format. See previous {} errors.",
367                 self.warning_count(),
368             )?;
369         }
370         Ok(())
371     }
372 }
373
374 /// Format the given snippet. The snippet is expected to be *complete* code.
375 /// When we cannot parse the given snippet, this function returns `None`.
376 fn format_snippet(snippet: &str, config: &Config) -> Option<FormattedSnippet> {
377     let mut config = config.clone();
378     panic::catch_unwind(|| {
379         let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
380         config.set().emit_mode(config::EmitMode::Stdout);
381         config.set().verbose(Verbosity::Quiet);
382         config.set().hide_parse_errors(true);
383
384         let (formatting_error, result) = {
385             let input = Input::Text(snippet.into());
386             let mut session = Session::new(config, Some(&mut out));
387             let result = session.format(input);
388             (
389                 session.errors.has_macro_format_failure
390                     || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
391                     || result.is_err(),
392                 result,
393             )
394         };
395         if formatting_error {
396             None
397         } else {
398             String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
399                 snippet,
400                 non_formatted_ranges: result.unwrap().non_formatted_ranges,
401             })
402         }
403     })
404     // Discard panics encountered while formatting the snippet
405     // The ? operator is needed to remove the extra Option
406     .ok()?
407 }
408
409 /// Format the given code block. Mainly targeted for code block in comment.
410 /// The code block may be incomplete (i.e. parser may be unable to parse it).
411 /// To avoid panic in parser, we wrap the code block with a dummy function.
412 /// The returned code block does *not* end with newline.
413 fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSnippet> {
414     const FN_MAIN_PREFIX: &str = "fn main() {\n";
415
416     fn enclose_in_main_block(s: &str, config: &Config) -> String {
417         let indent = Indent::from_width(config, config.tab_spaces());
418         let mut result = String::with_capacity(s.len() * 2);
419         result.push_str(FN_MAIN_PREFIX);
420         let mut need_indent = true;
421         for (kind, line) in LineClasses::new(s) {
422             if need_indent {
423                 result.push_str(&indent.to_string(config));
424             }
425             result.push_str(&line);
426             result.push('\n');
427             need_indent = !kind.is_string() || line.ends_with('\\');
428         }
429         result.push('}');
430         result
431     }
432
433     // Wrap the given code block with `fn main()` if it does not have one.
434     let snippet = enclose_in_main_block(code_snippet, config);
435     let mut result = String::with_capacity(snippet.len());
436     let mut is_first = true;
437
438     // While formatting the code, ignore the config's newline style setting and always use "\n"
439     // instead of "\r\n" for the newline characters. This is okay because the output here is
440     // not directly outputted by rustfmt command, but used by the comment formatter's input.
441     // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
442     let mut config_with_unix_newline = config.clone();
443     config_with_unix_newline
444         .set()
445         .newline_style(NewlineStyle::Unix);
446     let mut formatted = format_snippet(&snippet, &config_with_unix_newline)?;
447     // Remove wrapping main block
448     formatted.unwrap_code_block();
449
450     // Trim "fn main() {" on the first line and "}" on the last line,
451     // then unindent the whole code block.
452     let block_len = formatted
453         .snippet
454         .rfind('}')
455         .unwrap_or(formatted.snippet.len());
456     let mut is_indented = true;
457     for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
458         if !is_first {
459             result.push('\n');
460         } else {
461             is_first = false;
462         }
463         let trimmed_line = if !is_indented {
464             line
465         } else if line.len() > config.max_width() {
466             // If there are lines that are larger than max width, we cannot tell
467             // whether we have succeeded but have some comments or strings that
468             // are too long, or we have failed to format code block. We will be
469             // conservative and just return `None` in this case.
470             return None;
471         } else if line.len() > config.tab_spaces() {
472             // Make sure that the line has leading whitespaces.
473             let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
474             if line.starts_with(indent_str.as_ref()) {
475                 let offset = if config.hard_tabs() {
476                     1
477                 } else {
478                     config.tab_spaces()
479                 };
480                 &line[offset..]
481             } else {
482                 line
483             }
484         } else {
485             line
486         };
487         result.push_str(trimmed_line);
488         is_indented = !kind.is_string() || line.ends_with('\\');
489     }
490     Some(FormattedSnippet {
491         snippet: result,
492         non_formatted_ranges: formatted.non_formatted_ranges,
493     })
494 }
495
496 /// A session is a run of rustfmt across a single or multiple inputs.
497 pub struct Session<'b, T: Write + 'b> {
498     pub config: Config,
499     pub out: Option<&'b mut T>,
500     pub(crate) errors: ReportedErrors,
501     source_file: SourceFile,
502 }
503
504 impl<'b, T: Write + 'b> Session<'b, T> {
505     pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
506         if config.emit_mode() == EmitMode::Checkstyle {
507             println!("{}", checkstyle::header());
508         }
509
510         Session {
511             config,
512             out,
513             errors: ReportedErrors::default(),
514             source_file: SourceFile::new(),
515         }
516     }
517
518     /// The main entry point for Rustfmt. Formats the given input according to the
519     /// given config. `out` is only necessary if required by the configuration.
520     pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
521         self.format_input_inner(input)
522     }
523
524     pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
525     where
526         F: FnOnce(&mut Session<'b, T>) -> U,
527     {
528         mem::swap(&mut config, &mut self.config);
529         let result = f(self);
530         mem::swap(&mut config, &mut self.config);
531         result
532     }
533
534     pub fn add_operational_error(&mut self) {
535         self.errors.has_operational_errors = true;
536     }
537
538     pub fn has_operational_errors(&self) -> bool {
539         self.errors.has_operational_errors
540     }
541
542     pub fn has_parsing_errors(&self) -> bool {
543         self.errors.has_parsing_errors
544     }
545
546     pub fn has_formatting_errors(&self) -> bool {
547         self.errors.has_formatting_errors
548     }
549
550     pub fn has_check_errors(&self) -> bool {
551         self.errors.has_check_errors
552     }
553
554     pub fn has_diff(&self) -> bool {
555         self.errors.has_diff
556     }
557
558     pub fn has_no_errors(&self) -> bool {
559         !(self.has_operational_errors()
560             || self.has_parsing_errors()
561             || self.has_formatting_errors()
562             || self.has_check_errors()
563             || self.has_diff())
564             || self.errors.has_macro_format_failure
565     }
566 }
567
568 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
569     fn drop(&mut self) {
570         if self.config.emit_mode() == EmitMode::Checkstyle {
571             println!("{}", checkstyle::footer());
572         }
573     }
574 }
575
576 #[derive(Debug)]
577 pub enum Input {
578     File(PathBuf),
579     Text(String),
580 }
581
582 impl Input {
583     fn is_text(&self) -> bool {
584         match *self {
585             Input::File(_) => false,
586             Input::Text(_) => true,
587         }
588     }
589
590     fn file_name(&self) -> FileName {
591         match *self {
592             Input::File(ref file) => FileName::Real(file.clone()),
593             Input::Text(..) => FileName::Stdin,
594         }
595     }
596 }
597
598 #[cfg(test)]
599 mod unit_tests {
600     use super::*;
601
602     #[test]
603     fn test_no_panic_on_format_snippet_and_format_code_block() {
604         // `format_snippet()` and `format_code_block()` should not panic
605         // even when we cannot parse the given snippet.
606         let snippet = "let";
607         assert!(format_snippet(snippet, &Config::default()).is_none());
608         assert!(format_code_block(snippet, &Config::default()).is_none());
609     }
610
611     fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
612     where
613         F: Fn(&str, &Config) -> Option<FormattedSnippet>,
614     {
615         let output = formatter(input, &Config::default());
616         output.is_some() && output.unwrap().snippet == expected
617     }
618
619     #[test]
620     fn test_format_snippet() {
621         let snippet = "fn main() { println!(\"hello, world\"); }";
622         #[cfg(not(windows))]
623         let expected = "fn main() {\n    \
624                         println!(\"hello, world\");\n\
625                         }\n";
626         #[cfg(windows)]
627         let expected = "fn main() {\r\n    \
628                         println!(\"hello, world\");\r\n\
629                         }\r\n";
630         assert!(test_format_inner(format_snippet, snippet, expected));
631     }
632
633     #[test]
634     fn test_format_code_block_fail() {
635         #[rustfmt::skip]
636         let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
637         assert!(format_code_block(code_block, &Config::default()).is_none());
638     }
639
640     #[test]
641     fn test_format_code_block() {
642         // simple code block
643         let code_block = "let x=3;";
644         let expected = "let x = 3;";
645         assert!(test_format_inner(format_code_block, code_block, expected));
646
647         // more complex code block, taken from chains.rs.
648         let code_block =
649 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
650 (
651 chain_indent(context, shape.add_offset(parent_rewrite.len())),
652 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
653 )
654 } else if is_block_expr(context, &parent, &parent_rewrite) {
655 match context.config.indent_style() {
656 // Try to put the first child on the same line with parent's last line
657 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
658 // The parent is a block, so align the rest of the chain with the closing
659 // brace.
660 IndentStyle::Visual => (parent_shape, false),
661 }
662 } else {
663 (
664 chain_indent(context, shape.add_offset(parent_rewrite.len())),
665 false,
666 )
667 };
668 ";
669         let expected =
670 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
671     (
672         chain_indent(context, shape.add_offset(parent_rewrite.len())),
673         context.config.indent_style() == IndentStyle::Visual || is_small_parent,
674     )
675 } else if is_block_expr(context, &parent, &parent_rewrite) {
676     match context.config.indent_style() {
677         // Try to put the first child on the same line with parent's last line
678         IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
679         // The parent is a block, so align the rest of the chain with the closing
680         // brace.
681         IndentStyle::Visual => (parent_shape, false),
682     }
683 } else {
684     (
685         chain_indent(context, shape.add_offset(parent_rewrite.len())),
686         false,
687     )
688 };";
689         assert!(test_format_inner(format_code_block, code_block, expected));
690     }
691 }