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