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