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