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