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