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