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