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