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