]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
fix: Don't insert an extra brace in macros with native newlines
[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(custom_attribute)]
12 #![feature(decl_macro)]
13 // FIXME(cramertj) remove after match_default_bindings merges
14 #![allow(stable_features)]
15 #![allow(unused_attributes)]
16 #![feature(match_default_bindings)]
17 #![feature(type_ascription)]
18 #![feature(unicode_internals)]
19
20 #[macro_use]
21 extern crate derive_new;
22 extern crate diff;
23 #[macro_use]
24 extern crate failure;
25 extern crate getopts;
26 extern crate itertools;
27 #[cfg(test)]
28 #[macro_use]
29 extern crate lazy_static;
30 #[macro_use]
31 extern crate log;
32 extern crate regex;
33 extern crate rustc_target;
34 extern crate serde;
35 #[macro_use]
36 extern crate serde_derive;
37 extern crate serde_json;
38 extern crate syntax;
39 extern crate term;
40 extern crate toml;
41 extern crate unicode_segmentation;
42
43 use std::collections::HashMap;
44 use std::fmt;
45 use std::io::{self, stdout, Write};
46 use std::panic::{catch_unwind, AssertUnwindSafe};
47 use std::path::PathBuf;
48 use std::rc::Rc;
49 use std::time::Duration;
50
51 use syntax::ast;
52 pub use syntax::codemap::FileName;
53 use syntax::codemap::{CodeMap, FilePathMapping};
54 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
55 use syntax::errors::{DiagnosticBuilder, Handler};
56 use syntax::parse::{self, ParseSess};
57
58 use comment::{CharClasses, FullCodeCharKind, LineClasses};
59 use failure::Fail;
60 use issues::{BadIssueSeeker, Issue};
61 use shape::Indent;
62 use utils::use_colored_tty;
63 use visitor::{FmtVisitor, SnippetProvider};
64
65 pub use config::options::CliOptions;
66 pub use config::summary::Summary;
67 pub use config::{file_lines, load_config, Config, WriteMode};
68
69 pub type FmtResult<T> = std::result::Result<T, failure::Error>;
70
71 pub const WRITE_MODE_LIST: &str =
72     "[replace|overwrite|display|plain|diff|coverage|checkstyle|check]";
73
74 #[macro_use]
75 mod utils;
76
77 mod attr;
78 mod chains;
79 pub(crate) mod checkstyle;
80 mod closures;
81 pub(crate) mod codemap;
82 mod comment;
83 pub(crate) mod config;
84 mod expr;
85 pub(crate) mod filemap;
86 mod imports;
87 mod issues;
88 mod items;
89 mod lists;
90 mod macros;
91 mod matches;
92 mod missed_spans;
93 pub(crate) mod modules;
94 mod overflow;
95 mod patterns;
96 mod reorder;
97 mod rewrite;
98 pub(crate) mod rustfmt_diff;
99 mod shape;
100 mod spanned;
101 mod string;
102 #[cfg(test)]
103 mod test;
104 mod types;
105 mod vertical;
106 pub(crate) mod visitor;
107
108 const STDIN: &str = "<stdin>";
109
110 // A map of the files of a crate, with their new content
111 pub(crate) type FileMap = Vec<FileRecord>;
112
113 pub(crate) type FileRecord = (FileName, String);
114
115 #[derive(Fail, Debug, Clone, Copy)]
116 pub enum ErrorKind {
117     // Line has exceeded character limit (found, maximum)
118     #[fail(
119         display = "line formatted, but exceeded maximum width \
120                    (maximum: {} (see `max_width` option), found: {})",
121         _0,
122         _1
123     )]
124     LineOverflow(usize, usize),
125     // Line ends in whitespace
126     #[fail(display = "left behind trailing whitespace")]
127     TrailingWhitespace,
128     // TODO or FIXME item without an issue number
129     #[fail(display = "found {}", _0)]
130     BadIssue(Issue),
131     // License check has failed
132     #[fail(display = "license check failed")]
133     LicenseCheck,
134 }
135
136 // Formatting errors that are identified *after* rustfmt has run.
137 struct FormattingError {
138     line: usize,
139     kind: ErrorKind,
140     is_comment: bool,
141     is_string: bool,
142     line_buffer: String,
143 }
144
145 impl FormattingError {
146     fn msg_prefix(&self) -> &str {
147         match self.kind {
148             ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
149             ErrorKind::LicenseCheck => "error:",
150             ErrorKind::BadIssue(_) => "warning:",
151         }
152     }
153
154     fn msg_suffix(&self) -> &str {
155         if self.is_comment || self.is_string {
156             "set `error_on_unformatted = false` to suppress \
157              the warning against comments or string literals\n"
158         } else {
159             ""
160         }
161     }
162
163     // (space, target)
164     fn format_len(&self) -> (usize, usize) {
165         match self.kind {
166             ErrorKind::LineOverflow(found, max) => (max, found - max),
167             ErrorKind::TrailingWhitespace => {
168                 let trailing_ws_start = self.line_buffer
169                     .rfind(|c: char| !c.is_whitespace())
170                     .map(|pos| pos + 1)
171                     .unwrap_or(0);
172                 (
173                     trailing_ws_start,
174                     self.line_buffer.len() - trailing_ws_start,
175                 )
176             }
177             _ => unreachable!(),
178         }
179     }
180 }
181
182 pub struct FormatReport {
183     // Maps stringified file paths to their associated formatting errors.
184     file_error_map: HashMap<FileName, Vec<FormattingError>>,
185 }
186
187 impl FormatReport {
188     fn new() -> FormatReport {
189         FormatReport {
190             file_error_map: HashMap::new(),
191         }
192     }
193
194     fn warning_count(&self) -> usize {
195         self.file_error_map
196             .iter()
197             .map(|(_, errors)| errors.len())
198             .sum()
199     }
200
201     fn has_warnings(&self) -> bool {
202         self.warning_count() > 0
203     }
204
205     fn print_warnings_fancy(
206         &self,
207         mut t: Box<term::Terminal<Output = io::Stderr>>,
208     ) -> Result<(), term::Error> {
209         for (file, errors) in &self.file_error_map {
210             for error in errors {
211                 let prefix_space_len = error.line.to_string().len();
212                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
213
214                 // First line: the overview of error
215                 t.fg(term::color::RED)?;
216                 t.attr(term::Attr::Bold)?;
217                 write!(t, "{} ", error.msg_prefix())?;
218                 t.reset()?;
219                 t.attr(term::Attr::Bold)?;
220                 writeln!(t, "{}", error.kind)?;
221
222                 // Second line: file info
223                 write!(t, "{}--> ", &prefix_spaces[1..])?;
224                 t.reset()?;
225                 writeln!(t, "{}:{}", file, error.line)?;
226
227                 // Third to fifth lines: show the line which triggered error, if available.
228                 if !error.line_buffer.is_empty() {
229                     let (space_len, target_len) = error.format_len();
230                     t.attr(term::Attr::Bold)?;
231                     write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
232                     t.reset()?;
233                     writeln!(t, "{}", error.line_buffer)?;
234                     t.attr(term::Attr::Bold)?;
235                     write!(t, "{}| ", prefix_spaces)?;
236                     t.fg(term::color::RED)?;
237                     writeln!(t, "{}", target_str(space_len, target_len))?;
238                     t.reset()?;
239                 }
240
241                 // The last line: show note if available.
242                 let msg_suffix = error.msg_suffix();
243                 if !msg_suffix.is_empty() {
244                     t.attr(term::Attr::Bold)?;
245                     write!(t, "{}= note: ", prefix_spaces)?;
246                     t.reset()?;
247                     writeln!(t, "{}", error.msg_suffix())?;
248                 } else {
249                     writeln!(t)?;
250                 }
251                 t.reset()?;
252             }
253         }
254
255         if !self.file_error_map.is_empty() {
256             t.attr(term::Attr::Bold)?;
257             write!(t, "warning: ")?;
258             t.reset()?;
259             write!(
260                 t,
261                 "rustfmt may have failed to format. See previous {} errors.\n\n",
262                 self.warning_count(),
263             )?;
264         }
265
266         Ok(())
267     }
268 }
269
270 fn target_str(space_len: usize, target_len: usize) -> String {
271     let empty_line = " ".repeat(space_len);
272     let overflowed = "^".repeat(target_len);
273     empty_line + &overflowed
274 }
275
276 impl fmt::Display for FormatReport {
277     // Prints all the formatting errors.
278     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
279         for (file, errors) in &self.file_error_map {
280             for error in errors {
281                 let prefix_space_len = error.line.to_string().len();
282                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
283
284                 let error_line_buffer = if error.line_buffer.is_empty() {
285                     String::from(" ")
286                 } else {
287                     let (space_len, target_len) = error.format_len();
288                     format!(
289                         "{}|\n{} | {}\n{}| {}",
290                         prefix_spaces,
291                         error.line,
292                         error.line_buffer,
293                         prefix_spaces,
294                         target_str(space_len, target_len)
295                     )
296                 };
297
298                 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
299                 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
300                 let msg_suffix = error.msg_suffix();
301                 let note = if msg_suffix.is_empty() {
302                     String::new()
303                 } else {
304                     format!("{}note= ", prefix_spaces)
305                 };
306
307                 writeln!(
308                     fmt,
309                     "{}\n{}\n{}\n{}{}",
310                     error_info,
311                     file_info,
312                     error_line_buffer,
313                     note,
314                     error.msg_suffix()
315                 )?;
316             }
317         }
318         if !self.file_error_map.is_empty() {
319             writeln!(
320                 fmt,
321                 "warning: rustfmt may have failed to format. See previous {} errors.",
322                 self.warning_count(),
323             )?;
324         }
325         Ok(())
326     }
327 }
328
329 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
330 where
331     F: Fn(),
332 {
333     if config.verbose() && path.to_string() != STDIN {
334         f();
335     }
336 }
337
338 // Formatting which depends on the AST.
339 fn format_ast<F>(
340     krate: &ast::Crate,
341     parse_session: &mut ParseSess,
342     main_file: &FileName,
343     config: &Config,
344     mut after_file: F,
345 ) -> Result<(FileMap, bool), io::Error>
346 where
347     F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
348 {
349     let mut result = FileMap::new();
350     // diff mode: check if any files are differing
351     let mut has_diff = false;
352
353     // We always skip children for the "Plain" write mode, since there is
354     // nothing to distinguish the nested module contents.
355     let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
356     for (path, module) in modules::list_files(krate, parse_session.codemap())? {
357         if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
358             continue;
359         }
360         should_emit_verbose(&path, config, || println!("Formatting {}", path));
361         let filemap = parse_session
362             .codemap()
363             .lookup_char_pos(module.inner.lo())
364             .file;
365         let big_snippet = filemap.src.as_ref().unwrap();
366         let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
367         let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
368         // Format inner attributes if available.
369         if !krate.attrs.is_empty() && path == *main_file {
370             visitor.skip_empty_lines(filemap.end_pos);
371             if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
372                 visitor.push_rewrite(module.inner, None);
373             } else {
374                 visitor.format_separate_mod(module, &*filemap);
375             }
376         } else {
377             visitor.last_pos = filemap.start_pos;
378             visitor.skip_empty_lines(filemap.end_pos);
379             visitor.format_separate_mod(module, &*filemap);
380         };
381
382         debug_assert_eq!(
383             visitor.line_number,
384             ::utils::count_newlines(&visitor.buffer)
385         );
386
387         let filename = path.clone();
388         has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
389             Ok(result) => result,
390             Err(e) => {
391                 // Create a new error with path_str to help users see which files failed
392                 let err_msg = format!("{}: {}", path, e);
393                 return Err(io::Error::new(e.kind(), err_msg));
394             }
395         };
396
397         result.push((filename, visitor.buffer));
398     }
399
400     Ok((result, has_diff))
401 }
402
403 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
404 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
405     skipped_range
406         .iter()
407         .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
408 }
409
410 fn should_report_error(
411     config: &Config,
412     char_kind: FullCodeCharKind,
413     is_string: bool,
414     error_kind: ErrorKind,
415 ) -> bool {
416     let allow_error_report = if char_kind.is_comment() || is_string {
417         config.error_on_unformatted()
418     } else {
419         true
420     };
421
422     match error_kind {
423         ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
424         ErrorKind::TrailingWhitespace => allow_error_report,
425         _ => true,
426     }
427 }
428
429 // Formatting done on a char by char or line by line basis.
430 // FIXME(#20) other stuff for parity with make tidy
431 fn format_lines(
432     text: &mut String,
433     name: &FileName,
434     skipped_range: &[(usize, usize)],
435     config: &Config,
436     report: &mut FormatReport,
437 ) {
438     let mut trims = vec![];
439     let mut last_wspace: Option<usize> = None;
440     let mut line_len = 0;
441     let mut cur_line = 1;
442     let mut newline_count = 0;
443     let mut errors = vec![];
444     let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
445     let mut line_buffer = String::with_capacity(config.max_width() * 2);
446     let mut is_string = false; // true if the current line contains a string literal.
447     let mut format_line = config.file_lines().contains_line(name, cur_line);
448     let allow_issue_seek = !issue_seeker.is_disabled();
449
450     // Check license.
451     if let Some(ref license_template) = config.license_template {
452         if !license_template.is_match(text) {
453             errors.push(FormattingError {
454                 line: cur_line,
455                 kind: ErrorKind::LicenseCheck,
456                 is_comment: false,
457                 is_string: false,
458                 line_buffer: String::new(),
459             });
460         }
461     }
462
463     // Iterate over the chars in the file map.
464     for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
465         if c == '\r' {
466             continue;
467         }
468
469         if allow_issue_seek && format_line {
470             // Add warnings for bad todos/ fixmes
471             if let Some(issue) = issue_seeker.inspect(c) {
472                 errors.push(FormattingError {
473                     line: cur_line,
474                     kind: ErrorKind::BadIssue(issue),
475                     is_comment: false,
476                     is_string: false,
477                     line_buffer: String::new(),
478                 });
479             }
480         }
481
482         if c == '\n' {
483             if format_line {
484                 // Check for (and record) trailing whitespace.
485                 if let Some(..) = last_wspace {
486                     if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
487                         trims.push((cur_line, kind, line_buffer.clone()));
488                     }
489                     line_len -= 1;
490                 }
491
492                 // Check for any line width errors we couldn't correct.
493                 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
494                 if line_len > config.max_width()
495                     && !is_skipped_line(cur_line, skipped_range)
496                     && should_report_error(config, kind, is_string, error_kind)
497                 {
498                     errors.push(FormattingError {
499                         line: cur_line,
500                         kind: error_kind,
501                         is_comment: kind.is_comment(),
502                         is_string,
503                         line_buffer: line_buffer.clone(),
504                     });
505                 }
506             }
507
508             line_len = 0;
509             cur_line += 1;
510             format_line = config.file_lines().contains_line(name, cur_line);
511             newline_count += 1;
512             last_wspace = None;
513             line_buffer.clear();
514             is_string = false;
515         } else {
516             newline_count = 0;
517             line_len += if c == '\t' { config.tab_spaces() } else { 1 };
518             if c.is_whitespace() {
519                 if last_wspace.is_none() {
520                     last_wspace = Some(b);
521                 }
522             } else {
523                 last_wspace = None;
524             }
525             line_buffer.push(c);
526             if kind.is_string() {
527                 is_string = true;
528             }
529         }
530     }
531
532     if newline_count > 1 {
533         debug!("track truncate: {} {}", text.len(), newline_count);
534         let line = text.len() - newline_count + 1;
535         text.truncate(line);
536     }
537
538     for &(l, kind, ref b) in &trims {
539         if !is_skipped_line(l, skipped_range) {
540             errors.push(FormattingError {
541                 line: l,
542                 kind: ErrorKind::TrailingWhitespace,
543                 is_comment: kind.is_comment(),
544                 is_string: kind.is_string(),
545                 line_buffer: b.clone(),
546             });
547         }
548     }
549
550     report.file_error_map.insert(name.clone(), errors);
551 }
552
553 fn parse_input<'sess>(
554     input: Input,
555     parse_session: &'sess ParseSess,
556     config: &Config,
557 ) -> Result<ast::Crate, ParseError<'sess>> {
558     let mut parser = match input {
559         Input::File(file) => parse::new_parser_from_file(parse_session, &file),
560         Input::Text(text) => parse::new_parser_from_source_str(
561             parse_session,
562             FileName::Custom("stdin".to_owned()),
563             text,
564         ),
565     };
566
567     parser.cfg_mods = false;
568     if config.skip_children() {
569         parser.recurse_into_file_modules = false;
570     }
571
572     let mut parser = AssertUnwindSafe(parser);
573     let result = catch_unwind(move || parser.0.parse_crate_mod());
574
575     match result {
576         Ok(Ok(c)) => {
577             if parse_session.span_diagnostic.has_errors() {
578                 // Bail out if the parser recovered from an error.
579                 Err(ParseError::Recovered)
580             } else {
581                 Ok(c)
582             }
583         }
584         Ok(Err(e)) => Err(ParseError::Error(e)),
585         Err(_) => Err(ParseError::Panic),
586     }
587 }
588
589 /// All the ways that parsing can fail.
590 enum ParseError<'sess> {
591     /// There was an error, but the parser recovered.
592     Recovered,
593     /// There was an error (supplied) and parsing failed.
594     Error(DiagnosticBuilder<'sess>),
595     /// The parser panicked.
596     Panic,
597 }
598
599 /// Format the given snippet. The snippet is expected to be *complete* code.
600 /// When we cannot parse the given snippet, this function returns `None`.
601 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
602     let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
603     let input = Input::Text(snippet.into());
604     let mut config = config.clone();
605     config.set().write_mode(config::WriteMode::Plain);
606     config.set().hide_parse_errors(true);
607     match format_input(input, &config, Some(&mut out)) {
608         // `format_input()` returns an empty string on parsing error.
609         Ok(..) if out.is_empty() && !snippet.is_empty() => None,
610         Ok(..) => String::from_utf8(out).ok(),
611         Err(..) => None,
612     }
613 }
614
615 const FN_MAIN_PREFIX: &str = "fn main() {\n";
616
617 fn enclose_in_main_block(s: &str, config: &Config) -> String {
618     let indent = Indent::from_width(config, config.tab_spaces());
619     let mut result = String::with_capacity(s.len() * 2);
620     result.push_str(FN_MAIN_PREFIX);
621     let mut need_indent = true;
622     for (kind, line) in LineClasses::new(s) {
623         if need_indent {
624             result.push_str(&indent.to_string(config));
625         }
626         result.push_str(&line);
627         result.push('\n');
628         need_indent = !kind.is_string() || line.ends_with('\\');
629     }
630     result.push('}');
631     result
632 }
633
634 /// Format the given code block. Mainly targeted for code block in comment.
635 /// The code block may be incomplete (i.e. parser may be unable to parse it).
636 /// To avoid panic in parser, we wrap the code block with a dummy function.
637 /// The returned code block does *not* end with newline.
638 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
639     // Wrap the given code block with `fn main()` if it does not have one.
640     let snippet = enclose_in_main_block(code_snippet, config);
641     let mut result = String::with_capacity(snippet.len());
642     let mut is_first = true;
643
644     // Trim "fn main() {" on the first line and "}" on the last line,
645     // then unindent the whole code block.
646     let formatted = format_snippet(&snippet, config)?;
647     // 2 = "}\n"
648     let block_len = formatted.rfind('}').unwrap_or(formatted.len());
649     let mut is_indented = true;
650     for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
651         if !is_first {
652             result.push('\n');
653         } else {
654             is_first = false;
655         }
656         let trimmed_line = if !is_indented {
657             line
658         } else if line.len() > config.max_width() {
659             // If there are lines that are larger than max width, we cannot tell
660             // whether we have succeeded but have some comments or strings that
661             // are too long, or we have failed to format code block. We will be
662             // conservative and just return `None` in this case.
663             return None;
664         } else if line.len() > config.tab_spaces() {
665             // Make sure that the line has leading whitespaces.
666             let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
667             if line.starts_with(indent_str.as_ref()) {
668                 let offset = if config.hard_tabs() {
669                     1
670                 } else {
671                     config.tab_spaces()
672                 };
673                 &line[offset..]
674             } else {
675                 line
676             }
677         } else {
678             line
679         };
680         result.push_str(trimmed_line);
681         is_indented = !kind.is_string() || line.ends_with('\\');
682     }
683     Some(result)
684 }
685
686 pub fn format_input<T: Write>(
687     input: Input,
688     config: &Config,
689     out: Option<&mut T>,
690 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
691     syntax::with_globals(|| format_input_inner(input, config, out))
692 }
693
694 fn format_input_inner<T: Write>(
695     input: Input,
696     config: &Config,
697     mut out: Option<&mut T>,
698 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
699     let mut summary = Summary::default();
700     if config.disable_all_formatting() {
701         // When the input is from stdin, echo back the input.
702         if let Input::Text(ref buf) = input {
703             if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
704                 return Err((e, summary));
705             }
706         }
707         return Ok((summary, FileMap::new(), FormatReport::new()));
708     }
709     let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
710
711     let tty_handler = if config.hide_parse_errors() {
712         let silent_emitter = Box::new(EmitterWriter::new(
713             Box::new(Vec::new()),
714             Some(codemap.clone()),
715             false,
716             false,
717         ));
718         Handler::with_emitter(true, false, silent_emitter)
719     } else {
720         let supports_color = term::stderr().map_or(false, |term| term.supports_color());
721         let color_cfg = if supports_color {
722             ColorConfig::Auto
723         } else {
724             ColorConfig::Never
725         };
726         Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
727     };
728     let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
729
730     let main_file = match input {
731         Input::File(ref file) => FileName::Real(file.clone()),
732         Input::Text(..) => FileName::Custom("stdin".to_owned()),
733     };
734
735     let krate = match parse_input(input, &parse_session, config) {
736         Ok(krate) => krate,
737         Err(err) => {
738             match err {
739                 ParseError::Error(mut diagnostic) => diagnostic.emit(),
740                 ParseError::Panic => {
741                     // Note that if you see this message and want more information,
742                     // then go to `parse_input` and run the parse function without
743                     // `catch_unwind` so rustfmt panics and you can get a backtrace.
744                     should_emit_verbose(&main_file, config, || {
745                         println!("The Rust parser panicked")
746                     });
747                 }
748                 ParseError::Recovered => {}
749             }
750             summary.add_parsing_error();
751             return Ok((summary, FileMap::new(), FormatReport::new()));
752         }
753     };
754
755     summary.mark_parse_time();
756
757     // Suppress error output after parsing.
758     let silent_emitter = Box::new(EmitterWriter::new(
759         Box::new(Vec::new()),
760         Some(codemap.clone()),
761         false,
762         false,
763     ));
764     parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
765
766     let mut report = FormatReport::new();
767
768     let format_result = format_ast(
769         &krate,
770         &mut parse_session,
771         &main_file,
772         config,
773         |file_name, file, skipped_range| {
774             // For some reason, the codemap does not include terminating
775             // newlines so we must add one on for each file. This is sad.
776             filemap::append_newline(file);
777
778             format_lines(file, file_name, skipped_range, config, &mut report);
779
780             if let Some(ref mut out) = out {
781                 return filemap::write_file(file, file_name, out, config);
782             }
783             Ok(false)
784         },
785     );
786
787     summary.mark_format_time();
788
789     should_emit_verbose(&main_file, config, || {
790         fn duration_to_f32(d: Duration) -> f32 {
791             d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
792         }
793
794         println!(
795             "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
796             duration_to_f32(summary.get_parse_time().unwrap()),
797             duration_to_f32(summary.get_format_time().unwrap()),
798         )
799     });
800
801     match format_result {
802         Ok((file_map, has_diff)) => {
803             if report.has_warnings() {
804                 summary.add_formatting_error();
805             }
806
807             if has_diff {
808                 summary.add_diff();
809             }
810
811             Ok((summary, file_map, report))
812         }
813         Err(e) => Err((e, summary)),
814     }
815 }
816
817 /// A single span of changed lines, with 0 or more removed lines
818 /// and a vector of 0 or more inserted lines.
819 #[derive(Debug, PartialEq, Eq)]
820 struct ModifiedChunk {
821     /// The first to be removed from the original text
822     pub line_number_orig: u32,
823     /// The number of lines which have been replaced
824     pub lines_removed: u32,
825     /// The new lines
826     pub lines: Vec<String>,
827 }
828
829 /// Set of changed sections of a file.
830 #[derive(Debug, PartialEq, Eq)]
831 struct ModifiedLines {
832     /// The set of changed chunks.
833     pub chunks: Vec<ModifiedChunk>,
834 }
835
836 /// The successful result of formatting via `get_modified_lines()`.
837 #[cfg(test)]
838 struct ModifiedLinesResult {
839     /// The high level summary details
840     pub summary: Summary,
841     /// The result Filemap
842     pub filemap: FileMap,
843     /// Map of formatting errors
844     pub report: FormatReport,
845     /// The sets of updated lines.
846     pub modified_lines: ModifiedLines,
847 }
848
849 /// Format a file and return a `ModifiedLines` data structure describing
850 /// the changed ranges of lines.
851 #[cfg(test)]
852 fn get_modified_lines(
853     input: Input,
854     config: &Config,
855 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
856     use std::io::BufRead;
857
858     let mut data = Vec::new();
859
860     let mut config = config.clone();
861     config.set().write_mode(config::WriteMode::Modified);
862     let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
863
864     let mut lines = data.lines();
865     let mut chunks = Vec::new();
866     while let Some(Ok(header)) = lines.next() {
867         // Parse the header line
868         let values: Vec<_> = header
869             .split(' ')
870             .map(|s| s.parse::<u32>().unwrap())
871             .collect();
872         assert_eq!(values.len(), 3);
873         let line_number_orig = values[0];
874         let lines_removed = values[1];
875         let num_added = values[2];
876         let mut added_lines = Vec::new();
877         for _ in 0..num_added {
878             added_lines.push(lines.next().unwrap().unwrap());
879         }
880         chunks.push(ModifiedChunk {
881             line_number_orig,
882             lines_removed,
883             lines: added_lines,
884         });
885     }
886     Ok(ModifiedLinesResult {
887         summary,
888         filemap,
889         report,
890         modified_lines: ModifiedLines { chunks },
891     })
892 }
893
894 #[derive(Debug)]
895 pub enum Input {
896     File(PathBuf),
897     Text(String),
898 }
899
900 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
901     if !config.version_meets_requirement() {
902         return Err(format_err!("Version mismatch"));
903     }
904     let out = &mut stdout();
905     match format_input(input, config, Some(out)) {
906         Ok((summary, _, report)) => {
907             if report.has_warnings() {
908                 match term::stderr() {
909                     Some(ref t)
910                         if use_colored_tty(config.color())
911                             && t.supports_color()
912                             && t.supports_attr(term::Attr::Bold) =>
913                     {
914                         match report.print_warnings_fancy(term::stderr().unwrap()) {
915                             Ok(..) => (),
916                             Err(..) => panic!("Unable to write to stderr: {}", report),
917                         }
918                     }
919                     _ => eprintln!("{}", report),
920                 }
921             }
922
923             Ok(summary)
924         }
925         Err((msg, mut summary)) => {
926             eprintln!("Error writing files: {}", msg);
927             summary.add_operational_error();
928             Ok(summary)
929         }
930     }
931 }
932
933 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
934     if config.write_mode() == WriteMode::Checkstyle {
935         let mut out = &mut stdout();
936         checkstyle::output_header(&mut out)?;
937     }
938     Ok(())
939 }
940
941 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
942     if config.write_mode() == WriteMode::Checkstyle {
943         let mut out = &mut stdout();
944         checkstyle::output_footer(&mut out)?;
945     }
946     Ok(())
947 }
948
949 #[cfg(test)]
950 mod unit_tests {
951     use super::{format_code_block, format_snippet, Config};
952
953     #[test]
954     fn test_no_panic_on_format_snippet_and_format_code_block() {
955         // `format_snippet()` and `format_code_block()` should not panic
956         // even when we cannot parse the given snippet.
957         let snippet = "let";
958         assert!(format_snippet(snippet, &Config::default()).is_none());
959         assert!(format_code_block(snippet, &Config::default()).is_none());
960     }
961
962     fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
963     where
964         F: Fn(&str, &Config) -> Option<String>,
965     {
966         let output = formatter(input, &Config::default());
967         output.is_some() && output.unwrap() == expected
968     }
969
970     #[test]
971     fn test_format_snippet() {
972         let snippet = "fn main() { println!(\"hello, world\"); }";
973         let expected = "fn main() {\n    \
974                         println!(\"hello, world\");\n\
975                         }\n";
976         assert!(test_format_inner(format_snippet, snippet, expected));
977     }
978
979     #[test]
980     fn test_format_code_block_fail() {
981         #[rustfmt_skip]
982         let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
983         assert!(format_code_block(code_block, &Config::default()).is_none());
984     }
985
986     #[test]
987     fn test_format_code_block() {
988         // simple code block
989         let code_block = "let x=3;";
990         let expected = "let x = 3;";
991         assert!(test_format_inner(format_code_block, code_block, expected));
992
993         // more complex code block, taken from chains.rs.
994         let code_block =
995 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
996 (
997 chain_indent(context, shape.add_offset(parent_rewrite.len())),
998 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
999 )
1000 } else if is_block_expr(context, &parent, &parent_rewrite) {
1001 match context.config.indent_style() {
1002 // Try to put the first child on the same line with parent's last line
1003 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1004 // The parent is a block, so align the rest of the chain with the closing
1005 // brace.
1006 IndentStyle::Visual => (parent_shape, false),
1007 }
1008 } else {
1009 (
1010 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1011 false,
1012 )
1013 };
1014 ";
1015         let expected =
1016 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1017     (
1018         chain_indent(context, shape.add_offset(parent_rewrite.len())),
1019         context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1020     )
1021 } else if is_block_expr(context, &parent, &parent_rewrite) {
1022     match context.config.indent_style() {
1023         // Try to put the first child on the same line with parent's last line
1024         IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1025         // The parent is a block, so align the rest of the chain with the closing
1026         // brace.
1027         IndentStyle::Visual => (parent_shape, false),
1028     }
1029 } else {
1030     (
1031         chain_indent(context, shape.add_offset(parent_rewrite.len())),
1032         false,
1033     )
1034 };";
1035         assert!(test_format_inner(format_code_block, code_block, expected));
1036     }
1037 }