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