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