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 file_error_map: Rc<RefCell<HashMap<FileName, Vec<FormattingError>>>>,
207 fn new() -> FormatReport {
209 file_error_map: Rc::new(RefCell::new(HashMap::new())),
213 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
217 .and_modify(|fe| fe.append(&mut v))
221 fn warning_count(&self) -> usize {
225 .map(|(_, errors)| errors.len())
229 fn has_warnings(&self) -> bool {
230 self.warning_count() > 0
233 fn print_warnings_fancy(
235 mut t: Box<term::Terminal<Output = io::Stderr>>,
236 ) -> Result<(), term::Error> {
237 for (file, errors) in &*self.file_error_map.borrow() {
238 for error in errors {
239 let prefix_space_len = error.line.to_string().len();
240 let prefix_spaces = " ".repeat(1 + prefix_space_len);
242 // First line: the overview of error
243 t.fg(term::color::RED)?;
244 t.attr(term::Attr::Bold)?;
245 write!(t, "{} ", error.msg_prefix())?;
247 t.attr(term::Attr::Bold)?;
248 writeln!(t, "{}", error.kind)?;
250 // Second line: file info
251 write!(t, "{}--> ", &prefix_spaces[1..])?;
253 writeln!(t, "{}:{}", file, error.line)?;
255 // Third to fifth lines: show the line which triggered error, if available.
256 if !error.line_buffer.is_empty() {
257 let (space_len, target_len) = error.format_len();
258 t.attr(term::Attr::Bold)?;
259 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
261 writeln!(t, "{}", error.line_buffer)?;
262 t.attr(term::Attr::Bold)?;
263 write!(t, "{}| ", prefix_spaces)?;
264 t.fg(term::color::RED)?;
265 writeln!(t, "{}", target_str(space_len, target_len))?;
269 // The last line: show note if available.
270 let msg_suffix = error.msg_suffix();
271 if !msg_suffix.is_empty() {
272 t.attr(term::Attr::Bold)?;
273 write!(t, "{}= note: ", prefix_spaces)?;
275 writeln!(t, "{}", error.msg_suffix())?;
283 if !self.file_error_map.borrow().is_empty() {
284 t.attr(term::Attr::Bold)?;
285 write!(t, "warning: ")?;
289 "rustfmt may have failed to format. See previous {} errors.\n\n",
290 self.warning_count(),
298 fn target_str(space_len: usize, target_len: usize) -> String {
299 let empty_line = " ".repeat(space_len);
300 let overflowed = "^".repeat(target_len);
301 empty_line + &overflowed
304 impl fmt::Display for FormatReport {
305 // Prints all the formatting errors.
306 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
307 for (file, errors) in &*self.file_error_map.borrow() {
308 for error in errors {
309 let prefix_space_len = error.line.to_string().len();
310 let prefix_spaces = " ".repeat(1 + prefix_space_len);
312 let error_line_buffer = if error.line_buffer.is_empty() {
315 let (space_len, target_len) = error.format_len();
317 "{}|\n{} | {}\n{}| {}",
322 target_str(space_len, target_len)
326 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
327 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
328 let msg_suffix = error.msg_suffix();
329 let note = if msg_suffix.is_empty() {
332 format!("{}note= ", prefix_spaces)
346 if !self.file_error_map.borrow().is_empty() {
349 "warning: rustfmt may have failed to format. See previous {} errors.",
350 self.warning_count(),
357 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
361 if config.verbose() == Verbosity::Verbose && path.to_string() != STDIN {
366 // Formatting which depends on the AST.
369 parse_session: &mut ParseSess,
370 main_file: &FileName,
372 report: FormatReport,
374 ) -> Result<(FileMap, bool), io::Error>
376 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
378 let mut result = FileMap::new();
379 // diff mode: check if any files are differing
380 let mut has_diff = false;
382 let skip_children = config.skip_children();
383 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
384 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
387 should_emit_verbose(&path, config, || println!("Formatting {}", path));
388 let filemap = parse_session
390 .lookup_char_pos(module.inner.lo())
392 let big_snippet = filemap.src.as_ref().unwrap();
393 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
395 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
396 // Format inner attributes if available.
397 if !krate.attrs.is_empty() && path == *main_file {
398 visitor.skip_empty_lines(filemap.end_pos);
399 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
400 visitor.push_rewrite(module.inner, None);
402 visitor.format_separate_mod(module, &*filemap);
405 visitor.last_pos = filemap.start_pos;
406 visitor.skip_empty_lines(filemap.end_pos);
407 visitor.format_separate_mod(module, &*filemap);
412 ::utils::count_newlines(&visitor.buffer)
415 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
416 Ok(result) => result,
418 // Create a new error with path_str to help users see which files failed
419 let err_msg = format!("{}: {}", path, e);
420 return Err(io::Error::new(e.kind(), err_msg));
424 result.push((path.clone(), visitor.buffer));
427 Ok((result, has_diff))
430 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
431 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
434 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
437 fn should_report_error(
439 char_kind: FullCodeCharKind,
441 error_kind: ErrorKind,
443 let allow_error_report = if char_kind.is_comment() || is_string {
444 config.error_on_unformatted()
450 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
451 ErrorKind::TrailingWhitespace => allow_error_report,
456 // Formatting done on a char by char or line by line basis.
457 // FIXME(#20) other stuff for parity with make tidy
461 skipped_range: &[(usize, usize)],
463 report: &FormatReport,
465 let mut trims = vec![];
466 let mut last_wspace: Option<usize> = None;
467 let mut line_len = 0;
468 let mut cur_line = 1;
469 let mut newline_count = 0;
470 let mut errors = vec![];
471 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
472 let mut line_buffer = String::with_capacity(config.max_width() * 2);
473 let mut is_string = false; // true if the current line contains a string literal.
474 let mut format_line = config.file_lines().contains_line(name, cur_line);
475 let allow_issue_seek = !issue_seeker.is_disabled();
478 if let Some(ref license_template) = config.license_template {
479 if !license_template.is_match(text) {
480 errors.push(FormattingError {
482 kind: ErrorKind::LicenseCheck,
485 line_buffer: String::new(),
490 // Iterate over the chars in the file map.
491 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
496 if allow_issue_seek && format_line {
497 // Add warnings for bad todos/ fixmes
498 if let Some(issue) = issue_seeker.inspect(c) {
499 errors.push(FormattingError {
501 kind: ErrorKind::BadIssue(issue),
504 line_buffer: String::new(),
511 // Check for (and record) trailing whitespace.
512 if let Some(..) = last_wspace {
513 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
514 trims.push((cur_line, kind, line_buffer.clone()));
519 // Check for any line width errors we couldn't correct.
520 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
521 if line_len > config.max_width()
522 && !is_skipped_line(cur_line, skipped_range)
523 && should_report_error(config, kind, is_string, error_kind)
525 errors.push(FormattingError {
528 is_comment: kind.is_comment(),
530 line_buffer: line_buffer.clone(),
537 format_line = config.file_lines().contains_line(name, cur_line);
544 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
545 if c.is_whitespace() {
546 if last_wspace.is_none() {
547 last_wspace = Some(b);
553 if kind.is_string() {
559 if newline_count > 1 {
560 debug!("track truncate: {} {}", text.len(), newline_count);
561 let line = text.len() - newline_count + 1;
565 for &(l, kind, ref b) in &trims {
566 if !is_skipped_line(l, skipped_range) {
567 errors.push(FormattingError {
569 kind: ErrorKind::TrailingWhitespace,
570 is_comment: kind.is_comment(),
571 is_string: kind.is_string(),
572 line_buffer: b.clone(),
577 report.append(name.clone(), errors);
580 fn parse_input<'sess>(
582 parse_session: &'sess ParseSess,
584 ) -> Result<ast::Crate, ParseError<'sess>> {
585 let mut parser = match input {
586 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
587 Input::Text(text) => parse::new_parser_from_source_str(
589 FileName::Custom("stdin".to_owned()),
594 parser.cfg_mods = false;
595 if config.skip_children() {
596 parser.recurse_into_file_modules = false;
599 let mut parser = AssertUnwindSafe(parser);
600 let result = catch_unwind(move || parser.0.parse_crate_mod());
604 if parse_session.span_diagnostic.has_errors() {
605 // Bail out if the parser recovered from an error.
606 Err(ParseError::Recovered)
611 Ok(Err(e)) => Err(ParseError::Error(e)),
612 Err(_) => Err(ParseError::Panic),
616 /// All the ways that parsing can fail.
617 enum ParseError<'sess> {
618 /// There was an error, but the parser recovered.
620 /// There was an error (supplied) and parsing failed.
621 Error(DiagnosticBuilder<'sess>),
622 /// The parser panicked.
626 /// Format the given snippet. The snippet is expected to be *complete* code.
627 /// When we cannot parse the given snippet, this function returns `None`.
628 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
629 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
630 let input = Input::Text(snippet.into());
631 let mut config = config.clone();
632 config.set().write_mode(config::WriteMode::Display);
633 config.set().verbose(Verbosity::Quiet);
634 config.set().hide_parse_errors(true);
635 match format_input(input, &config, Some(&mut out)) {
636 // `format_input()` returns an empty string on parsing error.
637 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
638 Ok(..) => String::from_utf8(out).ok(),
643 const FN_MAIN_PREFIX: &str = "fn main() {\n";
645 fn enclose_in_main_block(s: &str, config: &Config) -> String {
646 let indent = Indent::from_width(config, config.tab_spaces());
647 let mut result = String::with_capacity(s.len() * 2);
648 result.push_str(FN_MAIN_PREFIX);
649 let mut need_indent = true;
650 for (kind, line) in LineClasses::new(s) {
652 result.push_str(&indent.to_string(config));
654 result.push_str(&line);
656 need_indent = !kind.is_string() || line.ends_with('\\');
662 /// Format the given code block. Mainly targeted for code block in comment.
663 /// The code block may be incomplete (i.e. parser may be unable to parse it).
664 /// To avoid panic in parser, we wrap the code block with a dummy function.
665 /// The returned code block does *not* end with newline.
666 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
667 // Wrap the given code block with `fn main()` if it does not have one.
668 let snippet = enclose_in_main_block(code_snippet, config);
669 let mut result = String::with_capacity(snippet.len());
670 let mut is_first = true;
672 // Trim "fn main() {" on the first line and "}" on the last line,
673 // then unindent the whole code block.
674 let formatted = format_snippet(&snippet, config)?;
676 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
677 let mut is_indented = true;
678 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
684 let trimmed_line = if !is_indented {
686 } else if line.len() > config.max_width() {
687 // If there are lines that are larger than max width, we cannot tell
688 // whether we have succeeded but have some comments or strings that
689 // are too long, or we have failed to format code block. We will be
690 // conservative and just return `None` in this case.
692 } else if line.len() > config.tab_spaces() {
693 // Make sure that the line has leading whitespaces.
694 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
695 if line.starts_with(indent_str.as_ref()) {
696 let offset = if config.hard_tabs() {
708 result.push_str(trimmed_line);
709 is_indented = !kind.is_string() || line.ends_with('\\');
714 pub fn format_input<T: Write>(
718 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
719 syntax::with_globals(|| format_input_inner(input, config, out))
722 fn format_input_inner<T: Write>(
725 mut out: Option<&mut T>,
726 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
727 let mut summary = Summary::default();
728 if config.disable_all_formatting() {
729 // When the input is from stdin, echo back the input.
730 if let Input::Text(ref buf) = input {
731 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
732 return Err((e, summary));
735 return Ok((summary, FileMap::new(), FormatReport::new()));
737 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
739 let tty_handler = if config.hide_parse_errors() {
740 let silent_emitter = Box::new(EmitterWriter::new(
741 Box::new(Vec::new()),
742 Some(codemap.clone()),
746 Handler::with_emitter(true, false, silent_emitter)
748 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
749 let color_cfg = if supports_color {
754 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
756 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
758 let main_file = match input {
759 Input::File(ref file) => FileName::Real(file.clone()),
760 Input::Text(..) => FileName::Custom("stdin".to_owned()),
763 let krate = match parse_input(input, &parse_session, config) {
767 ParseError::Error(mut diagnostic) => diagnostic.emit(),
768 ParseError::Panic => {
769 // Note that if you see this message and want more information,
770 // then go to `parse_input` and run the parse function without
771 // `catch_unwind` so rustfmt panics and you can get a backtrace.
772 should_emit_verbose(&main_file, config, || {
773 println!("The Rust parser panicked")
776 ParseError::Recovered => {}
778 summary.add_parsing_error();
779 return Ok((summary, FileMap::new(), FormatReport::new()));
783 summary.mark_parse_time();
785 // Suppress error output after parsing.
786 let silent_emitter = Box::new(EmitterWriter::new(
787 Box::new(Vec::new()),
788 Some(codemap.clone()),
792 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
794 let report = FormatReport::new();
796 let format_result = format_ast(
802 |file_name, file, skipped_range, report| {
803 // For some reason, the codemap does not include terminating
804 // newlines so we must add one on for each file. This is sad.
805 filemap::append_newline(file);
807 format_lines(file, file_name, skipped_range, config, report);
809 if let Some(ref mut out) = out {
810 return filemap::write_file(file, file_name, out, config);
816 summary.mark_format_time();
818 should_emit_verbose(&main_file, config, || {
819 fn duration_to_f32(d: Duration) -> f32 {
820 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
824 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
825 duration_to_f32(summary.get_parse_time().unwrap()),
826 duration_to_f32(summary.get_format_time().unwrap()),
830 match format_result {
831 Ok((file_map, has_diff)) => {
832 if report.has_warnings() {
833 summary.add_formatting_error();
840 Ok((summary, file_map, report))
842 Err(e) => Err((e, summary)),
846 /// A single span of changed lines, with 0 or more removed lines
847 /// and a vector of 0 or more inserted lines.
848 #[derive(Debug, PartialEq, Eq)]
849 struct ModifiedChunk {
850 /// The first to be removed from the original text
851 pub line_number_orig: u32,
852 /// The number of lines which have been replaced
853 pub lines_removed: u32,
855 pub lines: Vec<String>,
858 /// Set of changed sections of a file.
859 #[derive(Debug, PartialEq, Eq)]
860 struct ModifiedLines {
861 /// The set of changed chunks.
862 pub chunks: Vec<ModifiedChunk>,
865 /// The successful result of formatting via `get_modified_lines()`.
867 struct ModifiedLinesResult {
868 /// The high level summary details
869 pub summary: Summary,
870 /// The result Filemap
871 pub filemap: FileMap,
872 /// Map of formatting errors
873 pub report: FormatReport,
874 /// The sets of updated lines.
875 pub modified_lines: ModifiedLines,
878 /// Format a file and return a `ModifiedLines` data structure describing
879 /// the changed ranges of lines.
881 fn get_modified_lines(
884 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
885 use std::io::BufRead;
887 let mut data = Vec::new();
889 let mut config = config.clone();
890 config.set().write_mode(config::WriteMode::Modified);
891 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
893 let mut lines = data.lines();
894 let mut chunks = Vec::new();
895 while let Some(Ok(header)) = lines.next() {
896 // Parse the header line
897 let values: Vec<_> = header
899 .map(|s| s.parse::<u32>().unwrap())
901 assert_eq!(values.len(), 3);
902 let line_number_orig = values[0];
903 let lines_removed = values[1];
904 let num_added = values[2];
905 let mut added_lines = Vec::new();
906 for _ in 0..num_added {
907 added_lines.push(lines.next().unwrap().unwrap());
909 chunks.push(ModifiedChunk {
915 Ok(ModifiedLinesResult {
919 modified_lines: ModifiedLines { chunks },
929 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
930 if !config.version_meets_requirement() {
931 return Err(format_err!("Version mismatch"));
933 let out = &mut stdout();
934 match format_input(input, config, Some(out)) {
935 Ok((summary, _, report)) => {
936 if report.has_warnings() {
937 match term::stderr() {
939 if use_colored_tty(config.color())
940 && t.supports_color()
941 && t.supports_attr(term::Attr::Bold) =>
943 match report.print_warnings_fancy(term::stderr().unwrap()) {
945 Err(..) => panic!("Unable to write to stderr: {}", report),
948 _ => eprintln!("{}", report),
954 Err((msg, mut summary)) => {
955 eprintln!("Error writing files: {}", msg);
956 summary.add_operational_error();
962 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
963 if config.write_mode() == WriteMode::Checkstyle {
964 let mut out = &mut stdout();
965 checkstyle::output_header(&mut out)?;
970 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
971 if config.write_mode() == WriteMode::Checkstyle {
972 let mut out = &mut stdout();
973 checkstyle::output_footer(&mut out)?;
980 use super::{format_code_block, format_snippet, Config};
983 fn test_no_panic_on_format_snippet_and_format_code_block() {
984 // `format_snippet()` and `format_code_block()` should not panic
985 // even when we cannot parse the given snippet.
987 assert!(format_snippet(snippet, &Config::default()).is_none());
988 assert!(format_code_block(snippet, &Config::default()).is_none());
991 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
993 F: Fn(&str, &Config) -> Option<String>,
995 let output = formatter(input, &Config::default());
996 output.is_some() && output.unwrap() == expected
1000 fn test_format_snippet() {
1001 let snippet = "fn main() { println!(\"hello, world\"); }";
1002 let expected = "fn main() {\n \
1003 println!(\"hello, world\");\n\
1005 assert!(test_format_inner(format_snippet, snippet, expected));
1009 fn test_format_code_block_fail() {
1011 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1012 assert!(format_code_block(code_block, &Config::default()).is_none());
1016 fn test_format_code_block() {
1017 // simple code block
1018 let code_block = "let x=3;";
1019 let expected = "let x = 3;";
1020 assert!(test_format_inner(format_code_block, code_block, expected));
1022 // more complex code block, taken from chains.rs.
1024 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1026 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1027 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1029 } else if is_block_expr(context, &parent, &parent_rewrite) {
1030 match context.config.indent_style() {
1031 // Try to put the first child on the same line with parent's last line
1032 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1033 // The parent is a block, so align the rest of the chain with the closing
1035 IndentStyle::Visual => (parent_shape, false),
1039 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1045 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1047 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1048 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1050 } else if is_block_expr(context, &parent, &parent_rewrite) {
1051 match context.config.indent_style() {
1052 // Try to put the first child on the same line with parent's last line
1053 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1054 // The parent is a block, so align the rest of the chain with the closing
1056 IndentStyle::Visual => (parent_shape, false),
1060 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1064 assert!(test_format_inner(format_code_block, code_block, expected));