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