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 #![allow(unused_attributes)]
16 #![feature(match_default_bindings)]
17 #![feature(type_ascription)]
18 #![feature(unicode_internals)]
21 extern crate derive_new;
26 extern crate itertools;
29 extern crate lazy_static;
33 extern crate rustc_target;
36 extern crate serde_derive;
37 extern crate serde_json;
41 extern crate unicode_segmentation;
43 use std::collections::HashMap;
45 use std::io::{self, stdout, Write};
46 use std::panic::{catch_unwind, AssertUnwindSafe};
47 use std::path::PathBuf;
49 use std::time::Duration;
52 pub use syntax::codemap::FileName;
53 use syntax::codemap::{CodeMap, FilePathMapping};
54 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
55 use syntax::errors::{DiagnosticBuilder, Handler};
56 use syntax::parse::{self, ParseSess};
58 use comment::{CharClasses, FullCodeCharKind, LineClasses};
60 use issues::{BadIssueSeeker, Issue};
62 use utils::use_colored_tty;
63 use visitor::{FmtVisitor, SnippetProvider};
65 pub use config::options::CliOptions;
66 pub use config::summary::Summary;
67 pub use config::{file_lines, load_config, Config, Verbosity, WriteMode};
69 pub type FmtResult<T> = std::result::Result<T, failure::Error>;
71 pub const WRITE_MODE_LIST: &str = "[replace|overwrite|display|plain|diff|coverage|checkstyle]";
78 pub(crate) mod checkstyle;
80 pub(crate) mod codemap;
82 pub(crate) mod config;
84 pub(crate) mod filemap;
92 pub(crate) mod modules;
97 pub(crate) mod rustfmt_diff;
105 pub(crate) mod visitor;
107 const STDIN: &str = "<stdin>";
109 // A map of the files of a crate, with their new content
110 pub(crate) type FileMap = Vec<FileRecord>;
112 pub(crate) type FileRecord = (FileName, String);
114 #[derive(Fail, Debug, Clone, Copy)]
116 // Line has exceeded character limit (found, maximum)
118 display = "line formatted, but exceeded maximum width \
119 (maximum: {} (see `max_width` option), found: {})",
123 LineOverflow(usize, usize),
124 // Line ends in whitespace
125 #[fail(display = "left behind trailing whitespace")]
127 // TODO or FIXME item without an issue number
128 #[fail(display = "found {}", _0)]
130 // License check has failed
131 #[fail(display = "license check failed")]
135 // Formatting errors that are identified *after* rustfmt has run.
136 struct FormattingError {
144 impl FormattingError {
145 fn msg_prefix(&self) -> &str {
147 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
148 ErrorKind::LicenseCheck => "error:",
149 ErrorKind::BadIssue(_) => "warning:",
153 fn msg_suffix(&self) -> &str {
154 if self.is_comment || self.is_string {
155 "set `error_on_unformatted = false` to suppress \
156 the warning against comments or string literals\n"
163 fn format_len(&self) -> (usize, usize) {
165 ErrorKind::LineOverflow(found, max) => (max, found - max),
166 ErrorKind::TrailingWhitespace => {
167 let trailing_ws_start = self
169 .rfind(|c: char| !c.is_whitespace())
174 self.line_buffer.len() - trailing_ws_start,
182 pub struct FormatReport {
183 // Maps stringified file paths to their associated formatting errors.
184 file_error_map: HashMap<FileName, Vec<FormattingError>>,
188 fn new() -> FormatReport {
190 file_error_map: HashMap::new(),
194 fn warning_count(&self) -> usize {
197 .map(|(_, errors)| errors.len())
201 fn has_warnings(&self) -> bool {
202 self.warning_count() > 0
205 fn print_warnings_fancy(
207 mut t: Box<term::Terminal<Output = io::Stderr>>,
208 ) -> Result<(), term::Error> {
209 for (file, errors) in &self.file_error_map {
210 for error in errors {
211 let prefix_space_len = error.line.to_string().len();
212 let prefix_spaces = " ".repeat(1 + prefix_space_len);
214 // First line: the overview of error
215 t.fg(term::color::RED)?;
216 t.attr(term::Attr::Bold)?;
217 write!(t, "{} ", error.msg_prefix())?;
219 t.attr(term::Attr::Bold)?;
220 writeln!(t, "{}", error.kind)?;
222 // Second line: file info
223 write!(t, "{}--> ", &prefix_spaces[1..])?;
225 writeln!(t, "{}:{}", file, error.line)?;
227 // Third to fifth lines: show the line which triggered error, if available.
228 if !error.line_buffer.is_empty() {
229 let (space_len, target_len) = error.format_len();
230 t.attr(term::Attr::Bold)?;
231 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
233 writeln!(t, "{}", error.line_buffer)?;
234 t.attr(term::Attr::Bold)?;
235 write!(t, "{}| ", prefix_spaces)?;
236 t.fg(term::color::RED)?;
237 writeln!(t, "{}", target_str(space_len, target_len))?;
241 // The last line: show note if available.
242 let msg_suffix = error.msg_suffix();
243 if !msg_suffix.is_empty() {
244 t.attr(term::Attr::Bold)?;
245 write!(t, "{}= note: ", prefix_spaces)?;
247 writeln!(t, "{}", error.msg_suffix())?;
255 if !self.file_error_map.is_empty() {
256 t.attr(term::Attr::Bold)?;
257 write!(t, "warning: ")?;
261 "rustfmt may have failed to format. See previous {} errors.\n\n",
262 self.warning_count(),
270 fn target_str(space_len: usize, target_len: usize) -> String {
271 let empty_line = " ".repeat(space_len);
272 let overflowed = "^".repeat(target_len);
273 empty_line + &overflowed
276 impl fmt::Display for FormatReport {
277 // Prints all the formatting errors.
278 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
279 for (file, errors) in &self.file_error_map {
280 for error in errors {
281 let prefix_space_len = error.line.to_string().len();
282 let prefix_spaces = " ".repeat(1 + prefix_space_len);
284 let error_line_buffer = if error.line_buffer.is_empty() {
287 let (space_len, target_len) = error.format_len();
289 "{}|\n{} | {}\n{}| {}",
294 target_str(space_len, target_len)
298 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
299 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
300 let msg_suffix = error.msg_suffix();
301 let note = if msg_suffix.is_empty() {
304 format!("{}note= ", prefix_spaces)
318 if !self.file_error_map.is_empty() {
321 "warning: rustfmt may have failed to format. See previous {} errors.",
322 self.warning_count(),
329 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
333 if config.verbose() == Verbosity::Verbose && path.to_string() != STDIN {
338 // Formatting which depends on the AST.
341 parse_session: &mut ParseSess,
342 main_file: &FileName,
345 ) -> Result<(FileMap, bool), io::Error>
347 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
349 let mut result = FileMap::new();
350 // diff mode: check if any files are differing
351 let mut has_diff = false;
353 let skip_children = config.skip_children();
354 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
355 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
358 should_emit_verbose(&path, config, || println!("Formatting {}", path));
359 let filemap = parse_session
361 .lookup_char_pos(module.inner.lo())
363 let big_snippet = filemap.src.as_ref().unwrap();
364 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
365 let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
366 // Format inner attributes if available.
367 if !krate.attrs.is_empty() && path == *main_file {
368 visitor.skip_empty_lines(filemap.end_pos);
369 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
370 visitor.push_rewrite(module.inner, None);
372 visitor.format_separate_mod(module, &*filemap);
375 visitor.last_pos = filemap.start_pos;
376 visitor.skip_empty_lines(filemap.end_pos);
377 visitor.format_separate_mod(module, &*filemap);
382 ::utils::count_newlines(&visitor.buffer)
385 let filename = path.clone();
386 has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
387 Ok(result) => result,
389 // Create a new error with path_str to help users see which files failed
390 let err_msg = format!("{}: {}", path, e);
391 return Err(io::Error::new(e.kind(), err_msg));
395 result.push((filename, visitor.buffer));
398 Ok((result, has_diff))
401 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
402 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
405 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
408 fn should_report_error(
410 char_kind: FullCodeCharKind,
412 error_kind: ErrorKind,
414 let allow_error_report = if char_kind.is_comment() || is_string {
415 config.error_on_unformatted()
421 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
422 ErrorKind::TrailingWhitespace => allow_error_report,
427 // Formatting done on a char by char or line by line basis.
428 // FIXME(#20) other stuff for parity with make tidy
432 skipped_range: &[(usize, usize)],
434 report: &mut FormatReport,
436 let mut trims = vec![];
437 let mut last_wspace: Option<usize> = None;
438 let mut line_len = 0;
439 let mut cur_line = 1;
440 let mut newline_count = 0;
441 let mut errors = vec![];
442 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
443 let mut line_buffer = String::with_capacity(config.max_width() * 2);
444 let mut is_string = false; // true if the current line contains a string literal.
445 let mut format_line = config.file_lines().contains_line(name, cur_line);
446 let allow_issue_seek = !issue_seeker.is_disabled();
449 if let Some(ref license_template) = config.license_template {
450 if !license_template.is_match(text) {
451 errors.push(FormattingError {
453 kind: ErrorKind::LicenseCheck,
456 line_buffer: String::new(),
461 // Iterate over the chars in the file map.
462 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
467 if allow_issue_seek && format_line {
468 // Add warnings for bad todos/ fixmes
469 if let Some(issue) = issue_seeker.inspect(c) {
470 errors.push(FormattingError {
472 kind: ErrorKind::BadIssue(issue),
475 line_buffer: String::new(),
482 // Check for (and record) trailing whitespace.
483 if let Some(..) = last_wspace {
484 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
485 trims.push((cur_line, kind, line_buffer.clone()));
490 // Check for any line width errors we couldn't correct.
491 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
492 if line_len > config.max_width()
493 && !is_skipped_line(cur_line, skipped_range)
494 && should_report_error(config, kind, is_string, error_kind)
496 errors.push(FormattingError {
499 is_comment: kind.is_comment(),
501 line_buffer: line_buffer.clone(),
508 format_line = config.file_lines().contains_line(name, cur_line);
515 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
516 if c.is_whitespace() {
517 if last_wspace.is_none() {
518 last_wspace = Some(b);
524 if kind.is_string() {
530 if newline_count > 1 {
531 debug!("track truncate: {} {}", text.len(), newline_count);
532 let line = text.len() - newline_count + 1;
536 for &(l, kind, ref b) in &trims {
537 if !is_skipped_line(l, skipped_range) {
538 errors.push(FormattingError {
540 kind: ErrorKind::TrailingWhitespace,
541 is_comment: kind.is_comment(),
542 is_string: kind.is_string(),
543 line_buffer: b.clone(),
548 report.file_error_map.insert(name.clone(), errors);
551 fn parse_input<'sess>(
553 parse_session: &'sess ParseSess,
555 ) -> Result<ast::Crate, ParseError<'sess>> {
556 let mut parser = match input {
557 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
558 Input::Text(text) => parse::new_parser_from_source_str(
560 FileName::Custom("stdin".to_owned()),
565 parser.cfg_mods = false;
566 if config.skip_children() {
567 parser.recurse_into_file_modules = false;
570 let mut parser = AssertUnwindSafe(parser);
571 let result = catch_unwind(move || parser.0.parse_crate_mod());
575 if parse_session.span_diagnostic.has_errors() {
576 // Bail out if the parser recovered from an error.
577 Err(ParseError::Recovered)
582 Ok(Err(e)) => Err(ParseError::Error(e)),
583 Err(_) => Err(ParseError::Panic),
587 /// All the ways that parsing can fail.
588 enum ParseError<'sess> {
589 /// There was an error, but the parser recovered.
591 /// There was an error (supplied) and parsing failed.
592 Error(DiagnosticBuilder<'sess>),
593 /// The parser panicked.
597 /// Format the given snippet. The snippet is expected to be *complete* code.
598 /// When we cannot parse the given snippet, this function returns `None`.
599 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
600 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
601 let input = Input::Text(snippet.into());
602 let mut config = config.clone();
603 config.set().write_mode(config::WriteMode::Display);
604 config.set().verbose(Verbosity::Quiet);
605 config.set().hide_parse_errors(true);
606 match format_input(input, &config, Some(&mut out)) {
607 // `format_input()` returns an empty string on parsing error.
608 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
609 Ok(..) => String::from_utf8(out).ok(),
614 const FN_MAIN_PREFIX: &str = "fn main() {\n";
616 fn enclose_in_main_block(s: &str, config: &Config) -> String {
617 let indent = Indent::from_width(config, config.tab_spaces());
618 let mut result = String::with_capacity(s.len() * 2);
619 result.push_str(FN_MAIN_PREFIX);
620 let mut need_indent = true;
621 for (kind, line) in LineClasses::new(s) {
623 result.push_str(&indent.to_string(config));
625 result.push_str(&line);
627 need_indent = !kind.is_string() || line.ends_with('\\');
633 /// Format the given code block. Mainly targeted for code block in comment.
634 /// The code block may be incomplete (i.e. parser may be unable to parse it).
635 /// To avoid panic in parser, we wrap the code block with a dummy function.
636 /// The returned code block does *not* end with newline.
637 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
638 // Wrap the given code block with `fn main()` if it does not have one.
639 let snippet = enclose_in_main_block(code_snippet, config);
640 let mut result = String::with_capacity(snippet.len());
641 let mut is_first = true;
643 // Trim "fn main() {" on the first line and "}" on the last line,
644 // then unindent the whole code block.
645 let formatted = format_snippet(&snippet, config)?;
647 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
648 let mut is_indented = true;
649 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
655 let trimmed_line = if !is_indented {
657 } else if line.len() > config.max_width() {
658 // If there are lines that are larger than max width, we cannot tell
659 // whether we have succeeded but have some comments or strings that
660 // are too long, or we have failed to format code block. We will be
661 // conservative and just return `None` in this case.
663 } else if line.len() > config.tab_spaces() {
664 // Make sure that the line has leading whitespaces.
665 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
666 if line.starts_with(indent_str.as_ref()) {
667 let offset = if config.hard_tabs() {
679 result.push_str(trimmed_line);
680 is_indented = !kind.is_string() || line.ends_with('\\');
685 pub fn format_input<T: Write>(
689 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
690 syntax::with_globals(|| format_input_inner(input, config, out))
693 fn format_input_inner<T: Write>(
696 mut out: Option<&mut T>,
697 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
698 let mut summary = Summary::default();
699 if config.disable_all_formatting() {
700 // When the input is from stdin, echo back the input.
701 if let Input::Text(ref buf) = input {
702 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
703 return Err((e, summary));
706 return Ok((summary, FileMap::new(), FormatReport::new()));
708 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
710 let tty_handler = if config.hide_parse_errors() {
711 let silent_emitter = Box::new(EmitterWriter::new(
712 Box::new(Vec::new()),
713 Some(codemap.clone()),
717 Handler::with_emitter(true, false, silent_emitter)
719 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
720 let color_cfg = if supports_color {
725 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
727 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
729 let main_file = match input {
730 Input::File(ref file) => FileName::Real(file.clone()),
731 Input::Text(..) => FileName::Custom("stdin".to_owned()),
734 let krate = match parse_input(input, &parse_session, config) {
738 ParseError::Error(mut diagnostic) => diagnostic.emit(),
739 ParseError::Panic => {
740 // Note that if you see this message and want more information,
741 // then go to `parse_input` and run the parse function without
742 // `catch_unwind` so rustfmt panics and you can get a backtrace.
743 should_emit_verbose(&main_file, config, || {
744 println!("The Rust parser panicked")
747 ParseError::Recovered => {}
749 summary.add_parsing_error();
750 return Ok((summary, FileMap::new(), FormatReport::new()));
754 summary.mark_parse_time();
756 // Suppress error output after parsing.
757 let silent_emitter = Box::new(EmitterWriter::new(
758 Box::new(Vec::new()),
759 Some(codemap.clone()),
763 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
765 let mut report = FormatReport::new();
767 let format_result = format_ast(
772 |file_name, file, skipped_range| {
773 // For some reason, the codemap does not include terminating
774 // newlines so we must add one on for each file. This is sad.
775 filemap::append_newline(file);
777 format_lines(file, file_name, skipped_range, config, &mut report);
779 if let Some(ref mut out) = out {
780 return filemap::write_file(file, file_name, out, config);
786 summary.mark_format_time();
788 should_emit_verbose(&main_file, config, || {
789 fn duration_to_f32(d: Duration) -> f32 {
790 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
794 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
795 duration_to_f32(summary.get_parse_time().unwrap()),
796 duration_to_f32(summary.get_format_time().unwrap()),
800 match format_result {
801 Ok((file_map, has_diff)) => {
802 if report.has_warnings() {
803 summary.add_formatting_error();
810 Ok((summary, file_map, report))
812 Err(e) => Err((e, summary)),
816 /// A single span of changed lines, with 0 or more removed lines
817 /// and a vector of 0 or more inserted lines.
818 #[derive(Debug, PartialEq, Eq)]
819 struct ModifiedChunk {
820 /// The first to be removed from the original text
821 pub line_number_orig: u32,
822 /// The number of lines which have been replaced
823 pub lines_removed: u32,
825 pub lines: Vec<String>,
828 /// Set of changed sections of a file.
829 #[derive(Debug, PartialEq, Eq)]
830 struct ModifiedLines {
831 /// The set of changed chunks.
832 pub chunks: Vec<ModifiedChunk>,
835 /// The successful result of formatting via `get_modified_lines()`.
837 struct ModifiedLinesResult {
838 /// The high level summary details
839 pub summary: Summary,
840 /// The result Filemap
841 pub filemap: FileMap,
842 /// Map of formatting errors
843 pub report: FormatReport,
844 /// The sets of updated lines.
845 pub modified_lines: ModifiedLines,
848 /// Format a file and return a `ModifiedLines` data structure describing
849 /// the changed ranges of lines.
851 fn get_modified_lines(
854 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
855 use std::io::BufRead;
857 let mut data = Vec::new();
859 let mut config = config.clone();
860 config.set().write_mode(config::WriteMode::Modified);
861 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
863 let mut lines = data.lines();
864 let mut chunks = Vec::new();
865 while let Some(Ok(header)) = lines.next() {
866 // Parse the header line
867 let values: Vec<_> = header
869 .map(|s| s.parse::<u32>().unwrap())
871 assert_eq!(values.len(), 3);
872 let line_number_orig = values[0];
873 let lines_removed = values[1];
874 let num_added = values[2];
875 let mut added_lines = Vec::new();
876 for _ in 0..num_added {
877 added_lines.push(lines.next().unwrap().unwrap());
879 chunks.push(ModifiedChunk {
885 Ok(ModifiedLinesResult {
889 modified_lines: ModifiedLines { chunks },
899 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
900 if !config.version_meets_requirement() {
901 return Err(format_err!("Version mismatch"));
903 let out = &mut stdout();
904 match format_input(input, config, Some(out)) {
905 Ok((summary, _, report)) => {
906 if report.has_warnings() {
907 match term::stderr() {
909 if use_colored_tty(config.color())
910 && t.supports_color()
911 && t.supports_attr(term::Attr::Bold) =>
913 match report.print_warnings_fancy(term::stderr().unwrap()) {
915 Err(..) => panic!("Unable to write to stderr: {}", report),
918 _ => eprintln!("{}", report),
924 Err((msg, mut summary)) => {
925 eprintln!("Error writing files: {}", msg);
926 summary.add_operational_error();
932 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
933 if config.write_mode() == WriteMode::Checkstyle {
934 let mut out = &mut stdout();
935 checkstyle::output_header(&mut out)?;
940 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
941 if config.write_mode() == WriteMode::Checkstyle {
942 let mut out = &mut stdout();
943 checkstyle::output_footer(&mut out)?;
950 use super::{format_code_block, format_snippet, Config};
953 fn test_no_panic_on_format_snippet_and_format_code_block() {
954 // `format_snippet()` and `format_code_block()` should not panic
955 // even when we cannot parse the given snippet.
957 assert!(format_snippet(snippet, &Config::default()).is_none());
958 assert!(format_code_block(snippet, &Config::default()).is_none());
961 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
963 F: Fn(&str, &Config) -> Option<String>,
965 let output = formatter(input, &Config::default());
966 output.is_some() && output.unwrap() == expected
970 fn test_format_snippet() {
971 let snippet = "fn main() { println!(\"hello, world\"); }";
972 let expected = "fn main() {\n \
973 println!(\"hello, world\");\n\
975 assert!(test_format_inner(format_snippet, snippet, expected));
979 fn test_format_code_block_fail() {
981 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
982 assert!(format_code_block(code_block, &Config::default()).is_none());
986 fn test_format_code_block() {
988 let code_block = "let x=3;";
989 let expected = "let x = 3;";
990 assert!(test_format_inner(format_code_block, code_block, expected));
992 // more complex code block, taken from chains.rs.
994 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
996 chain_indent(context, shape.add_offset(parent_rewrite.len())),
997 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
999 } else if is_block_expr(context, &parent, &parent_rewrite) {
1000 match context.config.indent_style() {
1001 // Try to put the first child on the same line with parent's last line
1002 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1003 // The parent is a block, so align the rest of the chain with the closing
1005 IndentStyle::Visual => (parent_shape, false),
1009 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1015 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1017 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1018 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1020 } else if is_block_expr(context, &parent, &parent_rewrite) {
1021 match context.config.indent_style() {
1022 // Try to put the first child on the same line with parent's last line
1023 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1024 // The parent is a block, so align the rest of the chain with the closing
1026 IndentStyle::Visual => (parent_shape, false),
1030 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1034 assert!(test_format_inner(format_code_block, code_block, expected));