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