]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Use correct one line width for list attribute
[rust.git] / src / lib.rs
1 // Copyright 2015-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![feature(custom_attribute)]
12 #![feature(decl_macro)]
13 // FIXME(cramertj) remove after match_default_bindings merges
14 #![allow(stable_features)]
15 #![feature(match_default_bindings)]
16 #![feature(type_ascription)]
17 #![feature(unicode_internals)]
18
19 #[macro_use]
20 extern crate derive_new;
21 extern crate diff;
22 #[macro_use]
23 extern crate failure;
24 extern crate getopts;
25 extern crate itertools;
26 #[cfg(test)]
27 #[macro_use]
28 extern crate lazy_static;
29 #[macro_use]
30 extern crate log;
31 extern crate regex;
32 extern crate rustc_target;
33 extern crate serde;
34 #[macro_use]
35 extern crate serde_derive;
36 extern crate serde_json;
37 extern crate syntax;
38 extern crate term;
39 extern crate toml;
40 extern crate unicode_segmentation;
41
42 use std::collections::HashMap;
43 use std::fmt;
44 use std::io::{self, stdout, Write};
45 use std::panic::{catch_unwind, AssertUnwindSafe};
46 use std::path::PathBuf;
47 use std::rc::Rc;
48 use std::time::Duration;
49
50 use syntax::ast;
51 pub use syntax::codemap::FileName;
52 use syntax::codemap::{CodeMap, FilePathMapping};
53 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
54 use syntax::errors::{DiagnosticBuilder, Handler};
55 use syntax::parse::{self, ParseSess};
56
57 use comment::{CharClasses, FullCodeCharKind, LineClasses};
58 use failure::Fail;
59 use issues::{BadIssueSeeker, Issue};
60 use shape::Indent;
61 use utils::use_colored_tty;
62 use visitor::{FmtVisitor, SnippetProvider};
63
64 pub use config::options::CliOptions;
65 pub use config::summary::Summary;
66 pub use config::{file_lines, load_config, Config, WriteMode};
67
68 pub type FmtResult<T> = std::result::Result<T, failure::Error>;
69
70 pub const WRITE_MODE_LIST: &str =
71     "[replace|overwrite|display|plain|diff|coverage|checkstyle|check]";
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 (maximum: {} (see `max_width` option), found: {})",
119         _0,
120         _1
121     )]
122     LineOverflow(usize, usize),
123     // Line ends in whitespace
124     #[fail(display = "left behind trailing whitespace")]
125     TrailingWhitespace,
126     // TODO or FIXME item without an issue number
127     #[fail(display = "found {}", _0)]
128     BadIssue(Issue),
129     // License check has failed
130     #[fail(display = "license check failed")]
131     LicenseCheck,
132 }
133
134 // Formatting errors that are identified *after* rustfmt has run.
135 struct FormattingError {
136     line: usize,
137     kind: ErrorKind,
138     is_comment: bool,
139     is_string: bool,
140     line_buffer: String,
141 }
142
143 impl FormattingError {
144     fn msg_prefix(&self) -> &str {
145         match self.kind {
146             ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
147             ErrorKind::LicenseCheck => "error:",
148             ErrorKind::BadIssue(_) => "warning:",
149         }
150     }
151
152     fn msg_suffix(&self) -> &str {
153         if self.is_comment || self.is_string {
154             "set `error_on_unformatted = false` to suppress \
155              the warning against comments or string literals\n"
156         } else {
157             ""
158         }
159     }
160
161     // (space, target)
162     fn format_len(&self) -> (usize, usize) {
163         match self.kind {
164             ErrorKind::LineOverflow(found, max) => (max, found - max),
165             ErrorKind::TrailingWhitespace => {
166                 let trailing_ws_start = self.line_buffer
167                     .rfind(|c: char| !c.is_whitespace())
168                     .map(|pos| pos + 1)
169                     .unwrap_or(0);
170                 (
171                     trailing_ws_start,
172                     self.line_buffer.len() - trailing_ws_start,
173                 )
174             }
175             _ => unreachable!(),
176         }
177     }
178 }
179
180 pub struct FormatReport {
181     // Maps stringified file paths to their associated formatting errors.
182     file_error_map: HashMap<FileName, Vec<FormattingError>>,
183 }
184
185 impl FormatReport {
186     fn new() -> FormatReport {
187         FormatReport {
188             file_error_map: HashMap::new(),
189         }
190     }
191
192     fn warning_count(&self) -> usize {
193         self.file_error_map
194             .iter()
195             .map(|(_, errors)| errors.len())
196             .sum()
197     }
198
199     fn has_warnings(&self) -> bool {
200         self.warning_count() > 0
201     }
202
203     fn print_warnings_fancy(
204         &self,
205         mut t: Box<term::Terminal<Output = io::Stderr>>,
206     ) -> Result<(), term::Error> {
207         for (file, errors) in &self.file_error_map {
208             for error in errors {
209                 let prefix_space_len = error.line.to_string().len();
210                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
211
212                 // First line: the overview of error
213                 t.fg(term::color::RED)?;
214                 t.attr(term::Attr::Bold)?;
215                 write!(t, "{} ", error.msg_prefix())?;
216                 t.reset()?;
217                 t.attr(term::Attr::Bold)?;
218                 writeln!(t, "{}", error.kind)?;
219
220                 // Second line: file info
221                 write!(t, "{}--> ", &prefix_spaces[1..])?;
222                 t.reset()?;
223                 writeln!(t, "{}:{}", file, error.line)?;
224
225                 // Third to fifth lines: show the line which triggered error, if available.
226                 if !error.line_buffer.is_empty() {
227                     let (space_len, target_len) = error.format_len();
228                     t.attr(term::Attr::Bold)?;
229                     write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
230                     t.reset()?;
231                     writeln!(t, "{}", error.line_buffer)?;
232                     t.attr(term::Attr::Bold)?;
233                     write!(t, "{}| ", prefix_spaces)?;
234                     t.fg(term::color::RED)?;
235                     writeln!(t, "{}", target_str(space_len, target_len))?;
236                     t.reset()?;
237                 }
238
239                 // The last line: show note if available.
240                 let msg_suffix = error.msg_suffix();
241                 if !msg_suffix.is_empty() {
242                     t.attr(term::Attr::Bold)?;
243                     write!(t, "{}= note: ", prefix_spaces)?;
244                     t.reset()?;
245                     writeln!(t, "{}", error.msg_suffix())?;
246                 } else {
247                     writeln!(t)?;
248                 }
249                 t.reset()?;
250             }
251         }
252
253         if !self.file_error_map.is_empty() {
254             t.attr(term::Attr::Bold)?;
255             write!(t, "warning: ")?;
256             t.reset()?;
257             write!(
258                 t,
259                 "rustfmt may have failed to format. See previous {} errors.\n\n",
260                 self.warning_count(),
261             )?;
262         }
263
264         Ok(())
265     }
266 }
267
268 fn target_str(space_len: usize, target_len: usize) -> String {
269     let empty_line = " ".repeat(space_len);
270     let overflowed = "^".repeat(target_len);
271     empty_line + &overflowed
272 }
273
274 impl fmt::Display for FormatReport {
275     // Prints all the formatting errors.
276     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
277         for (file, errors) in &self.file_error_map {
278             for error in errors {
279                 let prefix_space_len = error.line.to_string().len();
280                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
281
282                 let error_line_buffer = if error.line_buffer.is_empty() {
283                     String::from(" ")
284                 } else {
285                     let (space_len, target_len) = error.format_len();
286                     format!(
287                         "{}|\n{} | {}\n{}| {}",
288                         prefix_spaces,
289                         error.line,
290                         error.line_buffer,
291                         prefix_spaces,
292                         target_str(space_len, target_len)
293                     )
294                 };
295
296                 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
297                 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
298                 let msg_suffix = error.msg_suffix();
299                 let note = if msg_suffix.is_empty() {
300                     String::new()
301                 } else {
302                     format!("{}note= ", prefix_spaces)
303                 };
304
305                 writeln!(
306                     fmt,
307                     "{}\n{}\n{}\n{}{}",
308                     error_info,
309                     file_info,
310                     error_line_buffer,
311                     note,
312                     error.msg_suffix()
313                 )?;
314             }
315         }
316         if !self.file_error_map.is_empty() {
317             writeln!(
318                 fmt,
319                 "warning: rustfmt may have failed to format. See previous {} errors.",
320                 self.warning_count(),
321             )?;
322         }
323         Ok(())
324     }
325 }
326
327 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
328 where
329     F: Fn(),
330 {
331     if config.verbose() && path.to_string() != STDIN {
332         f();
333     }
334 }
335
336 // Formatting which depends on the AST.
337 fn format_ast<F>(
338     krate: &ast::Crate,
339     parse_session: &mut ParseSess,
340     main_file: &FileName,
341     config: &Config,
342     mut after_file: F,
343 ) -> Result<(FileMap, bool), io::Error>
344 where
345     F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
346 {
347     let mut result = FileMap::new();
348     // diff mode: check if any files are differing
349     let mut has_diff = false;
350
351     // We always skip children for the "Plain" write mode, since there is
352     // nothing to distinguish the nested module contents.
353     let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
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() && !is_skipped_line(cur_line, skipped_range)
493                     && should_report_error(config, kind, is_string, error_kind)
494                 {
495                     errors.push(FormattingError {
496                         line: cur_line,
497                         kind: error_kind,
498                         is_comment: kind.is_comment(),
499                         is_string,
500                         line_buffer: line_buffer.clone(),
501                     });
502                 }
503             }
504
505             line_len = 0;
506             cur_line += 1;
507             format_line = config.file_lines().contains_line(name, cur_line);
508             newline_count += 1;
509             last_wspace = None;
510             line_buffer.clear();
511             is_string = false;
512         } else {
513             newline_count = 0;
514             line_len += if c == '\t' { config.tab_spaces() } else { 1 };
515             if c.is_whitespace() {
516                 if last_wspace.is_none() {
517                     last_wspace = Some(b);
518                 }
519             } else {
520                 last_wspace = None;
521             }
522             line_buffer.push(c);
523             if kind.is_string() {
524                 is_string = true;
525             }
526         }
527     }
528
529     if newline_count > 1 {
530         debug!("track truncate: {} {}", text.len(), newline_count);
531         let line = text.len() - newline_count + 1;
532         text.truncate(line);
533     }
534
535     for &(l, kind, ref b) in &trims {
536         if !is_skipped_line(l, skipped_range) {
537             errors.push(FormattingError {
538                 line: l,
539                 kind: ErrorKind::TrailingWhitespace,
540                 is_comment: kind.is_comment(),
541                 is_string: kind.is_string(),
542                 line_buffer: b.clone(),
543             });
544         }
545     }
546
547     report.file_error_map.insert(name.clone(), errors);
548 }
549
550 fn parse_input<'sess>(
551     input: Input,
552     parse_session: &'sess ParseSess,
553     config: &Config,
554 ) -> Result<ast::Crate, ParseError<'sess>> {
555     let mut parser = match input {
556         Input::File(file) => parse::new_parser_from_file(parse_session, &file),
557         Input::Text(text) => parse::new_parser_from_source_str(
558             parse_session,
559             FileName::Custom("stdin".to_owned()),
560             text,
561         ),
562     };
563
564     parser.cfg_mods = false;
565     if config.skip_children() {
566         parser.recurse_into_file_modules = false;
567     }
568
569     let mut parser = AssertUnwindSafe(parser);
570     let result = catch_unwind(move || parser.0.parse_crate_mod());
571
572     match result {
573         Ok(Ok(c)) => {
574             if parse_session.span_diagnostic.has_errors() {
575                 // Bail out if the parser recovered from an error.
576                 Err(ParseError::Recovered)
577             } else {
578                 Ok(c)
579             }
580         }
581         Ok(Err(e)) => Err(ParseError::Error(e)),
582         Err(_) => Err(ParseError::Panic),
583     }
584 }
585
586 /// All the ways that parsing can fail.
587 enum ParseError<'sess> {
588     /// There was an error, but the parser recovered.
589     Recovered,
590     /// There was an error (supplied) and parsing failed.
591     Error(DiagnosticBuilder<'sess>),
592     /// The parser panicked.
593     Panic,
594 }
595
596 /// Format the given snippet. The snippet is expected to be *complete* code.
597 /// When we cannot parse the given snippet, this function returns `None`.
598 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
599     let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
600     let input = Input::Text(snippet.into());
601     let mut config = config.clone();
602     config.set().write_mode(config::WriteMode::Plain);
603     config.set().hide_parse_errors(true);
604     match format_input(input, &config, Some(&mut out)) {
605         // `format_input()` returns an empty string on parsing error.
606         Ok(..) if out.is_empty() && !snippet.is_empty() => None,
607         Ok(..) => String::from_utf8(out).ok(),
608         Err(..) => None,
609     }
610 }
611
612 const FN_MAIN_PREFIX: &str = "fn main() {\n";
613
614 fn enclose_in_main_block(s: &str, config: &Config) -> String {
615     let indent = Indent::from_width(config, config.tab_spaces());
616     let mut result = String::with_capacity(s.len() * 2);
617     result.push_str(FN_MAIN_PREFIX);
618     let mut need_indent = true;
619     for (kind, line) in LineClasses::new(s) {
620         if need_indent {
621             result.push_str(&indent.to_string(config));
622         }
623         result.push_str(&line);
624         result.push('\n');
625         need_indent = !kind.is_string() || line.ends_with('\\');
626     }
627     result.push('}');
628     result
629 }
630
631 /// Format the given code block. Mainly targeted for code block in comment.
632 /// The code block may be incomplete (i.e. parser may be unable to parse it).
633 /// To avoid panic in parser, we wrap the code block with a dummy function.
634 /// The returned code block does *not* end with newline.
635 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
636     // Wrap the given code block with `fn main()` if it does not have one.
637     let snippet = enclose_in_main_block(code_snippet, config);
638     let mut result = String::with_capacity(snippet.len());
639     let mut is_first = true;
640
641     // Trim "fn main() {" on the first line and "}" on the last line,
642     // then unindent the whole code block.
643     let formatted = format_snippet(&snippet, config)?;
644     // 2 = "}\n"
645     let block_len = formatted.len().checked_sub(2).unwrap_or(0);
646     let mut is_indented = true;
647     for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
648         if !is_first {
649             result.push('\n');
650         } else {
651             is_first = false;
652         }
653         let trimmed_line = if !is_indented {
654             line
655         } else if line.len() > config.max_width() {
656             // If there are lines that are larger than max width, we cannot tell
657             // whether we have succeeded but have some comments or strings that
658             // are too long, or we have failed to format code block. We will be
659             // conservative and just return `None` in this case.
660             return None;
661         } else if line.len() > config.tab_spaces() {
662             // Make sure that the line has leading whitespaces.
663             let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
664             if line.starts_with(indent_str.as_ref()) {
665                 let offset = if config.hard_tabs() {
666                     1
667                 } else {
668                     config.tab_spaces()
669                 };
670                 &line[offset..]
671             } else {
672                 line
673             }
674         } else {
675             line
676         };
677         result.push_str(trimmed_line);
678         is_indented = !kind.is_string() || line.ends_with('\\');
679     }
680     Some(result)
681 }
682
683 pub fn format_input<T: Write>(
684     input: Input,
685     config: &Config,
686     out: Option<&mut T>,
687 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
688     syntax::with_globals(|| format_input_inner(input, config, out))
689 }
690
691 fn format_input_inner<T: Write>(
692     input: Input,
693     config: &Config,
694     mut out: Option<&mut T>,
695 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
696     let mut summary = Summary::default();
697     if config.disable_all_formatting() {
698         // When the input is from stdin, echo back the input.
699         if let Input::Text(ref buf) = input {
700             if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
701                 return Err((e, summary));
702             }
703         }
704         return Ok((summary, FileMap::new(), FormatReport::new()));
705     }
706     let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
707
708     let tty_handler = if config.hide_parse_errors() {
709         let silent_emitter = Box::new(EmitterWriter::new(
710             Box::new(Vec::new()),
711             Some(codemap.clone()),
712             false,
713             false,
714         ));
715         Handler::with_emitter(true, false, silent_emitter)
716     } else {
717         let supports_color = term::stderr().map_or(false, |term| term.supports_color());
718         let color_cfg = if supports_color {
719             ColorConfig::Auto
720         } else {
721             ColorConfig::Never
722         };
723         Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
724     };
725     let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
726
727     let main_file = match input {
728         Input::File(ref file) => FileName::Real(file.clone()),
729         Input::Text(..) => FileName::Custom("stdin".to_owned()),
730     };
731
732     let krate = match parse_input(input, &parse_session, config) {
733         Ok(krate) => krate,
734         Err(err) => {
735             match err {
736                 ParseError::Error(mut diagnostic) => diagnostic.emit(),
737                 ParseError::Panic => {
738                     // Note that if you see this message and want more information,
739                     // then go to `parse_input` and run the parse function without
740                     // `catch_unwind` so rustfmt panics and you can get a backtrace.
741                     should_emit_verbose(&main_file, config, || {
742                         println!("The Rust parser panicked")
743                     });
744                 }
745                 ParseError::Recovered => {}
746             }
747             summary.add_parsing_error();
748             return Ok((summary, FileMap::new(), FormatReport::new()));
749         }
750     };
751
752     summary.mark_parse_time();
753
754     // Suppress error output after parsing.
755     let silent_emitter = Box::new(EmitterWriter::new(
756         Box::new(Vec::new()),
757         Some(codemap.clone()),
758         false,
759         false,
760     ));
761     parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
762
763     let mut report = FormatReport::new();
764
765     let format_result = format_ast(
766         &krate,
767         &mut parse_session,
768         &main_file,
769         config,
770         |file_name, file, skipped_range| {
771             // For some reason, the codemap does not include terminating
772             // newlines so we must add one on for each file. This is sad.
773             filemap::append_newline(file);
774
775             format_lines(file, file_name, skipped_range, config, &mut report);
776
777             if let Some(ref mut out) = out {
778                 return filemap::write_file(file, file_name, out, config);
779             }
780             Ok(false)
781         },
782     );
783
784     summary.mark_format_time();
785
786     should_emit_verbose(&main_file, config, || {
787         fn duration_to_f32(d: Duration) -> f32 {
788             d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
789         }
790
791         println!(
792             "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
793             duration_to_f32(summary.get_parse_time().unwrap()),
794             duration_to_f32(summary.get_format_time().unwrap()),
795         )
796     });
797
798     match format_result {
799         Ok((file_map, has_diff)) => {
800             if report.has_warnings() {
801                 summary.add_formatting_error();
802             }
803
804             if has_diff {
805                 summary.add_diff();
806             }
807
808             Ok((summary, file_map, report))
809         }
810         Err(e) => Err((e, summary)),
811     }
812 }
813
814 /// A single span of changed lines, with 0 or more removed lines
815 /// and a vector of 0 or more inserted lines.
816 #[derive(Debug, PartialEq, Eq)]
817 struct ModifiedChunk {
818     /// The first to be removed from the original text
819     pub line_number_orig: u32,
820     /// The number of lines which have been replaced
821     pub lines_removed: u32,
822     /// The new lines
823     pub lines: Vec<String>,
824 }
825
826 /// Set of changed sections of a file.
827 #[derive(Debug, PartialEq, Eq)]
828 struct ModifiedLines {
829     /// The set of changed chunks.
830     pub chunks: Vec<ModifiedChunk>,
831 }
832
833 /// The successful result of formatting via `get_modified_lines()`.
834 #[cfg(test)]
835 struct ModifiedLinesResult {
836     /// The high level summary details
837     pub summary: Summary,
838     /// The result Filemap
839     pub filemap: FileMap,
840     /// Map of formatting errors
841     pub report: FormatReport,
842     /// The sets of updated lines.
843     pub modified_lines: ModifiedLines,
844 }
845
846 /// Format a file and return a `ModifiedLines` data structure describing
847 /// the changed ranges of lines.
848 #[cfg(test)]
849 fn get_modified_lines(
850     input: Input,
851     config: &Config,
852 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
853     use std::io::BufRead;
854
855     let mut data = Vec::new();
856
857     let mut config = config.clone();
858     config.set().write_mode(config::WriteMode::Modified);
859     let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
860
861     let mut lines = data.lines();
862     let mut chunks = Vec::new();
863     while let Some(Ok(header)) = lines.next() {
864         // Parse the header line
865         let values: Vec<_> = header
866             .split(' ')
867             .map(|s| s.parse::<u32>().unwrap())
868             .collect();
869         assert_eq!(values.len(), 3);
870         let line_number_orig = values[0];
871         let lines_removed = values[1];
872         let num_added = values[2];
873         let mut added_lines = Vec::new();
874         for _ in 0..num_added {
875             added_lines.push(lines.next().unwrap().unwrap());
876         }
877         chunks.push(ModifiedChunk {
878             line_number_orig,
879             lines_removed,
880             lines: added_lines,
881         });
882     }
883     Ok(ModifiedLinesResult {
884         summary,
885         filemap,
886         report,
887         modified_lines: ModifiedLines { chunks },
888     })
889 }
890
891 #[derive(Debug)]
892 pub enum Input {
893     File(PathBuf),
894     Text(String),
895 }
896
897 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
898     if !config.version_meets_requirement() {
899         return Err(format_err!("Version mismatch"));
900     }
901     let out = &mut stdout();
902     match format_input(input, config, Some(out)) {
903         Ok((summary, _, report)) => {
904             if report.has_warnings() {
905                 match term::stderr() {
906                     Some(ref t)
907                         if use_colored_tty(config.color()) && t.supports_color()
908                             && t.supports_attr(term::Attr::Bold) =>
909                     {
910                         match report.print_warnings_fancy(term::stderr().unwrap()) {
911                             Ok(..) => (),
912                             Err(..) => panic!("Unable to write to stderr: {}", report),
913                         }
914                     }
915                     _ => eprintln!("{}", report),
916                 }
917             }
918
919             Ok(summary)
920         }
921         Err((msg, mut summary)) => {
922             eprintln!("Error writing files: {}", msg);
923             summary.add_operational_error();
924             Ok(summary)
925         }
926     }
927 }
928
929 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
930     if config.write_mode() == WriteMode::Checkstyle {
931         let mut out = &mut stdout();
932         checkstyle::output_header(&mut out)?;
933     }
934     Ok(())
935 }
936
937 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
938     if config.write_mode() == WriteMode::Checkstyle {
939         let mut out = &mut stdout();
940         checkstyle::output_footer(&mut out)?;
941     }
942     Ok(())
943 }
944
945 #[cfg(test)]
946 mod unit_tests {
947     use super::{format_code_block, format_snippet, Config};
948
949     #[test]
950     fn test_no_panic_on_format_snippet_and_format_code_block() {
951         // `format_snippet()` and `format_code_block()` should not panic
952         // even when we cannot parse the given snippet.
953         let snippet = "let";
954         assert!(format_snippet(snippet, &Config::default()).is_none());
955         assert!(format_code_block(snippet, &Config::default()).is_none());
956     }
957
958     fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
959     where
960         F: Fn(&str, &Config) -> Option<String>,
961     {
962         let output = formatter(input, &Config::default());
963         output.is_some() && output.unwrap() == expected
964     }
965
966     #[test]
967     fn test_format_snippet() {
968         let snippet = "fn main() { println!(\"hello, world\"); }";
969         let expected = "fn main() {\n    \
970                         println!(\"hello, world\");\n\
971                         }\n";
972         assert!(test_format_inner(format_snippet, snippet, expected));
973     }
974
975     #[test]
976     fn test_format_code_block_fail() {
977         #[rustfmt_skip]
978         let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
979         assert!(format_code_block(code_block, &Config::default()).is_none());
980     }
981
982     #[test]
983     fn test_format_code_block() {
984         // simple code block
985         let code_block = "let x=3;";
986         let expected = "let x = 3;";
987         assert!(test_format_inner(format_code_block, code_block, expected));
988
989         // more complex code block, taken from chains.rs.
990         let code_block =
991 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
992 (
993 chain_indent(context, shape.add_offset(parent_rewrite.len())),
994 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
995 )
996 } else if is_block_expr(context, &parent, &parent_rewrite) {
997 match context.config.indent_style() {
998 // Try to put the first child on the same line with parent's last line
999 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1000 // The parent is a block, so align the rest of the chain with the closing
1001 // brace.
1002 IndentStyle::Visual => (parent_shape, false),
1003 }
1004 } else {
1005 (
1006 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1007 false,
1008 )
1009 };
1010 ";
1011         let expected =
1012 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1013     (
1014         chain_indent(context, shape.add_offset(parent_rewrite.len())),
1015         context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1016     )
1017 } else if is_block_expr(context, &parent, &parent_rewrite) {
1018     match context.config.indent_style() {
1019         // Try to put the first child on the same line with parent's last line
1020         IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1021         // The parent is a block, so align the rest of the chain with the closing
1022         // brace.
1023         IndentStyle::Visual => (parent_shape, false),
1024     }
1025 } else {
1026     (
1027         chain_indent(context, shape.add_offset(parent_rewrite.len())),
1028         false,
1029     )
1030 };";
1031         assert!(test_format_inner(format_code_block, code_block, expected));
1032     }
1033 }