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