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