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