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