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;
22 extern crate itertools;
25 extern crate lazy_static;
29 extern crate rustc_target;
32 extern crate serde_derive;
33 extern crate serde_json;
37 extern crate unicode_segmentation;
39 use std::cell::RefCell;
40 use std::collections::HashMap;
42 use std::io::{self, stdout, Write};
43 use std::panic::{catch_unwind, AssertUnwindSafe};
44 use std::path::PathBuf;
46 use std::time::Duration;
49 pub use syntax::codemap::FileName;
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};
55 use comment::{CharClasses, FullCodeCharKind, LineClasses};
57 use issues::{BadIssueSeeker, Issue};
59 use utils::use_colored_tty;
60 use visitor::{FmtVisitor, SnippetProvider};
62 pub use config::options::CliOptions;
63 pub use config::summary::Summary;
64 pub use config::{load_config, Color, Config, FileLines, Verbosity, WriteMode};
71 pub(crate) mod checkstyle;
73 pub(crate) mod codemap;
75 pub(crate) mod config;
77 pub(crate) mod filemap;
85 pub(crate) mod modules;
90 pub(crate) mod rustfmt_diff;
98 pub(crate) mod visitor;
100 const STDIN: &str = "<stdin>";
102 // A map of the files of a crate, with their new content
103 pub(crate) type FileMap = Vec<FileRecord>;
105 pub(crate) type FileRecord = (FileName, String);
107 #[derive(Fail, Debug)]
109 // Line has exceeded character limit (found, maximum)
111 display = "line formatted, but exceeded maximum width \
112 (maximum: {} (see `max_width` option), found: {})",
116 LineOverflow(usize, usize),
117 // Line ends in whitespace
118 #[fail(display = "left behind trailing whitespace")]
120 // TODO or FIXME item without an issue number
121 #[fail(display = "found {}", _0)]
123 // License check has failed
124 #[fail(display = "license check failed")]
126 // Used deprecated skip attribute
127 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
129 // Used a rustfmt:: attribute other than skip
130 #[fail(display = "invalid attribute")]
132 #[fail(display = "io error: {}", _0)]
136 impl From<io::Error> for ErrorKind {
137 fn from(e: io::Error) -> ErrorKind {
138 ErrorKind::IoError(e)
142 struct FormattingError {
150 impl FormattingError {
151 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
153 line: codemap.lookup_char_pos(span.lo()).line,
158 .span_to_lines(*span)
162 .get_line(fl.lines[0].line_index)
163 .map(|l| l.into_owned())
165 .unwrap_or_else(|| String::new()),
168 fn msg_prefix(&self) -> &str {
170 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace | ErrorKind::IoError(_) => {
173 ErrorKind::LicenseCheck | ErrorKind::BadAttr => "error:",
174 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
178 fn msg_suffix(&self) -> &str {
179 if self.is_comment || self.is_string {
180 "set `error_on_unformatted = false` to suppress \
181 the warning against comments or string literals\n"
188 fn format_len(&self) -> (usize, usize) {
190 ErrorKind::LineOverflow(found, max) => (max, found - max),
191 ErrorKind::TrailingWhitespace | ErrorKind::DeprecatedAttr | ErrorKind::BadAttr => {
192 let trailing_ws_start = self
194 .rfind(|c: char| !c.is_whitespace())
199 self.line_buffer.len() - trailing_ws_start,
208 struct FormatReport {
209 // Maps stringified file paths to their associated formatting errors.
210 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
213 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
215 #[derive(Default, Debug)]
216 struct ReportedErrors {
217 has_operational_errors: bool,
218 has_check_errors: bool,
222 fn new() -> FormatReport {
224 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
228 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
229 self.track_errors(&v);
234 .and_modify(|fe| fe.append(&mut v))
238 fn track_errors(&self, new_errors: &[FormattingError]) {
239 let errs = &mut self.internal.borrow_mut().1;
240 if errs.has_operational_errors && errs.has_check_errors {
243 for err in new_errors {
245 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
246 errs.has_operational_errors = true;
248 ErrorKind::BadIssue(_)
249 | ErrorKind::LicenseCheck
250 | ErrorKind::DeprecatedAttr
251 | ErrorKind::BadAttr => {
252 errs.has_check_errors = true;
259 fn warning_count(&self) -> usize {
264 .map(|(_, errors)| errors.len())
268 fn has_warnings(&self) -> bool {
269 self.warning_count() > 0
272 fn print_warnings_fancy(
274 mut t: Box<term::Terminal<Output = io::Stderr>>,
275 ) -> Result<(), term::Error> {
276 for (file, errors) in &self.internal.borrow().0 {
277 for error in errors {
278 let prefix_space_len = error.line.to_string().len();
279 let prefix_spaces = " ".repeat(1 + prefix_space_len);
281 // First line: the overview of error
282 t.fg(term::color::RED)?;
283 t.attr(term::Attr::Bold)?;
284 write!(t, "{} ", error.msg_prefix())?;
286 t.attr(term::Attr::Bold)?;
287 writeln!(t, "{}", error.kind)?;
289 // Second line: file info
290 write!(t, "{}--> ", &prefix_spaces[1..])?;
292 writeln!(t, "{}:{}", file, error.line)?;
294 // Third to fifth lines: show the line which triggered error, if available.
295 if !error.line_buffer.is_empty() {
296 let (space_len, target_len) = error.format_len();
297 t.attr(term::Attr::Bold)?;
298 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
300 writeln!(t, "{}", error.line_buffer)?;
301 t.attr(term::Attr::Bold)?;
302 write!(t, "{}| ", prefix_spaces)?;
303 t.fg(term::color::RED)?;
304 writeln!(t, "{}", target_str(space_len, target_len))?;
308 // The last line: show note if available.
309 let msg_suffix = error.msg_suffix();
310 if !msg_suffix.is_empty() {
311 t.attr(term::Attr::Bold)?;
312 write!(t, "{}= note: ", prefix_spaces)?;
314 writeln!(t, "{}", error.msg_suffix())?;
322 if !self.internal.borrow().0.is_empty() {
323 t.attr(term::Attr::Bold)?;
324 write!(t, "warning: ")?;
328 "rustfmt may have failed to format. See previous {} errors.\n\n",
329 self.warning_count(),
337 fn target_str(space_len: usize, target_len: usize) -> String {
338 let empty_line = " ".repeat(space_len);
339 let overflowed = "^".repeat(target_len);
340 empty_line + &overflowed
343 impl fmt::Display for FormatReport {
344 // Prints all the formatting errors.
345 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
346 for (file, errors) in &self.internal.borrow().0 {
347 for error in errors {
348 let prefix_space_len = error.line.to_string().len();
349 let prefix_spaces = " ".repeat(1 + prefix_space_len);
351 let error_line_buffer = if error.line_buffer.is_empty() {
354 let (space_len, target_len) = error.format_len();
356 "{}|\n{} | {}\n{}| {}",
361 target_str(space_len, target_len)
365 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
366 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
367 let msg_suffix = error.msg_suffix();
368 let note = if msg_suffix.is_empty() {
371 format!("{}note= ", prefix_spaces)
385 if !self.internal.borrow().0.is_empty() {
388 "warning: rustfmt may have failed to format. See previous {} errors.",
389 self.warning_count(),
396 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
400 if config.verbose() == Verbosity::Verbose && path.to_string() != STDIN {
405 // Formatting which depends on the AST.
408 parse_session: &mut ParseSess,
409 main_file: &FileName,
411 report: FormatReport,
413 ) -> Result<(FileMap, bool), io::Error>
415 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
417 let mut result = FileMap::new();
418 // diff mode: check if any files are differing
419 let mut has_diff = false;
421 let skip_children = config.skip_children();
422 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
423 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
426 should_emit_verbose(&path, config, || println!("Formatting {}", path));
427 let filemap = parse_session
429 .lookup_char_pos(module.inner.lo())
431 let big_snippet = filemap.src.as_ref().unwrap();
432 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
434 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
435 // Format inner attributes if available.
436 if !krate.attrs.is_empty() && path == *main_file {
437 visitor.skip_empty_lines(filemap.end_pos);
438 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
439 visitor.push_rewrite(module.inner, None);
441 visitor.format_separate_mod(module, &*filemap);
444 visitor.last_pos = filemap.start_pos;
445 visitor.skip_empty_lines(filemap.end_pos);
446 visitor.format_separate_mod(module, &*filemap);
451 ::utils::count_newlines(&visitor.buffer)
454 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
455 Ok(result) => result,
457 // Create a new error with path_str to help users see which files failed
458 let err_msg = format!("{}: {}", path, e);
459 return Err(io::Error::new(e.kind(), err_msg));
463 result.push((path.clone(), visitor.buffer));
466 Ok((result, has_diff))
469 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
470 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
473 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
476 fn should_report_error(
478 char_kind: FullCodeCharKind,
480 error_kind: &ErrorKind,
482 let allow_error_report = if char_kind.is_comment() || is_string {
483 config.error_on_unformatted()
489 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
490 ErrorKind::TrailingWhitespace => allow_error_report,
495 // Formatting done on a char by char or line by line basis.
496 // FIXME(#20) other stuff for parity with make tidy
500 skipped_range: &[(usize, usize)],
502 report: &FormatReport,
504 let mut trims = vec![];
505 let mut last_wspace: Option<usize> = None;
506 let mut line_len = 0;
507 let mut cur_line = 1;
508 let mut newline_count = 0;
509 let mut errors = vec![];
510 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
511 let mut line_buffer = String::with_capacity(config.max_width() * 2);
512 let mut is_string = false; // true if the current line contains a string literal.
513 let mut format_line = config.file_lines().contains_line(name, cur_line);
514 let allow_issue_seek = !issue_seeker.is_disabled();
517 if let Some(ref license_template) = config.license_template {
518 if !license_template.is_match(text) {
519 errors.push(FormattingError {
521 kind: ErrorKind::LicenseCheck,
524 line_buffer: String::new(),
529 // Iterate over the chars in the file map.
530 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
535 if allow_issue_seek && format_line {
536 // Add warnings for bad todos/ fixmes
537 if let Some(issue) = issue_seeker.inspect(c) {
538 errors.push(FormattingError {
540 kind: ErrorKind::BadIssue(issue),
543 line_buffer: String::new(),
550 // Check for (and record) trailing whitespace.
551 if let Some(..) = last_wspace {
552 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
554 trims.push((cur_line, kind, line_buffer.clone()));
559 // Check for any line width errors we couldn't correct.
560 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
561 if line_len > config.max_width()
562 && !is_skipped_line(cur_line, skipped_range)
563 && should_report_error(config, kind, is_string, &error_kind)
565 errors.push(FormattingError {
568 is_comment: kind.is_comment(),
570 line_buffer: line_buffer.clone(),
577 format_line = config.file_lines().contains_line(name, cur_line);
584 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
585 if c.is_whitespace() {
586 if last_wspace.is_none() {
587 last_wspace = Some(b);
593 if kind.is_string() {
599 if newline_count > 1 {
600 debug!("track truncate: {} {}", text.len(), newline_count);
601 let line = text.len() - newline_count + 1;
605 for &(l, kind, ref b) in &trims {
606 if !is_skipped_line(l, skipped_range) {
607 errors.push(FormattingError {
609 kind: ErrorKind::TrailingWhitespace,
610 is_comment: kind.is_comment(),
611 is_string: kind.is_string(),
612 line_buffer: b.clone(),
617 report.append(name.clone(), errors);
620 fn parse_input<'sess>(
622 parse_session: &'sess ParseSess,
624 ) -> Result<ast::Crate, ParseError<'sess>> {
625 let mut parser = match input {
626 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
627 Input::Text(text) => parse::new_parser_from_source_str(
629 FileName::Custom("stdin".to_owned()),
634 parser.cfg_mods = false;
635 if config.skip_children() {
636 parser.recurse_into_file_modules = false;
639 let mut parser = AssertUnwindSafe(parser);
640 let result = catch_unwind(move || parser.0.parse_crate_mod());
644 if parse_session.span_diagnostic.has_errors() {
645 // Bail out if the parser recovered from an error.
646 Err(ParseError::Recovered)
651 Ok(Err(e)) => Err(ParseError::Error(e)),
652 Err(_) => Err(ParseError::Panic),
656 /// All the ways that parsing can fail.
657 enum ParseError<'sess> {
658 /// There was an error, but the parser recovered.
660 /// There was an error (supplied) and parsing failed.
661 Error(DiagnosticBuilder<'sess>),
662 /// The parser panicked.
666 /// Format the given snippet. The snippet is expected to be *complete* code.
667 /// When we cannot parse the given snippet, this function returns `None`.
668 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
669 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
670 let input = Input::Text(snippet.into());
671 let mut config = config.clone();
672 config.set().write_mode(config::WriteMode::Display);
673 config.set().verbose(Verbosity::Quiet);
674 config.set().hide_parse_errors(true);
675 match format_input(input, &config, Some(&mut out)) {
676 // `format_input()` returns an empty string on parsing error.
677 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
678 Ok(..) => String::from_utf8(out).ok(),
683 const FN_MAIN_PREFIX: &str = "fn main() {\n";
685 fn enclose_in_main_block(s: &str, config: &Config) -> String {
686 let indent = Indent::from_width(config, config.tab_spaces());
687 let mut result = String::with_capacity(s.len() * 2);
688 result.push_str(FN_MAIN_PREFIX);
689 let mut need_indent = true;
690 for (kind, line) in LineClasses::new(s) {
692 result.push_str(&indent.to_string(config));
694 result.push_str(&line);
696 need_indent = !kind.is_string() || line.ends_with('\\');
702 /// Format the given code block. Mainly targeted for code block in comment.
703 /// The code block may be incomplete (i.e. parser may be unable to parse it).
704 /// To avoid panic in parser, we wrap the code block with a dummy function.
705 /// The returned code block does *not* end with newline.
706 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
707 // Wrap the given code block with `fn main()` if it does not have one.
708 let snippet = enclose_in_main_block(code_snippet, config);
709 let mut result = String::with_capacity(snippet.len());
710 let mut is_first = true;
712 // Trim "fn main() {" on the first line and "}" on the last line,
713 // then unindent the whole code block.
714 let formatted = format_snippet(&snippet, config)?;
716 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
717 let mut is_indented = true;
718 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
724 let trimmed_line = if !is_indented {
726 } else if line.len() > config.max_width() {
727 // If there are lines that are larger than max width, we cannot tell
728 // whether we have succeeded but have some comments or strings that
729 // are too long, or we have failed to format code block. We will be
730 // conservative and just return `None` in this case.
732 } else if line.len() > config.tab_spaces() {
733 // Make sure that the line has leading whitespaces.
734 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
735 if line.starts_with(indent_str.as_ref()) {
736 let offset = if config.hard_tabs() {
748 result.push_str(trimmed_line);
749 is_indented = !kind.is_string() || line.ends_with('\\');
754 pub fn format_input<T: Write>(
758 ) -> Result<Summary, (ErrorKind, Summary)> {
759 syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| tup.0)
762 fn format_input_inner<T: Write>(
765 mut out: Option<&mut T>,
766 ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
767 let mut summary = Summary::default();
768 if config.disable_all_formatting() {
769 // When the input is from stdin, echo back the input.
770 if let Input::Text(ref buf) = input {
771 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
772 return Err((From::from(e), summary));
775 return Ok((summary, FileMap::new(), FormatReport::new()));
777 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
779 let tty_handler = if config.hide_parse_errors() {
780 let silent_emitter = Box::new(EmitterWriter::new(
781 Box::new(Vec::new()),
782 Some(codemap.clone()),
786 Handler::with_emitter(true, false, silent_emitter)
788 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
789 let color_cfg = if supports_color {
794 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
796 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
798 let main_file = match input {
799 Input::File(ref file) => FileName::Real(file.clone()),
800 Input::Text(..) => FileName::Custom("stdin".to_owned()),
803 let krate = match parse_input(input, &parse_session, config) {
807 ParseError::Error(mut diagnostic) => diagnostic.emit(),
808 ParseError::Panic => {
809 // Note that if you see this message and want more information,
810 // then go to `parse_input` and run the parse function without
811 // `catch_unwind` so rustfmt panics and you can get a backtrace.
812 should_emit_verbose(&main_file, config, || {
813 println!("The Rust parser panicked")
816 ParseError::Recovered => {}
818 summary.add_parsing_error();
819 return Ok((summary, FileMap::new(), FormatReport::new()));
823 summary.mark_parse_time();
825 // Suppress error output after parsing.
826 let silent_emitter = Box::new(EmitterWriter::new(
827 Box::new(Vec::new()),
828 Some(codemap.clone()),
832 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
834 let report = FormatReport::new();
836 let format_result = format_ast(
842 |file_name, file, skipped_range, report| {
843 // For some reason, the codemap does not include terminating
844 // newlines so we must add one on for each file. This is sad.
845 filemap::append_newline(file);
847 format_lines(file, file_name, skipped_range, config, report);
849 if let Some(ref mut out) = out {
850 return filemap::write_file(file, file_name, out, config);
856 summary.mark_format_time();
858 should_emit_verbose(&main_file, config, || {
859 fn duration_to_f32(d: Duration) -> f32 {
860 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
864 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
865 duration_to_f32(summary.get_parse_time().unwrap()),
866 duration_to_f32(summary.get_format_time().unwrap()),
871 let report_errs = &report.internal.borrow().1;
872 if report_errs.has_check_errors {
873 summary.add_check_error();
875 if report_errs.has_operational_errors {
876 summary.add_operational_error();
880 match format_result {
881 Ok((file_map, has_diff)) => {
882 if report.has_warnings() {
883 summary.add_formatting_error();
890 Ok((summary, file_map, report))
892 Err(e) => Err((From::from(e), summary)),
896 /// A single span of changed lines, with 0 or more removed lines
897 /// and a vector of 0 or more inserted lines.
898 #[derive(Debug, PartialEq, Eq)]
899 struct ModifiedChunk {
900 /// The first to be removed from the original text
901 pub line_number_orig: u32,
902 /// The number of lines which have been replaced
903 pub lines_removed: u32,
905 pub lines: Vec<String>,
908 /// Set of changed sections of a file.
909 #[derive(Debug, PartialEq, Eq)]
910 struct ModifiedLines {
911 /// The set of changed chunks.
912 pub chunks: Vec<ModifiedChunk>,
915 /// Format a file and return a `ModifiedLines` data structure describing
916 /// the changed ranges of lines.
918 fn get_modified_lines(
921 ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
922 use std::io::BufRead;
924 let mut data = Vec::new();
926 let mut config = config.clone();
927 config.set().write_mode(config::WriteMode::Modified);
928 format_input(input, &config, Some(&mut data))?;
930 let mut lines = data.lines();
931 let mut chunks = Vec::new();
932 while let Some(Ok(header)) = lines.next() {
933 // Parse the header line
934 let values: Vec<_> = header
936 .map(|s| s.parse::<u32>().unwrap())
938 assert_eq!(values.len(), 3);
939 let line_number_orig = values[0];
940 let lines_removed = values[1];
941 let num_added = values[2];
942 let mut added_lines = Vec::new();
943 for _ in 0..num_added {
944 added_lines.push(lines.next().unwrap().unwrap());
946 chunks.push(ModifiedChunk {
952 Ok(ModifiedLines { chunks })
961 pub fn format_and_emit_report(input: Input, config: &Config) -> Result<Summary, failure::Error> {
962 if !config.version_meets_requirement() {
963 return Err(format_err!("Version mismatch"));
965 let out = &mut stdout();
966 match syntax::with_globals(|| format_input_inner(input, config, Some(out))) {
967 Ok((summary, _, report)) => {
968 if report.has_warnings() {
969 match term::stderr() {
971 if use_colored_tty(config.color())
972 && t.supports_color()
973 && t.supports_attr(term::Attr::Bold) =>
975 match report.print_warnings_fancy(term::stderr().unwrap()) {
977 Err(..) => panic!("Unable to write to stderr: {}", report),
980 _ => eprintln!("{}", report),
986 Err((msg, mut summary)) => {
987 eprintln!("Error writing files: {}", msg);
988 summary.add_operational_error();
994 pub fn emit_pre_matter(config: &Config) -> Result<(), ErrorKind> {
995 if config.write_mode() == WriteMode::Checkstyle {
996 let mut out = &mut stdout();
997 checkstyle::output_header(&mut out)?;
1002 pub fn emit_post_matter(config: &Config) -> Result<(), ErrorKind> {
1003 if config.write_mode() == WriteMode::Checkstyle {
1004 let mut out = &mut stdout();
1005 checkstyle::output_footer(&mut out)?;
1012 use super::{format_code_block, format_snippet, Config};
1015 fn test_no_panic_on_format_snippet_and_format_code_block() {
1016 // `format_snippet()` and `format_code_block()` should not panic
1017 // even when we cannot parse the given snippet.
1018 let snippet = "let";
1019 assert!(format_snippet(snippet, &Config::default()).is_none());
1020 assert!(format_code_block(snippet, &Config::default()).is_none());
1023 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
1025 F: Fn(&str, &Config) -> Option<String>,
1027 let output = formatter(input, &Config::default());
1028 output.is_some() && output.unwrap() == expected
1032 fn test_format_snippet() {
1033 let snippet = "fn main() { println!(\"hello, world\"); }";
1034 let expected = "fn main() {\n \
1035 println!(\"hello, world\");\n\
1037 assert!(test_format_inner(format_snippet, snippet, expected));
1041 fn test_format_code_block_fail() {
1043 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1044 assert!(format_code_block(code_block, &Config::default()).is_none());
1048 fn test_format_code_block() {
1049 // simple code block
1050 let code_block = "let x=3;";
1051 let expected = "let x = 3;";
1052 assert!(test_format_inner(format_code_block, code_block, expected));
1054 // more complex code block, taken from chains.rs.
1056 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1058 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1059 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1061 } else if is_block_expr(context, &parent, &parent_rewrite) {
1062 match context.config.indent_style() {
1063 // Try to put the first child on the same line with parent's last line
1064 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1065 // The parent is a block, so align the rest of the chain with the closing
1067 IndentStyle::Visual => (parent_shape, false),
1071 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1077 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1079 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1080 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1082 } else if is_block_expr(context, &parent, &parent_rewrite) {
1083 match context.config.indent_style() {
1084 // Try to put the first child on the same line with parent's last line
1085 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1086 // The parent is a block, so align the rest of the chain with the closing
1088 IndentStyle::Visual => (parent_shape, false),
1092 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1096 assert!(test_format_inner(format_code_block, code_block, expected));