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