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