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