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.
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.
11 #![feature(tool_attributes)]
12 #![feature(decl_macro)]
13 #![allow(unused_attributes)]
14 #![feature(type_ascription)]
15 #![feature(unicode_internals)]
18 extern crate derive_new;
23 extern crate itertools;
26 extern crate lazy_static;
30 extern crate rustc_target;
33 extern crate serde_derive;
34 extern crate serde_json;
38 extern crate unicode_segmentation;
40 use std::cell::RefCell;
41 use std::collections::HashMap;
43 use std::io::{self, stdout, Write};
44 use std::panic::{catch_unwind, AssertUnwindSafe};
45 use std::path::PathBuf;
47 use std::time::Duration;
50 pub use syntax::codemap::FileName;
51 use syntax::codemap::{CodeMap, FilePathMapping, Span};
52 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
53 use syntax::errors::{DiagnosticBuilder, Handler};
54 use syntax::parse::{self, ParseSess};
56 use comment::{CharClasses, FullCodeCharKind, LineClasses};
58 use issues::{BadIssueSeeker, Issue};
60 use utils::use_colored_tty;
61 use visitor::{FmtVisitor, SnippetProvider};
63 pub use config::options::CliOptions;
64 pub use config::summary::Summary;
65 pub use config::{file_lines, load_config, Config, Verbosity, WriteMode};
67 pub type FmtResult<T> = std::result::Result<T, failure::Error>;
74 pub(crate) mod checkstyle;
76 pub(crate) mod codemap;
78 pub(crate) mod config;
80 pub(crate) mod filemap;
88 pub(crate) mod modules;
93 pub(crate) mod rustfmt_diff;
101 pub(crate) mod visitor;
103 const STDIN: &str = "<stdin>";
105 // A map of the files of a crate, with their new content
106 pub(crate) type FileMap = Vec<FileRecord>;
108 pub(crate) type FileRecord = (FileName, String);
110 #[derive(Fail, Debug, Clone, Copy)]
112 // Line has exceeded character limit (found, maximum)
114 display = "line formatted, but exceeded maximum width \
115 (maximum: {} (see `max_width` option), found: {})",
119 LineOverflow(usize, usize),
120 // Line ends in whitespace
121 #[fail(display = "left behind trailing whitespace")]
123 // TODO or FIXME item without an issue number
124 #[fail(display = "found {}", _0)]
126 // License check has failed
127 #[fail(display = "license check failed")]
129 // Used deprecated skip attribute
130 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
132 // Used a rustfmt:: attribute other than skip
133 #[fail(display = "invalid attribute")]
137 struct FormattingError {
145 impl FormattingError {
146 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
148 line: codemap.lookup_char_pos(span.lo()).line,
153 .span_to_lines(*span)
157 .get_line(fl.lines[0].line_index)
158 .map(|l| l.into_owned())
160 .unwrap_or_else(|| String::new()),
163 fn msg_prefix(&self) -> &str {
165 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
166 ErrorKind::LicenseCheck | ErrorKind::BadAttr => "error:",
167 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
171 fn msg_suffix(&self) -> &str {
172 if self.is_comment || self.is_string {
173 "set `error_on_unformatted = false` to suppress \
174 the warning against comments or string literals\n"
181 fn format_len(&self) -> (usize, usize) {
183 ErrorKind::LineOverflow(found, max) => (max, found - max),
184 ErrorKind::TrailingWhitespace | ErrorKind::DeprecatedAttr | ErrorKind::BadAttr => {
185 let trailing_ws_start = self
187 .rfind(|c: char| !c.is_whitespace())
192 self.line_buffer.len() - trailing_ws_start,
201 pub struct FormatReport {
202 // Maps stringified file paths to their associated formatting errors.
203 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
206 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
208 #[derive(Default, Debug)]
209 struct ReportedErrors {
210 has_operational_errors: bool,
211 has_check_errors: bool,
215 fn new() -> FormatReport {
217 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
221 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
222 self.track_errors(&v);
227 .and_modify(|fe| fe.append(&mut v))
231 fn track_errors(&self, new_errors: &[FormattingError]) {
232 let errs = &mut self.internal.borrow_mut().1;
233 if errs.has_operational_errors && errs.has_check_errors {
236 for err in new_errors {
238 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
239 errs.has_operational_errors = true;
241 ErrorKind::BadIssue(_)
242 | ErrorKind::LicenseCheck
243 | ErrorKind::DeprecatedAttr
244 | ErrorKind::BadAttr => {
245 errs.has_check_errors = true;
251 fn warning_count(&self) -> usize {
256 .map(|(_, errors)| errors.len())
260 fn has_warnings(&self) -> bool {
261 self.warning_count() > 0
264 fn print_warnings_fancy(
266 mut t: Box<term::Terminal<Output = io::Stderr>>,
267 ) -> Result<(), term::Error> {
268 for (file, errors) in &self.internal.borrow().0 {
269 for error in errors {
270 let prefix_space_len = error.line.to_string().len();
271 let prefix_spaces = " ".repeat(1 + prefix_space_len);
273 // First line: the overview of error
274 t.fg(term::color::RED)?;
275 t.attr(term::Attr::Bold)?;
276 write!(t, "{} ", error.msg_prefix())?;
278 t.attr(term::Attr::Bold)?;
279 writeln!(t, "{}", error.kind)?;
281 // Second line: file info
282 write!(t, "{}--> ", &prefix_spaces[1..])?;
284 writeln!(t, "{}:{}", file, error.line)?;
286 // Third to fifth lines: show the line which triggered error, if available.
287 if !error.line_buffer.is_empty() {
288 let (space_len, target_len) = error.format_len();
289 t.attr(term::Attr::Bold)?;
290 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
292 writeln!(t, "{}", error.line_buffer)?;
293 t.attr(term::Attr::Bold)?;
294 write!(t, "{}| ", prefix_spaces)?;
295 t.fg(term::color::RED)?;
296 writeln!(t, "{}", target_str(space_len, target_len))?;
300 // The last line: show note if available.
301 let msg_suffix = error.msg_suffix();
302 if !msg_suffix.is_empty() {
303 t.attr(term::Attr::Bold)?;
304 write!(t, "{}= note: ", prefix_spaces)?;
306 writeln!(t, "{}", error.msg_suffix())?;
314 if !self.internal.borrow().0.is_empty() {
315 t.attr(term::Attr::Bold)?;
316 write!(t, "warning: ")?;
320 "rustfmt may have failed to format. See previous {} errors.\n\n",
321 self.warning_count(),
329 fn target_str(space_len: usize, target_len: usize) -> String {
330 let empty_line = " ".repeat(space_len);
331 let overflowed = "^".repeat(target_len);
332 empty_line + &overflowed
335 impl fmt::Display for FormatReport {
336 // Prints all the formatting errors.
337 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
338 for (file, errors) in &self.internal.borrow().0 {
339 for error in errors {
340 let prefix_space_len = error.line.to_string().len();
341 let prefix_spaces = " ".repeat(1 + prefix_space_len);
343 let error_line_buffer = if error.line_buffer.is_empty() {
346 let (space_len, target_len) = error.format_len();
348 "{}|\n{} | {}\n{}| {}",
353 target_str(space_len, target_len)
357 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
358 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
359 let msg_suffix = error.msg_suffix();
360 let note = if msg_suffix.is_empty() {
363 format!("{}note= ", prefix_spaces)
377 if !self.internal.borrow().0.is_empty() {
380 "warning: rustfmt may have failed to format. See previous {} errors.",
381 self.warning_count(),
388 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
392 if config.verbose() == Verbosity::Verbose && path.to_string() != STDIN {
397 // Formatting which depends on the AST.
400 parse_session: &mut ParseSess,
401 main_file: &FileName,
403 report: FormatReport,
405 ) -> Result<(FileMap, bool), io::Error>
407 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
409 let mut result = FileMap::new();
410 // diff mode: check if any files are differing
411 let mut has_diff = false;
413 let skip_children = config.skip_children();
414 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
415 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
418 should_emit_verbose(&path, config, || println!("Formatting {}", path));
419 let filemap = parse_session
421 .lookup_char_pos(module.inner.lo())
423 let big_snippet = filemap.src.as_ref().unwrap();
424 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
426 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
427 // Format inner attributes if available.
428 if !krate.attrs.is_empty() && path == *main_file {
429 visitor.skip_empty_lines(filemap.end_pos);
430 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
431 visitor.push_rewrite(module.inner, None);
433 visitor.format_separate_mod(module, &*filemap);
436 visitor.last_pos = filemap.start_pos;
437 visitor.skip_empty_lines(filemap.end_pos);
438 visitor.format_separate_mod(module, &*filemap);
443 ::utils::count_newlines(&visitor.buffer)
446 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
447 Ok(result) => result,
449 // Create a new error with path_str to help users see which files failed
450 let err_msg = format!("{}: {}", path, e);
451 return Err(io::Error::new(e.kind(), err_msg));
455 result.push((path.clone(), visitor.buffer));
458 Ok((result, has_diff))
461 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
462 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
465 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
468 fn should_report_error(
470 char_kind: FullCodeCharKind,
472 error_kind: ErrorKind,
474 let allow_error_report = if char_kind.is_comment() || is_string {
475 config.error_on_unformatted()
481 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
482 ErrorKind::TrailingWhitespace => allow_error_report,
487 // Formatting done on a char by char or line by line basis.
488 // FIXME(#20) other stuff for parity with make tidy
492 skipped_range: &[(usize, usize)],
494 report: &FormatReport,
496 let mut trims = vec![];
497 let mut last_wspace: Option<usize> = None;
498 let mut line_len = 0;
499 let mut cur_line = 1;
500 let mut newline_count = 0;
501 let mut errors = vec![];
502 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
503 let mut line_buffer = String::with_capacity(config.max_width() * 2);
504 let mut is_string = false; // true if the current line contains a string literal.
505 let mut format_line = config.file_lines().contains_line(name, cur_line);
506 let allow_issue_seek = !issue_seeker.is_disabled();
509 if let Some(ref license_template) = config.license_template {
510 if !license_template.is_match(text) {
511 errors.push(FormattingError {
513 kind: ErrorKind::LicenseCheck,
516 line_buffer: String::new(),
521 // Iterate over the chars in the file map.
522 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
527 if allow_issue_seek && format_line {
528 // Add warnings for bad todos/ fixmes
529 if let Some(issue) = issue_seeker.inspect(c) {
530 errors.push(FormattingError {
532 kind: ErrorKind::BadIssue(issue),
535 line_buffer: String::new(),
542 // Check for (and record) trailing whitespace.
543 if let Some(..) = last_wspace {
544 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
545 trims.push((cur_line, kind, line_buffer.clone()));
550 // Check for any line width errors we couldn't correct.
551 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
552 if line_len > config.max_width()
553 && !is_skipped_line(cur_line, skipped_range)
554 && should_report_error(config, kind, is_string, error_kind)
556 errors.push(FormattingError {
559 is_comment: kind.is_comment(),
561 line_buffer: line_buffer.clone(),
568 format_line = config.file_lines().contains_line(name, cur_line);
575 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
576 if c.is_whitespace() {
577 if last_wspace.is_none() {
578 last_wspace = Some(b);
584 if kind.is_string() {
590 if newline_count > 1 {
591 debug!("track truncate: {} {}", text.len(), newline_count);
592 let line = text.len() - newline_count + 1;
596 for &(l, kind, ref b) in &trims {
597 if !is_skipped_line(l, skipped_range) {
598 errors.push(FormattingError {
600 kind: ErrorKind::TrailingWhitespace,
601 is_comment: kind.is_comment(),
602 is_string: kind.is_string(),
603 line_buffer: b.clone(),
608 report.append(name.clone(), errors);
611 fn parse_input<'sess>(
613 parse_session: &'sess ParseSess,
615 ) -> Result<ast::Crate, ParseError<'sess>> {
616 let mut parser = match input {
617 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
618 Input::Text(text) => parse::new_parser_from_source_str(
620 FileName::Custom("stdin".to_owned()),
625 parser.cfg_mods = false;
626 if config.skip_children() {
627 parser.recurse_into_file_modules = false;
630 let mut parser = AssertUnwindSafe(parser);
631 let result = catch_unwind(move || parser.0.parse_crate_mod());
635 if parse_session.span_diagnostic.has_errors() {
636 // Bail out if the parser recovered from an error.
637 Err(ParseError::Recovered)
642 Ok(Err(e)) => Err(ParseError::Error(e)),
643 Err(_) => Err(ParseError::Panic),
647 /// All the ways that parsing can fail.
648 enum ParseError<'sess> {
649 /// There was an error, but the parser recovered.
651 /// There was an error (supplied) and parsing failed.
652 Error(DiagnosticBuilder<'sess>),
653 /// The parser panicked.
657 /// Format the given snippet. The snippet is expected to be *complete* code.
658 /// When we cannot parse the given snippet, this function returns `None`.
659 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
660 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
661 let input = Input::Text(snippet.into());
662 let mut config = config.clone();
663 config.set().write_mode(config::WriteMode::Display);
664 config.set().verbose(Verbosity::Quiet);
665 config.set().hide_parse_errors(true);
666 match format_input(input, &config, Some(&mut out)) {
667 // `format_input()` returns an empty string on parsing error.
668 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
669 Ok(..) => String::from_utf8(out).ok(),
674 const FN_MAIN_PREFIX: &str = "fn main() {\n";
676 fn enclose_in_main_block(s: &str, config: &Config) -> String {
677 let indent = Indent::from_width(config, config.tab_spaces());
678 let mut result = String::with_capacity(s.len() * 2);
679 result.push_str(FN_MAIN_PREFIX);
680 let mut need_indent = true;
681 for (kind, line) in LineClasses::new(s) {
683 result.push_str(&indent.to_string(config));
685 result.push_str(&line);
687 need_indent = !kind.is_string() || line.ends_with('\\');
693 /// Format the given code block. Mainly targeted for code block in comment.
694 /// The code block may be incomplete (i.e. parser may be unable to parse it).
695 /// To avoid panic in parser, we wrap the code block with a dummy function.
696 /// The returned code block does *not* end with newline.
697 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
698 // Wrap the given code block with `fn main()` if it does not have one.
699 let snippet = enclose_in_main_block(code_snippet, config);
700 let mut result = String::with_capacity(snippet.len());
701 let mut is_first = true;
703 // Trim "fn main() {" on the first line and "}" on the last line,
704 // then unindent the whole code block.
705 let formatted = format_snippet(&snippet, config)?;
707 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
708 let mut is_indented = true;
709 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
715 let trimmed_line = if !is_indented {
717 } else if line.len() > config.max_width() {
718 // If there are lines that are larger than max width, we cannot tell
719 // whether we have succeeded but have some comments or strings that
720 // are too long, or we have failed to format code block. We will be
721 // conservative and just return `None` in this case.
723 } else if line.len() > config.tab_spaces() {
724 // Make sure that the line has leading whitespaces.
725 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
726 if line.starts_with(indent_str.as_ref()) {
727 let offset = if config.hard_tabs() {
739 result.push_str(trimmed_line);
740 is_indented = !kind.is_string() || line.ends_with('\\');
745 pub fn format_input<T: Write>(
749 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
750 syntax::with_globals(|| format_input_inner(input, config, out))
753 fn format_input_inner<T: Write>(
756 mut out: Option<&mut T>,
757 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
758 let mut summary = Summary::default();
759 if config.disable_all_formatting() {
760 // When the input is from stdin, echo back the input.
761 if let Input::Text(ref buf) = input {
762 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
763 return Err((e, summary));
766 return Ok((summary, FileMap::new(), FormatReport::new()));
768 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
770 let tty_handler = if config.hide_parse_errors() {
771 let silent_emitter = Box::new(EmitterWriter::new(
772 Box::new(Vec::new()),
773 Some(codemap.clone()),
777 Handler::with_emitter(true, false, silent_emitter)
779 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
780 let color_cfg = if supports_color {
785 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
787 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
789 let main_file = match input {
790 Input::File(ref file) => FileName::Real(file.clone()),
791 Input::Text(..) => FileName::Custom("stdin".to_owned()),
794 let krate = match parse_input(input, &parse_session, config) {
798 ParseError::Error(mut diagnostic) => diagnostic.emit(),
799 ParseError::Panic => {
800 // Note that if you see this message and want more information,
801 // then go to `parse_input` and run the parse function without
802 // `catch_unwind` so rustfmt panics and you can get a backtrace.
803 should_emit_verbose(&main_file, config, || {
804 println!("The Rust parser panicked")
807 ParseError::Recovered => {}
809 summary.add_parsing_error();
810 return Ok((summary, FileMap::new(), FormatReport::new()));
814 summary.mark_parse_time();
816 // Suppress error output after parsing.
817 let silent_emitter = Box::new(EmitterWriter::new(
818 Box::new(Vec::new()),
819 Some(codemap.clone()),
823 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
825 let report = FormatReport::new();
827 let format_result = format_ast(
833 |file_name, file, skipped_range, report| {
834 // For some reason, the codemap does not include terminating
835 // newlines so we must add one on for each file. This is sad.
836 filemap::append_newline(file);
838 format_lines(file, file_name, skipped_range, config, report);
840 if let Some(ref mut out) = out {
841 return filemap::write_file(file, file_name, out, config);
847 summary.mark_format_time();
849 should_emit_verbose(&main_file, config, || {
850 fn duration_to_f32(d: Duration) -> f32 {
851 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
855 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
856 duration_to_f32(summary.get_parse_time().unwrap()),
857 duration_to_f32(summary.get_format_time().unwrap()),
862 let report_errs = &report.internal.borrow().1;
863 if report_errs.has_check_errors {
864 summary.add_check_error();
866 if report_errs.has_operational_errors {
867 summary.add_operational_error();
871 match format_result {
872 Ok((file_map, has_diff)) => {
873 if report.has_warnings() {
874 summary.add_formatting_error();
881 Ok((summary, file_map, report))
883 Err(e) => Err((e, summary)),
887 /// A single span of changed lines, with 0 or more removed lines
888 /// and a vector of 0 or more inserted lines.
889 #[derive(Debug, PartialEq, Eq)]
890 struct ModifiedChunk {
891 /// The first to be removed from the original text
892 pub line_number_orig: u32,
893 /// The number of lines which have been replaced
894 pub lines_removed: u32,
896 pub lines: Vec<String>,
899 /// Set of changed sections of a file.
900 #[derive(Debug, PartialEq, Eq)]
901 struct ModifiedLines {
902 /// The set of changed chunks.
903 pub chunks: Vec<ModifiedChunk>,
906 /// The successful result of formatting via `get_modified_lines()`.
908 struct ModifiedLinesResult {
909 /// The high level summary details
910 pub summary: Summary,
911 /// The result Filemap
912 pub filemap: FileMap,
913 /// Map of formatting errors
914 pub report: FormatReport,
915 /// The sets of updated lines.
916 pub modified_lines: ModifiedLines,
919 /// Format a file and return a `ModifiedLines` data structure describing
920 /// the changed ranges of lines.
922 fn get_modified_lines(
925 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
926 use std::io::BufRead;
928 let mut data = Vec::new();
930 let mut config = config.clone();
931 config.set().write_mode(config::WriteMode::Modified);
932 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
934 let mut lines = data.lines();
935 let mut chunks = Vec::new();
936 while let Some(Ok(header)) = lines.next() {
937 // Parse the header line
938 let values: Vec<_> = header
940 .map(|s| s.parse::<u32>().unwrap())
942 assert_eq!(values.len(), 3);
943 let line_number_orig = values[0];
944 let lines_removed = values[1];
945 let num_added = values[2];
946 let mut added_lines = Vec::new();
947 for _ in 0..num_added {
948 added_lines.push(lines.next().unwrap().unwrap());
950 chunks.push(ModifiedChunk {
956 Ok(ModifiedLinesResult {
960 modified_lines: ModifiedLines { chunks },
970 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
971 if !config.version_meets_requirement() {
972 return Err(format_err!("Version mismatch"));
974 let out = &mut stdout();
975 match format_input(input, config, Some(out)) {
976 Ok((summary, _, report)) => {
977 if report.has_warnings() {
978 match term::stderr() {
980 if use_colored_tty(config.color())
981 && t.supports_color()
982 && t.supports_attr(term::Attr::Bold) =>
984 match report.print_warnings_fancy(term::stderr().unwrap()) {
986 Err(..) => panic!("Unable to write to stderr: {}", report),
989 _ => eprintln!("{}", report),
995 Err((msg, mut summary)) => {
996 eprintln!("Error writing files: {}", msg);
997 summary.add_operational_error();
1003 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
1004 if config.write_mode() == WriteMode::Checkstyle {
1005 let mut out = &mut stdout();
1006 checkstyle::output_header(&mut out)?;
1011 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
1012 if config.write_mode() == WriteMode::Checkstyle {
1013 let mut out = &mut stdout();
1014 checkstyle::output_footer(&mut out)?;
1021 use super::{format_code_block, format_snippet, Config};
1024 fn test_no_panic_on_format_snippet_and_format_code_block() {
1025 // `format_snippet()` and `format_code_block()` should not panic
1026 // even when we cannot parse the given snippet.
1027 let snippet = "let";
1028 assert!(format_snippet(snippet, &Config::default()).is_none());
1029 assert!(format_code_block(snippet, &Config::default()).is_none());
1032 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
1034 F: Fn(&str, &Config) -> Option<String>,
1036 let output = formatter(input, &Config::default());
1037 output.is_some() && output.unwrap() == expected
1041 fn test_format_snippet() {
1042 let snippet = "fn main() { println!(\"hello, world\"); }";
1043 let expected = "fn main() {\n \
1044 println!(\"hello, world\");\n\
1046 assert!(test_format_inner(format_snippet, snippet, expected));
1050 fn test_format_code_block_fail() {
1052 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1053 assert!(format_code_block(code_block, &Config::default()).is_none());
1057 fn test_format_code_block() {
1058 // simple code block
1059 let code_block = "let x=3;";
1060 let expected = "let x = 3;";
1061 assert!(test_format_inner(format_code_block, code_block, expected));
1063 // more complex code block, taken from chains.rs.
1065 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1067 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1068 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1070 } else if is_block_expr(context, &parent, &parent_rewrite) {
1071 match context.config.indent_style() {
1072 // Try to put the first child on the same line with parent's last line
1073 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1074 // The parent is a block, so align the rest of the chain with the closing
1076 IndentStyle::Visual => (parent_shape, false),
1080 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1086 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1088 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1089 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1091 } else if is_block_expr(context, &parent, &parent_rewrite) {
1092 match context.config.indent_style() {
1093 // Try to put the first child on the same line with parent's last line
1094 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1095 // The parent is a block, so align the rest of the chain with the closing
1097 IndentStyle::Visual => (parent_shape, false),
1101 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1105 assert!(test_format_inner(format_code_block, code_block, expected));