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