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