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 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};
54 use comment::{CharClasses, FullCodeCharKind, LineClasses};
56 use issues::{BadIssueSeeker, Issue};
58 use utils::use_colored_tty;
59 use visitor::{FmtVisitor, SnippetProvider};
61 pub use config::summary::Summary;
63 load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, Verbosity,
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 // A map of the files of a crate, with their new content
101 pub(crate) type FileMap = Vec<FileRecord>;
103 pub(crate) type FileRecord = (FileName, String);
105 #[derive(Fail, Debug)]
107 // Line has exceeded character limit (found, maximum)
109 display = "line formatted, but exceeded maximum width \
110 (maximum: {} (see `max_width` option), found: {})",
114 LineOverflow(usize, usize),
115 // Line ends in whitespace
116 #[fail(display = "left behind trailing whitespace")]
118 // TODO or FIXME item without an issue number
119 #[fail(display = "found {}", _0)]
121 // License check has failed
122 #[fail(display = "license check failed")]
124 // Used deprecated skip attribute
125 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
127 // Used a rustfmt:: attribute other than skip
128 #[fail(display = "invalid attribute")]
130 #[fail(display = "io error: {}", _0)]
134 impl From<io::Error> for ErrorKind {
135 fn from(e: io::Error) -> ErrorKind {
136 ErrorKind::IoError(e)
140 struct FormattingError {
148 impl FormattingError {
149 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
151 line: codemap.lookup_char_pos(span.lo()).line,
156 .span_to_lines(*span)
160 .get_line(fl.lines[0].line_index)
161 .map(|l| l.into_owned())
163 .unwrap_or_else(|| String::new()),
166 fn msg_prefix(&self) -> &str {
168 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace | ErrorKind::IoError(_) => {
171 ErrorKind::LicenseCheck | ErrorKind::BadAttr => "error:",
172 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
176 fn msg_suffix(&self) -> &str {
177 if self.is_comment || self.is_string {
178 "set `error_on_unformatted = false` to suppress \
179 the warning against comments or string literals\n"
186 fn format_len(&self) -> (usize, usize) {
188 ErrorKind::LineOverflow(found, max) => (max, found - max),
189 ErrorKind::TrailingWhitespace | ErrorKind::DeprecatedAttr | ErrorKind::BadAttr => {
190 let trailing_ws_start = self
192 .rfind(|c: char| !c.is_whitespace())
197 self.line_buffer.len() - trailing_ws_start,
206 struct FormatReport {
207 // Maps stringified file paths to their associated formatting errors.
208 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
211 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
213 #[derive(Default, Debug)]
214 struct ReportedErrors {
215 has_operational_errors: bool,
216 has_check_errors: bool,
220 fn new() -> FormatReport {
222 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
226 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
227 self.track_errors(&v);
232 .and_modify(|fe| fe.append(&mut v))
236 fn track_errors(&self, new_errors: &[FormattingError]) {
237 let errs = &mut self.internal.borrow_mut().1;
238 if errs.has_operational_errors && errs.has_check_errors {
241 for err in new_errors {
243 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
244 errs.has_operational_errors = true;
246 ErrorKind::BadIssue(_)
247 | ErrorKind::LicenseCheck
248 | ErrorKind::DeprecatedAttr
249 | ErrorKind::BadAttr => {
250 errs.has_check_errors = true;
257 fn warning_count(&self) -> usize {
262 .map(|(_, errors)| errors.len())
266 fn has_warnings(&self) -> bool {
267 self.warning_count() > 0
270 fn print_warnings_fancy(
272 mut t: Box<term::Terminal<Output = io::Stderr>>,
273 ) -> Result<(), term::Error> {
274 for (file, errors) in &self.internal.borrow().0 {
275 for error in errors {
276 let prefix_space_len = error.line.to_string().len();
277 let prefix_spaces = " ".repeat(1 + prefix_space_len);
279 // First line: the overview of error
280 t.fg(term::color::RED)?;
281 t.attr(term::Attr::Bold)?;
282 write!(t, "{} ", error.msg_prefix())?;
284 t.attr(term::Attr::Bold)?;
285 writeln!(t, "{}", error.kind)?;
287 // Second line: file info
288 write!(t, "{}--> ", &prefix_spaces[1..])?;
290 writeln!(t, "{}:{}", file, error.line)?;
292 // Third to fifth lines: show the line which triggered error, if available.
293 if !error.line_buffer.is_empty() {
294 let (space_len, target_len) = error.format_len();
295 t.attr(term::Attr::Bold)?;
296 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
298 writeln!(t, "{}", error.line_buffer)?;
299 t.attr(term::Attr::Bold)?;
300 write!(t, "{}| ", prefix_spaces)?;
301 t.fg(term::color::RED)?;
302 writeln!(t, "{}", target_str(space_len, target_len))?;
306 // The last line: show note if available.
307 let msg_suffix = error.msg_suffix();
308 if !msg_suffix.is_empty() {
309 t.attr(term::Attr::Bold)?;
310 write!(t, "{}= note: ", prefix_spaces)?;
312 writeln!(t, "{}", error.msg_suffix())?;
320 if !self.internal.borrow().0.is_empty() {
321 t.attr(term::Attr::Bold)?;
322 write!(t, "warning: ")?;
326 "rustfmt may have failed to format. See previous {} errors.\n\n",
327 self.warning_count(),
335 fn target_str(space_len: usize, target_len: usize) -> String {
336 let empty_line = " ".repeat(space_len);
337 let overflowed = "^".repeat(target_len);
338 empty_line + &overflowed
341 impl fmt::Display for FormatReport {
342 // Prints all the formatting errors.
343 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
344 for (file, errors) in &self.internal.borrow().0 {
345 for error in errors {
346 let prefix_space_len = error.line.to_string().len();
347 let prefix_spaces = " ".repeat(1 + prefix_space_len);
349 let error_line_buffer = if error.line_buffer.is_empty() {
352 let (space_len, target_len) = error.format_len();
354 "{}|\n{} | {}\n{}| {}",
359 target_str(space_len, target_len)
363 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
364 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
365 let msg_suffix = error.msg_suffix();
366 let note = if msg_suffix.is_empty() {
369 format!("{}note= ", prefix_spaces)
383 if !self.internal.borrow().0.is_empty() {
386 "warning: rustfmt may have failed to format. See previous {} errors.",
387 self.warning_count(),
394 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
398 if config.verbose() == Verbosity::Verbose && path != &FileName::Stdin {
403 // Formatting which depends on the AST.
406 parse_session: &mut ParseSess,
407 main_file: &FileName,
409 report: FormatReport,
411 ) -> Result<(FileMap, bool), io::Error>
413 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
415 let mut result = FileMap::new();
416 // diff mode: check if any files are differing
417 let mut has_diff = false;
419 let skip_children = config.skip_children();
420 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
421 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
424 should_emit_verbose(&path, config, || println!("Formatting {}", path));
425 let filemap = parse_session
427 .lookup_char_pos(module.inner.lo())
429 let big_snippet = filemap.src.as_ref().unwrap();
430 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
432 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
433 // Format inner attributes if available.
434 if !krate.attrs.is_empty() && path == *main_file {
435 visitor.skip_empty_lines(filemap.end_pos);
436 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
437 visitor.push_rewrite(module.inner, None);
439 visitor.format_separate_mod(module, &*filemap);
442 visitor.last_pos = filemap.start_pos;
443 visitor.skip_empty_lines(filemap.end_pos);
444 visitor.format_separate_mod(module, &*filemap);
449 ::utils::count_newlines(&visitor.buffer)
452 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
453 Ok(result) => result,
455 // Create a new error with path_str to help users see which files failed
456 let err_msg = format!("{}: {}", path, e);
457 return Err(io::Error::new(e.kind(), err_msg));
461 result.push((path.clone(), visitor.buffer));
464 Ok((result, has_diff))
467 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
468 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
471 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
474 fn should_report_error(
476 char_kind: FullCodeCharKind,
478 error_kind: &ErrorKind,
480 let allow_error_report = if char_kind.is_comment() || is_string {
481 config.error_on_unformatted()
487 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
488 ErrorKind::TrailingWhitespace => allow_error_report,
493 // Formatting done on a char by char or line by line basis.
494 // FIXME(#20) other stuff for parity with make tidy
498 skipped_range: &[(usize, usize)],
500 report: &FormatReport,
502 let mut trims = vec![];
503 let mut last_wspace: Option<usize> = None;
504 let mut line_len = 0;
505 let mut cur_line = 1;
506 let mut newline_count = 0;
507 let mut errors = vec![];
508 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
509 let mut line_buffer = String::with_capacity(config.max_width() * 2);
510 let mut is_string = false; // true if the current line contains a string literal.
511 let mut format_line = config.file_lines().contains_line(name, cur_line);
512 let allow_issue_seek = !issue_seeker.is_disabled();
515 if let Some(ref license_template) = config.license_template {
516 if !license_template.is_match(text) {
517 errors.push(FormattingError {
519 kind: ErrorKind::LicenseCheck,
522 line_buffer: String::new(),
527 // Iterate over the chars in the file map.
528 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
533 if allow_issue_seek && format_line {
534 // Add warnings for bad todos/ fixmes
535 if let Some(issue) = issue_seeker.inspect(c) {
536 errors.push(FormattingError {
538 kind: ErrorKind::BadIssue(issue),
541 line_buffer: String::new(),
548 // Check for (and record) trailing whitespace.
549 if let Some(..) = last_wspace {
550 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
552 trims.push((cur_line, kind, line_buffer.clone()));
557 // Check for any line width errors we couldn't correct.
558 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
559 if line_len > config.max_width()
560 && !is_skipped_line(cur_line, skipped_range)
561 && should_report_error(config, kind, is_string, &error_kind)
563 errors.push(FormattingError {
566 is_comment: kind.is_comment(),
568 line_buffer: line_buffer.clone(),
575 format_line = config.file_lines().contains_line(name, cur_line);
582 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
583 if c.is_whitespace() {
584 if last_wspace.is_none() {
585 last_wspace = Some(b);
591 if kind.is_string() {
597 if newline_count > 1 {
598 debug!("track truncate: {} {}", text.len(), newline_count);
599 let line = text.len() - newline_count + 1;
603 for &(l, kind, ref b) in &trims {
604 if !is_skipped_line(l, skipped_range) {
605 errors.push(FormattingError {
607 kind: ErrorKind::TrailingWhitespace,
608 is_comment: kind.is_comment(),
609 is_string: kind.is_string(),
610 line_buffer: b.clone(),
615 report.append(name.clone(), errors);
618 fn parse_input<'sess>(
620 parse_session: &'sess ParseSess,
622 ) -> Result<ast::Crate, ParseError<'sess>> {
623 let mut parser = match input {
624 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
625 Input::Text(text) => parse::new_parser_from_source_str(
627 syntax::codemap::FileName::Custom("stdin".to_owned()),
632 parser.cfg_mods = false;
633 if config.skip_children() {
634 parser.recurse_into_file_modules = false;
637 let mut parser = AssertUnwindSafe(parser);
638 let result = catch_unwind(move || parser.0.parse_crate_mod());
642 if parse_session.span_diagnostic.has_errors() {
643 // Bail out if the parser recovered from an error.
644 Err(ParseError::Recovered)
649 Ok(Err(e)) => Err(ParseError::Error(e)),
650 Err(_) => Err(ParseError::Panic),
654 /// All the ways that parsing can fail.
655 enum ParseError<'sess> {
656 /// There was an error, but the parser recovered.
658 /// There was an error (supplied) and parsing failed.
659 Error(DiagnosticBuilder<'sess>),
660 /// The parser panicked.
664 /// Format the given snippet. The snippet is expected to be *complete* code.
665 /// When we cannot parse the given snippet, this function returns `None`.
666 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
667 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
668 let input = Input::Text(snippet.into());
669 let mut config = config.clone();
670 config.set().emit_mode(config::EmitMode::Stdout);
671 config.set().verbose(Verbosity::Quiet);
672 config.set().hide_parse_errors(true);
673 match format_input(input, &config, Some(&mut out)) {
674 // `format_input()` returns an empty string on parsing error.
675 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
676 Ok(..) => String::from_utf8(out).ok(),
681 const FN_MAIN_PREFIX: &str = "fn main() {\n";
683 fn enclose_in_main_block(s: &str, config: &Config) -> String {
684 let indent = Indent::from_width(config, config.tab_spaces());
685 let mut result = String::with_capacity(s.len() * 2);
686 result.push_str(FN_MAIN_PREFIX);
687 let mut need_indent = true;
688 for (kind, line) in LineClasses::new(s) {
690 result.push_str(&indent.to_string(config));
692 result.push_str(&line);
694 need_indent = !kind.is_string() || line.ends_with('\\');
700 /// Format the given code block. Mainly targeted for code block in comment.
701 /// The code block may be incomplete (i.e. parser may be unable to parse it).
702 /// To avoid panic in parser, we wrap the code block with a dummy function.
703 /// The returned code block does *not* end with newline.
704 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
705 // Wrap the given code block with `fn main()` if it does not have one.
706 let snippet = enclose_in_main_block(code_snippet, config);
707 let mut result = String::with_capacity(snippet.len());
708 let mut is_first = true;
710 // Trim "fn main() {" on the first line and "}" on the last line,
711 // then unindent the whole code block.
712 let formatted = format_snippet(&snippet, config)?;
714 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
715 let mut is_indented = true;
716 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
722 let trimmed_line = if !is_indented {
724 } else if line.len() > config.max_width() {
725 // If there are lines that are larger than max width, we cannot tell
726 // whether we have succeeded but have some comments or strings that
727 // are too long, or we have failed to format code block. We will be
728 // conservative and just return `None` in this case.
730 } else if line.len() > config.tab_spaces() {
731 // Make sure that the line has leading whitespaces.
732 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
733 if line.starts_with(indent_str.as_ref()) {
734 let offset = if config.hard_tabs() {
746 result.push_str(trimmed_line);
747 is_indented = !kind.is_string() || line.ends_with('\\');
752 pub fn format_input<T: Write>(
756 ) -> Result<Summary, (ErrorKind, Summary)> {
757 syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| tup.0)
760 fn format_input_inner<T: Write>(
763 mut out: Option<&mut T>,
764 ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
765 let mut summary = Summary::default();
766 if config.disable_all_formatting() {
767 // When the input is from stdin, echo back the input.
768 if let Input::Text(ref buf) = input {
769 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
770 return Err((From::from(e), summary));
773 return Ok((summary, FileMap::new(), FormatReport::new()));
775 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
777 let tty_handler = if config.hide_parse_errors() {
778 let silent_emitter = Box::new(EmitterWriter::new(
779 Box::new(Vec::new()),
780 Some(codemap.clone()),
784 Handler::with_emitter(true, false, silent_emitter)
786 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
787 let color_cfg = if supports_color {
792 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
794 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
796 let main_file = match input {
797 Input::File(ref file) => FileName::Real(file.clone()),
798 Input::Text(..) => FileName::Stdin,
801 let krate = match parse_input(input, &parse_session, config) {
805 ParseError::Error(mut diagnostic) => diagnostic.emit(),
806 ParseError::Panic => {
807 // Note that if you see this message and want more information,
808 // then go to `parse_input` and run the parse function without
809 // `catch_unwind` so rustfmt panics and you can get a backtrace.
810 should_emit_verbose(&main_file, config, || {
811 println!("The Rust parser panicked")
814 ParseError::Recovered => {}
816 summary.add_parsing_error();
817 return Ok((summary, FileMap::new(), FormatReport::new()));
821 summary.mark_parse_time();
823 // Suppress error output after parsing.
824 let silent_emitter = Box::new(EmitterWriter::new(
825 Box::new(Vec::new()),
826 Some(codemap.clone()),
830 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
832 let report = FormatReport::new();
834 let format_result = format_ast(
840 |file_name, file, skipped_range, report| {
841 // For some reason, the codemap does not include terminating
842 // newlines so we must add one on for each file. This is sad.
843 filemap::append_newline(file);
845 format_lines(file, file_name, skipped_range, config, report);
847 if let Some(ref mut out) = out {
848 return filemap::write_file(file, file_name, out, config);
854 summary.mark_format_time();
856 should_emit_verbose(&main_file, config, || {
857 fn duration_to_f32(d: Duration) -> f32 {
858 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
862 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
863 duration_to_f32(summary.get_parse_time().unwrap()),
864 duration_to_f32(summary.get_format_time().unwrap()),
869 let report_errs = &report.internal.borrow().1;
870 if report_errs.has_check_errors {
871 summary.add_check_error();
873 if report_errs.has_operational_errors {
874 summary.add_operational_error();
878 match format_result {
879 Ok((file_map, has_diff)) => {
880 if report.has_warnings() {
881 summary.add_formatting_error();
888 Ok((summary, file_map, report))
890 Err(e) => Err((From::from(e), summary)),
894 /// A single span of changed lines, with 0 or more removed lines
895 /// and a vector of 0 or more inserted lines.
896 #[derive(Debug, PartialEq, Eq)]
897 struct ModifiedChunk {
898 /// The first to be removed from the original text
899 pub line_number_orig: u32,
900 /// The number of lines which have been replaced
901 pub lines_removed: u32,
903 pub lines: Vec<String>,
906 /// Set of changed sections of a file.
907 #[derive(Debug, PartialEq, Eq)]
908 struct ModifiedLines {
909 /// The set of changed chunks.
910 pub chunks: Vec<ModifiedChunk>,
913 /// Format a file and return a `ModifiedLines` data structure describing
914 /// the changed ranges of lines.
916 fn get_modified_lines(
919 ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
920 use std::io::BufRead;
922 let mut data = Vec::new();
924 let mut config = config.clone();
925 config.set().emit_mode(config::EmitMode::ModifiedLines);
926 format_input(input, &config, Some(&mut data))?;
928 let mut lines = data.lines();
929 let mut chunks = Vec::new();
930 while let Some(Ok(header)) = lines.next() {
931 // Parse the header line
932 let values: Vec<_> = header
934 .map(|s| s.parse::<u32>().unwrap())
936 assert_eq!(values.len(), 3);
937 let line_number_orig = values[0];
938 let lines_removed = values[1];
939 let num_added = values[2];
940 let mut added_lines = Vec::new();
941 for _ in 0..num_added {
942 added_lines.push(lines.next().unwrap().unwrap());
944 chunks.push(ModifiedChunk {
950 Ok(ModifiedLines { chunks })
959 pub fn format_and_emit_report(input: Input, config: &Config) -> Result<Summary, failure::Error> {
960 if !config.version_meets_requirement() {
961 return Err(format_err!("Version mismatch"));
963 let out = &mut stdout();
964 match syntax::with_globals(|| format_input_inner(input, config, Some(out))) {
965 Ok((summary, _, report)) => {
966 if report.has_warnings() {
967 match term::stderr() {
969 if use_colored_tty(config.color())
970 && t.supports_color()
971 && t.supports_attr(term::Attr::Bold) =>
973 match report.print_warnings_fancy(term::stderr().unwrap()) {
975 Err(..) => panic!("Unable to write to stderr: {}", report),
978 _ => eprintln!("{}", report),
984 Err((msg, mut summary)) => {
985 eprintln!("Error writing files: {}", msg);
986 summary.add_operational_error();
992 pub fn emit_pre_matter(config: &Config) -> Result<(), ErrorKind> {
993 if config.emit_mode() == EmitMode::Checkstyle {
994 let mut out = &mut stdout();
995 checkstyle::output_header(&mut out)?;
1000 pub fn emit_post_matter(config: &Config) -> Result<(), ErrorKind> {
1001 if config.emit_mode() == EmitMode::Checkstyle {
1002 let mut out = &mut stdout();
1003 checkstyle::output_footer(&mut out)?;
1010 use super::{format_code_block, format_snippet, Config};
1013 fn test_no_panic_on_format_snippet_and_format_code_block() {
1014 // `format_snippet()` and `format_code_block()` should not panic
1015 // even when we cannot parse the given snippet.
1016 let snippet = "let";
1017 assert!(format_snippet(snippet, &Config::default()).is_none());
1018 assert!(format_code_block(snippet, &Config::default()).is_none());
1021 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
1023 F: Fn(&str, &Config) -> Option<String>,
1025 let output = formatter(input, &Config::default());
1026 output.is_some() && output.unwrap() == expected
1030 fn test_format_snippet() {
1031 let snippet = "fn main() { println!(\"hello, world\"); }";
1032 let expected = "fn main() {\n \
1033 println!(\"hello, world\");\n\
1035 assert!(test_format_inner(format_snippet, snippet, expected));
1039 fn test_format_code_block_fail() {
1041 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1042 assert!(format_code_block(code_block, &Config::default()).is_none());
1046 fn test_format_code_block() {
1047 // simple code block
1048 let code_block = "let x=3;";
1049 let expected = "let x = 3;";
1050 assert!(test_format_inner(format_code_block, code_block, expected));
1052 // more complex code block, taken from chains.rs.
1054 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1056 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1057 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
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
1065 IndentStyle::Visual => (parent_shape, false),
1069 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1075 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1077 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1078 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1080 } else if is_block_expr(context, &parent, &parent_rewrite) {
1081 match context.config.indent_style() {
1082 // Try to put the first child on the same line with parent's last line
1083 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1084 // The parent is a block, so align the rest of the chain with the closing
1086 IndentStyle::Visual => (parent_shape, false),
1090 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1094 assert!(test_format_inner(format_code_block, code_block, expected));