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