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(custom_attribute)]
12 #![feature(decl_macro)]
13 // FIXME(cramertj) remove after match_default_bindings merges
14 #![allow(stable_features)]
15 #![feature(match_default_bindings)]
16 #![feature(type_ascription)]
17 #![feature(unicode_internals)]
20 extern crate derive_new;
25 extern crate itertools;
28 extern crate lazy_static;
34 extern crate serde_derive;
35 extern crate serde_json;
39 extern crate unicode_segmentation;
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};
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, WriteMode};
67 pub type FmtResult<T> = std::result::Result<T, failure::Error>;
69 pub const WRITE_MODE_LIST: &str =
70 "[replace|overwrite|display|plain|diff|coverage|checkstyle|check]";
77 pub(crate) mod checkstyle;
79 pub(crate) mod codemap;
81 pub(crate) mod config;
83 pub(crate) mod filemap;
91 pub(crate) mod modules;
96 pub(crate) mod rustfmt_diff;
104 pub(crate) mod visitor;
106 const STDIN: &str = "<stdin>";
108 // A map of the files of a crate, with their new content
109 pub(crate) type FileMap = Vec<FileRecord>;
111 pub(crate) type FileRecord = (FileName, String);
113 #[derive(Fail, Debug, Clone, Copy)]
115 // Line has exceeded character limit (found, maximum)
117 display = "line formatted, but exceeded maximum width (maximum: {} (see `max_width` option), found: {})",
121 LineOverflow(usize, usize),
122 // Line ends in whitespace
123 #[fail(display = "left behind trailing whitespace")]
125 // TODO or FIXME item without an issue number
126 #[fail(display = "found {}", _0)]
128 // License check has failed
129 #[fail(display = "license check failed")]
133 // Formatting errors that are identified *after* rustfmt has run.
134 struct FormattingError {
142 impl FormattingError {
143 fn msg_prefix(&self) -> &str {
145 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
146 ErrorKind::LicenseCheck => "error:",
147 ErrorKind::BadIssue(_) => "warning:",
151 fn msg_suffix(&self) -> &str {
152 if self.is_comment || self.is_string {
153 "set `error_on_unformatted = false` to suppress \
154 the warning against comments or string literals\n"
161 fn format_len(&self) -> (usize, usize) {
163 ErrorKind::LineOverflow(found, max) => (max, found - max),
164 ErrorKind::TrailingWhitespace => {
165 let trailing_ws_start = self.line_buffer
166 .rfind(|c: char| !c.is_whitespace())
171 self.line_buffer.len() - trailing_ws_start,
179 pub struct FormatReport {
180 // Maps stringified file paths to their associated formatting errors.
181 file_error_map: HashMap<FileName, Vec<FormattingError>>,
185 fn new() -> FormatReport {
187 file_error_map: HashMap::new(),
191 fn warning_count(&self) -> usize {
194 .map(|(_, errors)| errors.len())
198 fn has_warnings(&self) -> bool {
199 self.warning_count() > 0
202 fn print_warnings_fancy(
204 mut t: Box<term::Terminal<Output = io::Stderr>>,
205 ) -> Result<(), term::Error> {
206 for (file, errors) in &self.file_error_map {
207 for error in errors {
208 let prefix_space_len = error.line.to_string().len();
209 let prefix_spaces = " ".repeat(1 + prefix_space_len);
211 // First line: the overview of error
212 t.fg(term::color::RED)?;
213 t.attr(term::Attr::Bold)?;
214 write!(t, "{} ", error.msg_prefix())?;
216 t.attr(term::Attr::Bold)?;
217 writeln!(t, "{}", error.kind)?;
219 // Second line: file info
220 write!(t, "{}--> ", &prefix_spaces[1..])?;
222 writeln!(t, "{}:{}", file, error.line)?;
224 // Third to fifth lines: show the line which triggered error, if available.
225 if !error.line_buffer.is_empty() {
226 let (space_len, target_len) = error.format_len();
227 t.attr(term::Attr::Bold)?;
228 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
230 writeln!(t, "{}", error.line_buffer)?;
231 t.attr(term::Attr::Bold)?;
232 write!(t, "{}| ", prefix_spaces)?;
233 t.fg(term::color::RED)?;
234 writeln!(t, "{}", target_str(space_len, target_len))?;
238 // The last line: show note if available.
239 let msg_suffix = error.msg_suffix();
240 if !msg_suffix.is_empty() {
241 t.attr(term::Attr::Bold)?;
242 write!(t, "{}= note: ", prefix_spaces)?;
244 writeln!(t, "{}", error.msg_suffix())?;
252 if !self.file_error_map.is_empty() {
253 t.attr(term::Attr::Bold)?;
254 write!(t, "warning: ")?;
258 "rustfmt may have failed to format. See previous {} errors.\n\n",
259 self.warning_count(),
267 fn target_str(space_len: usize, target_len: usize) -> String {
268 let empty_line = " ".repeat(space_len);
269 let overflowed = "^".repeat(target_len);
270 empty_line + &overflowed
273 impl fmt::Display for FormatReport {
274 // Prints all the formatting errors.
275 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
276 for (file, errors) in &self.file_error_map {
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 let error_line_buffer = if error.line_buffer.is_empty() {
284 let (space_len, target_len) = error.format_len();
286 "{}|\n{} | {}\n{}| {}",
291 target_str(space_len, target_len)
295 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
296 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
297 let msg_suffix = error.msg_suffix();
298 let note = if msg_suffix.is_empty() {
301 format!("{}note= ", prefix_spaces)
315 if !self.file_error_map.is_empty() {
318 "warning: rustfmt may have failed to format. See previous {} errors.",
319 self.warning_count(),
326 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
330 if config.verbose() && path.to_string() != STDIN {
335 // Formatting which depends on the AST.
338 parse_session: &mut ParseSess,
339 main_file: &FileName,
342 ) -> Result<(FileMap, bool), io::Error>
344 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
346 let mut result = FileMap::new();
347 // diff mode: check if any files are differing
348 let mut has_diff = false;
350 // We always skip children for the "Plain" write mode, since there is
351 // nothing to distinguish the nested module contents.
352 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
353 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
354 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
357 should_emit_verbose(&path, config, || println!("Formatting {}", path));
358 let filemap = parse_session
360 .lookup_char_pos(module.inner.lo())
362 let big_snippet = filemap.src.as_ref().unwrap();
363 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
364 let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
365 // Format inner attributes if available.
366 if !krate.attrs.is_empty() && path == *main_file {
367 visitor.skip_empty_lines(filemap.end_pos);
368 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
369 visitor.push_rewrite(module.inner, None);
371 visitor.format_separate_mod(module, &*filemap);
374 visitor.last_pos = filemap.start_pos;
375 visitor.skip_empty_lines(filemap.end_pos);
376 visitor.format_separate_mod(module, &*filemap);
381 ::utils::count_newlines(&visitor.buffer)
384 let filename = path.clone();
385 has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
386 Ok(result) => result,
388 // Create a new error with path_str to help users see which files failed
389 let err_msg = format!("{}: {}", path, e);
390 return Err(io::Error::new(e.kind(), err_msg));
394 result.push((filename, visitor.buffer));
397 Ok((result, has_diff))
400 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
401 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
404 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
407 fn should_report_error(
409 char_kind: FullCodeCharKind,
411 error_kind: ErrorKind,
413 let allow_error_report = if char_kind.is_comment() || is_string {
414 config.error_on_unformatted()
420 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
421 ErrorKind::TrailingWhitespace => allow_error_report,
426 // Formatting done on a char by char or line by line basis.
427 // FIXME(#20) other stuff for parity with make tidy
431 skipped_range: &[(usize, usize)],
433 report: &mut FormatReport,
435 let mut trims = vec![];
436 let mut last_wspace: Option<usize> = None;
437 let mut line_len = 0;
438 let mut cur_line = 1;
439 let mut newline_count = 0;
440 let mut errors = vec![];
441 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
442 let mut line_buffer = String::with_capacity(config.max_width() * 2);
443 let mut is_string = false; // true if the current line contains a string literal.
444 let mut format_line = config.file_lines().contains_line(name, cur_line);
445 let allow_issue_seek = !issue_seeker.is_disabled();
448 if let Some(ref license_template) = config.license_template {
449 if !license_template.is_match(text) {
450 errors.push(FormattingError {
452 kind: ErrorKind::LicenseCheck,
455 line_buffer: String::new(),
460 // Iterate over the chars in the file map.
461 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
466 if allow_issue_seek && format_line {
467 // Add warnings for bad todos/ fixmes
468 if let Some(issue) = issue_seeker.inspect(c) {
469 errors.push(FormattingError {
471 kind: ErrorKind::BadIssue(issue),
474 line_buffer: String::new(),
481 // Check for (and record) trailing whitespace.
482 if let Some(..) = last_wspace {
483 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
484 trims.push((cur_line, kind, line_buffer.clone()));
489 // Check for any line width errors we couldn't correct.
490 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
491 if line_len > config.max_width() && !is_skipped_line(cur_line, skipped_range)
492 && should_report_error(config, kind, is_string, error_kind)
494 errors.push(FormattingError {
497 is_comment: kind.is_comment(),
499 line_buffer: line_buffer.clone(),
506 format_line = config.file_lines().contains_line(name, cur_line);
513 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
514 if c.is_whitespace() {
515 if last_wspace.is_none() {
516 last_wspace = Some(b);
522 if kind.is_string() {
528 if newline_count > 1 {
529 debug!("track truncate: {} {}", text.len(), newline_count);
530 let line = text.len() - newline_count + 1;
534 for &(l, kind, ref b) in &trims {
535 if !is_skipped_line(l, skipped_range) {
536 errors.push(FormattingError {
538 kind: ErrorKind::TrailingWhitespace,
539 is_comment: kind.is_comment(),
540 is_string: kind.is_string(),
541 line_buffer: b.clone(),
546 report.file_error_map.insert(name.clone(), errors);
549 fn parse_input<'sess>(
551 parse_session: &'sess ParseSess,
553 ) -> Result<ast::Crate, ParseError<'sess>> {
554 let mut parser = match input {
555 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
556 Input::Text(text) => parse::new_parser_from_source_str(
558 FileName::Custom("stdin".to_owned()),
563 parser.cfg_mods = false;
564 if config.skip_children() {
565 parser.recurse_into_file_modules = false;
568 let mut parser = AssertUnwindSafe(parser);
569 let result = catch_unwind(move || parser.0.parse_crate_mod());
573 if parse_session.span_diagnostic.has_errors() {
574 // Bail out if the parser recovered from an error.
575 Err(ParseError::Recovered)
580 Ok(Err(e)) => Err(ParseError::Error(e)),
581 Err(_) => Err(ParseError::Panic),
585 /// All the ways that parsing can fail.
586 enum ParseError<'sess> {
587 /// There was an error, but the parser recovered.
589 /// There was an error (supplied) and parsing failed.
590 Error(DiagnosticBuilder<'sess>),
591 /// The parser panicked.
595 /// Format the given snippet. The snippet is expected to be *complete* code.
596 /// When we cannot parse the given snippet, this function returns `None`.
597 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
598 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
599 let input = Input::Text(snippet.into());
600 let mut config = config.clone();
601 config.set().write_mode(config::WriteMode::Plain);
602 config.set().hide_parse_errors(true);
603 match format_input(input, &config, Some(&mut out)) {
604 // `format_input()` returns an empty string on parsing error.
605 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
606 Ok(..) => String::from_utf8(out).ok(),
611 const FN_MAIN_PREFIX: &str = "fn main() {\n";
613 fn enclose_in_main_block(s: &str, config: &Config) -> String {
614 let indent = Indent::from_width(config, config.tab_spaces());
615 let mut result = String::with_capacity(s.len() * 2);
616 result.push_str(FN_MAIN_PREFIX);
617 let mut need_indent = true;
618 for (kind, line) in LineClasses::new(s) {
620 result.push_str(&indent.to_string(config));
622 result.push_str(&line);
624 need_indent = !kind.is_string() || line.ends_with('\\');
630 /// Format the given code block. Mainly targeted for code block in comment.
631 /// The code block may be incomplete (i.e. parser may be unable to parse it).
632 /// To avoid panic in parser, we wrap the code block with a dummy function.
633 /// The returned code block does *not* end with newline.
634 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
635 // Wrap the given code block with `fn main()` if it does not have one.
636 let snippet = enclose_in_main_block(code_snippet, config);
637 let mut result = String::with_capacity(snippet.len());
638 let mut is_first = true;
640 // Trim "fn main() {" on the first line and "}" on the last line,
641 // then unindent the whole code block.
642 let formatted = format_snippet(&snippet, config)?;
644 let block_len = formatted.len().checked_sub(2).unwrap_or(0);
645 let mut is_indented = true;
646 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
652 let trimmed_line = if !is_indented {
654 } else if line.len() > config.max_width() {
655 // If there are lines that are larger than max width, we cannot tell
656 // whether we have succeeded but have some comments or strings that
657 // are too long, or we have failed to format code block. We will be
658 // conservative and just return `None` in this case.
660 } else if line.len() > config.tab_spaces() {
661 // Make sure that the line has leading whitespaces.
662 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
663 if line.starts_with(indent_str.as_ref()) {
664 let offset = if config.hard_tabs() {
676 result.push_str(trimmed_line);
677 is_indented = !kind.is_string() || line.ends_with('\\');
682 pub fn format_input<T: Write>(
686 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
687 syntax::with_globals(|| format_input_inner(input, config, out))
690 fn format_input_inner<T: Write>(
693 mut out: Option<&mut T>,
694 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
695 let mut summary = Summary::default();
696 if config.disable_all_formatting() {
697 // When the input is from stdin, echo back the input.
698 if let Input::Text(ref buf) = input {
699 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
700 return Err((e, summary));
703 return Ok((summary, FileMap::new(), FormatReport::new()));
705 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
707 let tty_handler = if config.hide_parse_errors() {
708 let silent_emitter = Box::new(EmitterWriter::new(
709 Box::new(Vec::new()),
710 Some(codemap.clone()),
714 Handler::with_emitter(true, false, silent_emitter)
716 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
717 let color_cfg = if supports_color {
722 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
724 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
726 let main_file = match input {
727 Input::File(ref file) => FileName::Real(file.clone()),
728 Input::Text(..) => FileName::Custom("stdin".to_owned()),
731 let krate = match parse_input(input, &parse_session, config) {
735 ParseError::Error(mut diagnostic) => diagnostic.emit(),
736 ParseError::Panic => {
737 // Note that if you see this message and want more information,
738 // then go to `parse_input` and run the parse function without
739 // `catch_unwind` so rustfmt panics and you can get a backtrace.
740 should_emit_verbose(&main_file, config, || {
741 println!("The Rust parser panicked")
744 ParseError::Recovered => {}
746 summary.add_parsing_error();
747 return Ok((summary, FileMap::new(), FormatReport::new()));
751 summary.mark_parse_time();
753 // Suppress error output after parsing.
754 let silent_emitter = Box::new(EmitterWriter::new(
755 Box::new(Vec::new()),
756 Some(codemap.clone()),
760 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
762 let mut report = FormatReport::new();
764 let format_result = format_ast(
769 |file_name, file, skipped_range| {
770 // For some reason, the codemap does not include terminating
771 // newlines so we must add one on for each file. This is sad.
772 filemap::append_newline(file);
774 format_lines(file, file_name, skipped_range, config, &mut report);
776 if let Some(ref mut out) = out {
777 return filemap::write_file(file, file_name, out, config);
783 summary.mark_format_time();
785 should_emit_verbose(&main_file, config, || {
786 fn duration_to_f32(d: Duration) -> f32 {
787 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
791 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
792 duration_to_f32(summary.get_parse_time().unwrap()),
793 duration_to_f32(summary.get_format_time().unwrap()),
797 match format_result {
798 Ok((file_map, has_diff)) => {
799 if report.has_warnings() {
800 summary.add_formatting_error();
807 Ok((summary, file_map, report))
809 Err(e) => Err((e, summary)),
813 /// A single span of changed lines, with 0 or more removed lines
814 /// and a vector of 0 or more inserted lines.
815 #[derive(Debug, PartialEq, Eq)]
816 struct ModifiedChunk {
817 /// The first to be removed from the original text
818 pub line_number_orig: u32,
819 /// The number of lines which have been replaced
820 pub lines_removed: u32,
822 pub lines: Vec<String>,
825 /// Set of changed sections of a file.
826 #[derive(Debug, PartialEq, Eq)]
827 struct ModifiedLines {
828 /// The set of changed chunks.
829 pub chunks: Vec<ModifiedChunk>,
832 /// The successful result of formatting via `get_modified_lines()`.
834 struct ModifiedLinesResult {
835 /// The high level summary details
836 pub summary: Summary,
837 /// The result Filemap
838 pub filemap: FileMap,
839 /// Map of formatting errors
840 pub report: FormatReport,
841 /// The sets of updated lines.
842 pub modified_lines: ModifiedLines,
845 /// Format a file and return a `ModifiedLines` data structure describing
846 /// the changed ranges of lines.
848 fn get_modified_lines(
851 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
852 use std::io::BufRead;
854 let mut data = Vec::new();
856 let mut config = config.clone();
857 config.set().write_mode(config::WriteMode::Modified);
858 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
860 let mut lines = data.lines();
861 let mut chunks = Vec::new();
862 while let Some(Ok(header)) = lines.next() {
863 // Parse the header line
864 let values: Vec<_> = header
866 .map(|s| s.parse::<u32>().unwrap())
868 assert_eq!(values.len(), 3);
869 let line_number_orig = values[0];
870 let lines_removed = values[1];
871 let num_added = values[2];
872 let mut added_lines = Vec::new();
873 for _ in 0..num_added {
874 added_lines.push(lines.next().unwrap().unwrap());
876 chunks.push(ModifiedChunk {
882 Ok(ModifiedLinesResult {
886 modified_lines: ModifiedLines { chunks },
896 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
897 if !config.version_meets_requirement() {
898 return Err(format_err!("Version mismatch"));
900 let out = &mut stdout();
901 match format_input(input, config, Some(out)) {
902 Ok((summary, _, report)) => {
903 if report.has_warnings() {
904 match term::stderr() {
906 if use_colored_tty(config.color()) && t.supports_color()
907 && t.supports_attr(term::Attr::Bold) =>
909 match report.print_warnings_fancy(term::stderr().unwrap()) {
911 Err(..) => panic!("Unable to write to stderr: {}", report),
914 _ => eprintln!("{}", report),
920 Err((msg, mut summary)) => {
921 eprintln!("Error writing files: {}", msg);
922 summary.add_operational_error();
928 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
929 if config.write_mode() == WriteMode::Checkstyle {
930 let mut out = &mut stdout();
931 checkstyle::output_header(&mut out)?;
936 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
937 if config.write_mode() == WriteMode::Checkstyle {
938 let mut out = &mut stdout();
939 checkstyle::output_footer(&mut out)?;
946 use super::{format_code_block, format_snippet, Config};
949 fn test_no_panic_on_format_snippet_and_format_code_block() {
950 // `format_snippet()` and `format_code_block()` should not panic
951 // even when we cannot parse the given snippet.
953 assert!(format_snippet(snippet, &Config::default()).is_none());
954 assert!(format_code_block(snippet, &Config::default()).is_none());
957 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
959 F: Fn(&str, &Config) -> Option<String>,
961 let output = formatter(input, &Config::default());
962 output.is_some() && output.unwrap() == expected
966 fn test_format_snippet() {
967 let snippet = "fn main() { println!(\"hello, world\"); }";
968 let expected = "fn main() {\n \
969 println!(\"hello, world\");\n\
971 assert!(test_format_inner(format_snippet, snippet, expected));
975 fn test_format_code_block_fail() {
977 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
978 assert!(format_code_block(code_block, &Config::default()).is_none());
982 fn test_format_code_block() {
984 let code_block = "let x=3;";
985 let expected = "let x = 3;";
986 assert!(test_format_inner(format_code_block, code_block, expected));
988 // more complex code block, taken from chains.rs.
990 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
992 chain_indent(context, shape.add_offset(parent_rewrite.len())),
993 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
995 } else if is_block_expr(context, &parent, &parent_rewrite) {
996 match context.config.indent_style() {
997 // Try to put the first child on the same line with parent's last line
998 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
999 // The parent is a block, so align the rest of the chain with the closing
1001 IndentStyle::Visual => (parent_shape, false),
1005 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1011 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1013 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1014 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1016 } else if is_block_expr(context, &parent, &parent_rewrite) {
1017 match context.config.indent_style() {
1018 // Try to put the first child on the same line with parent's last line
1019 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1020 // The parent is a block, so align the rest of the chain with the closing
1022 IndentStyle::Visual => (parent_shape, false),
1026 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1030 assert!(test_format_inner(format_code_block, code_block, expected));