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