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