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