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