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 =
72 "[replace|overwrite|display|plain|diff|coverage|checkstyle|check]";
79 pub(crate) mod checkstyle;
81 pub(crate) mod codemap;
83 pub(crate) mod config;
85 pub(crate) mod filemap;
93 pub(crate) mod modules;
98 pub(crate) mod rustfmt_diff;
106 pub(crate) mod visitor;
108 const STDIN: &str = "<stdin>";
110 // A map of the files of a crate, with their new content
111 pub(crate) type FileMap = Vec<FileRecord>;
113 pub(crate) type FileRecord = (FileName, String);
115 #[derive(Fail, Debug, Clone, Copy)]
117 // Line has exceeded character limit (found, maximum)
119 display = "line formatted, but exceeded maximum width \
120 (maximum: {} (see `max_width` option), found: {})",
124 LineOverflow(usize, usize),
125 // Line ends in whitespace
126 #[fail(display = "left behind trailing whitespace")]
128 // TODO or FIXME item without an issue number
129 #[fail(display = "found {}", _0)]
131 // License check has failed
132 #[fail(display = "license check failed")]
136 // Formatting errors that are identified *after* rustfmt has run.
137 struct FormattingError {
145 impl FormattingError {
146 fn msg_prefix(&self) -> &str {
148 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
149 ErrorKind::LicenseCheck => "error:",
150 ErrorKind::BadIssue(_) => "warning:",
154 fn msg_suffix(&self) -> &str {
155 if self.is_comment || self.is_string {
156 "set `error_on_unformatted = false` to suppress \
157 the warning against comments or string literals\n"
164 fn format_len(&self) -> (usize, usize) {
166 ErrorKind::LineOverflow(found, max) => (max, found - max),
167 ErrorKind::TrailingWhitespace => {
168 let trailing_ws_start = self
170 .rfind(|c: char| !c.is_whitespace())
175 self.line_buffer.len() - trailing_ws_start,
183 pub struct FormatReport {
184 // Maps stringified file paths to their associated formatting errors.
185 file_error_map: HashMap<FileName, Vec<FormattingError>>,
189 fn new() -> FormatReport {
191 file_error_map: HashMap::new(),
195 fn warning_count(&self) -> usize {
198 .map(|(_, errors)| errors.len())
202 fn has_warnings(&self) -> bool {
203 self.warning_count() > 0
206 fn print_warnings_fancy(
208 mut t: Box<term::Terminal<Output = io::Stderr>>,
209 ) -> Result<(), term::Error> {
210 for (file, errors) in &self.file_error_map {
211 for error in errors {
212 let prefix_space_len = error.line.to_string().len();
213 let prefix_spaces = " ".repeat(1 + prefix_space_len);
215 // First line: the overview of error
216 t.fg(term::color::RED)?;
217 t.attr(term::Attr::Bold)?;
218 write!(t, "{} ", error.msg_prefix())?;
220 t.attr(term::Attr::Bold)?;
221 writeln!(t, "{}", error.kind)?;
223 // Second line: file info
224 write!(t, "{}--> ", &prefix_spaces[1..])?;
226 writeln!(t, "{}:{}", file, error.line)?;
228 // Third to fifth lines: show the line which triggered error, if available.
229 if !error.line_buffer.is_empty() {
230 let (space_len, target_len) = error.format_len();
231 t.attr(term::Attr::Bold)?;
232 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
234 writeln!(t, "{}", error.line_buffer)?;
235 t.attr(term::Attr::Bold)?;
236 write!(t, "{}| ", prefix_spaces)?;
237 t.fg(term::color::RED)?;
238 writeln!(t, "{}", target_str(space_len, target_len))?;
242 // The last line: show note if available.
243 let msg_suffix = error.msg_suffix();
244 if !msg_suffix.is_empty() {
245 t.attr(term::Attr::Bold)?;
246 write!(t, "{}= note: ", prefix_spaces)?;
248 writeln!(t, "{}", error.msg_suffix())?;
256 if !self.file_error_map.is_empty() {
257 t.attr(term::Attr::Bold)?;
258 write!(t, "warning: ")?;
262 "rustfmt may have failed to format. See previous {} errors.\n\n",
263 self.warning_count(),
271 fn target_str(space_len: usize, target_len: usize) -> String {
272 let empty_line = " ".repeat(space_len);
273 let overflowed = "^".repeat(target_len);
274 empty_line + &overflowed
277 impl fmt::Display for FormatReport {
278 // Prints all the formatting errors.
279 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
280 for (file, errors) in &self.file_error_map {
281 for error in errors {
282 let prefix_space_len = error.line.to_string().len();
283 let prefix_spaces = " ".repeat(1 + prefix_space_len);
285 let error_line_buffer = if error.line_buffer.is_empty() {
288 let (space_len, target_len) = error.format_len();
290 "{}|\n{} | {}\n{}| {}",
295 target_str(space_len, target_len)
299 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
300 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
301 let msg_suffix = error.msg_suffix();
302 let note = if msg_suffix.is_empty() {
305 format!("{}note= ", prefix_spaces)
319 if !self.file_error_map.is_empty() {
322 "warning: rustfmt may have failed to format. See previous {} errors.",
323 self.warning_count(),
330 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
334 if config.verbose() == Verbosity::Verbose && path.to_string() != STDIN {
339 // Formatting which depends on the AST.
342 parse_session: &mut ParseSess,
343 main_file: &FileName,
346 ) -> Result<(FileMap, bool), io::Error>
348 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
350 let mut result = FileMap::new();
351 // diff mode: check if any files are differing
352 let mut has_diff = false;
354 let skip_children = config.skip_children();
355 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
356 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
359 should_emit_verbose(&path, config, || println!("Formatting {}", path));
360 let filemap = parse_session
362 .lookup_char_pos(module.inner.lo())
364 let big_snippet = filemap.src.as_ref().unwrap();
365 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
366 let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
367 // Format inner attributes if available.
368 if !krate.attrs.is_empty() && path == *main_file {
369 visitor.skip_empty_lines(filemap.end_pos);
370 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
371 visitor.push_rewrite(module.inner, None);
373 visitor.format_separate_mod(module, &*filemap);
376 visitor.last_pos = filemap.start_pos;
377 visitor.skip_empty_lines(filemap.end_pos);
378 visitor.format_separate_mod(module, &*filemap);
383 ::utils::count_newlines(&visitor.buffer)
386 let filename = path.clone();
387 has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
388 Ok(result) => result,
390 // Create a new error with path_str to help users see which files failed
391 let err_msg = format!("{}: {}", path, e);
392 return Err(io::Error::new(e.kind(), err_msg));
396 result.push((filename, visitor.buffer));
399 Ok((result, has_diff))
402 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
403 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
406 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
409 fn should_report_error(
411 char_kind: FullCodeCharKind,
413 error_kind: ErrorKind,
415 let allow_error_report = if char_kind.is_comment() || is_string {
416 config.error_on_unformatted()
422 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
423 ErrorKind::TrailingWhitespace => allow_error_report,
428 // Formatting done on a char by char or line by line basis.
429 // FIXME(#20) other stuff for parity with make tidy
433 skipped_range: &[(usize, usize)],
435 report: &mut FormatReport,
437 let mut trims = vec![];
438 let mut last_wspace: Option<usize> = None;
439 let mut line_len = 0;
440 let mut cur_line = 1;
441 let mut newline_count = 0;
442 let mut errors = vec![];
443 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
444 let mut line_buffer = String::with_capacity(config.max_width() * 2);
445 let mut is_string = false; // true if the current line contains a string literal.
446 let mut format_line = config.file_lines().contains_line(name, cur_line);
447 let allow_issue_seek = !issue_seeker.is_disabled();
450 if let Some(ref license_template) = config.license_template {
451 if !license_template.is_match(text) {
452 errors.push(FormattingError {
454 kind: ErrorKind::LicenseCheck,
457 line_buffer: String::new(),
462 // Iterate over the chars in the file map.
463 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
468 if allow_issue_seek && format_line {
469 // Add warnings for bad todos/ fixmes
470 if let Some(issue) = issue_seeker.inspect(c) {
471 errors.push(FormattingError {
473 kind: ErrorKind::BadIssue(issue),
476 line_buffer: String::new(),
483 // Check for (and record) trailing whitespace.
484 if let Some(..) = last_wspace {
485 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
486 trims.push((cur_line, kind, line_buffer.clone()));
491 // Check for any line width errors we couldn't correct.
492 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
493 if line_len > config.max_width()
494 && !is_skipped_line(cur_line, skipped_range)
495 && should_report_error(config, kind, is_string, error_kind)
497 errors.push(FormattingError {
500 is_comment: kind.is_comment(),
502 line_buffer: line_buffer.clone(),
509 format_line = config.file_lines().contains_line(name, cur_line);
516 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
517 if c.is_whitespace() {
518 if last_wspace.is_none() {
519 last_wspace = Some(b);
525 if kind.is_string() {
531 if newline_count > 1 {
532 debug!("track truncate: {} {}", text.len(), newline_count);
533 let line = text.len() - newline_count + 1;
537 for &(l, kind, ref b) in &trims {
538 if !is_skipped_line(l, skipped_range) {
539 errors.push(FormattingError {
541 kind: ErrorKind::TrailingWhitespace,
542 is_comment: kind.is_comment(),
543 is_string: kind.is_string(),
544 line_buffer: b.clone(),
549 report.file_error_map.insert(name.clone(), errors);
552 fn parse_input<'sess>(
554 parse_session: &'sess ParseSess,
556 ) -> Result<ast::Crate, ParseError<'sess>> {
557 let mut parser = match input {
558 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
559 Input::Text(text) => parse::new_parser_from_source_str(
561 FileName::Custom("stdin".to_owned()),
566 parser.cfg_mods = false;
567 if config.skip_children() {
568 parser.recurse_into_file_modules = false;
571 let mut parser = AssertUnwindSafe(parser);
572 let result = catch_unwind(move || parser.0.parse_crate_mod());
576 if parse_session.span_diagnostic.has_errors() {
577 // Bail out if the parser recovered from an error.
578 Err(ParseError::Recovered)
583 Ok(Err(e)) => Err(ParseError::Error(e)),
584 Err(_) => Err(ParseError::Panic),
588 /// All the ways that parsing can fail.
589 enum ParseError<'sess> {
590 /// There was an error, but the parser recovered.
592 /// There was an error (supplied) and parsing failed.
593 Error(DiagnosticBuilder<'sess>),
594 /// The parser panicked.
598 /// Format the given snippet. The snippet is expected to be *complete* code.
599 /// When we cannot parse the given snippet, this function returns `None`.
600 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
601 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
602 let input = Input::Text(snippet.into());
603 let mut config = config.clone();
604 config.set().write_mode(config::WriteMode::Display);
605 config.set().verbose(Verbosity::Quiet);
606 config.set().hide_parse_errors(true);
607 match format_input(input, &config, Some(&mut out)) {
608 // `format_input()` returns an empty string on parsing error.
609 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
610 Ok(..) => String::from_utf8(out).ok(),
615 const FN_MAIN_PREFIX: &str = "fn main() {\n";
617 fn enclose_in_main_block(s: &str, config: &Config) -> String {
618 let indent = Indent::from_width(config, config.tab_spaces());
619 let mut result = String::with_capacity(s.len() * 2);
620 result.push_str(FN_MAIN_PREFIX);
621 let mut need_indent = true;
622 for (kind, line) in LineClasses::new(s) {
624 result.push_str(&indent.to_string(config));
626 result.push_str(&line);
628 need_indent = !kind.is_string() || line.ends_with('\\');
634 /// Format the given code block. Mainly targeted for code block in comment.
635 /// The code block may be incomplete (i.e. parser may be unable to parse it).
636 /// To avoid panic in parser, we wrap the code block with a dummy function.
637 /// The returned code block does *not* end with newline.
638 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
639 // Wrap the given code block with `fn main()` if it does not have one.
640 let snippet = enclose_in_main_block(code_snippet, config);
641 let mut result = String::with_capacity(snippet.len());
642 let mut is_first = true;
644 // Trim "fn main() {" on the first line and "}" on the last line,
645 // then unindent the whole code block.
646 let formatted = format_snippet(&snippet, config)?;
648 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
649 let mut is_indented = true;
650 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
656 let trimmed_line = if !is_indented {
658 } else if line.len() > config.max_width() {
659 // If there are lines that are larger than max width, we cannot tell
660 // whether we have succeeded but have some comments or strings that
661 // are too long, or we have failed to format code block. We will be
662 // conservative and just return `None` in this case.
664 } else if line.len() > config.tab_spaces() {
665 // Make sure that the line has leading whitespaces.
666 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
667 if line.starts_with(indent_str.as_ref()) {
668 let offset = if config.hard_tabs() {
680 result.push_str(trimmed_line);
681 is_indented = !kind.is_string() || line.ends_with('\\');
686 pub fn format_input<T: Write>(
690 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
691 syntax::with_globals(|| format_input_inner(input, config, out))
694 fn format_input_inner<T: Write>(
697 mut out: Option<&mut T>,
698 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
699 let mut summary = Summary::default();
700 if config.disable_all_formatting() {
701 // When the input is from stdin, echo back the input.
702 if let Input::Text(ref buf) = input {
703 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
704 return Err((e, summary));
707 return Ok((summary, FileMap::new(), FormatReport::new()));
709 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
711 let tty_handler = if config.hide_parse_errors() {
712 let silent_emitter = Box::new(EmitterWriter::new(
713 Box::new(Vec::new()),
714 Some(codemap.clone()),
718 Handler::with_emitter(true, false, silent_emitter)
720 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
721 let color_cfg = if supports_color {
726 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
728 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
730 let main_file = match input {
731 Input::File(ref file) => FileName::Real(file.clone()),
732 Input::Text(..) => FileName::Custom("stdin".to_owned()),
735 let krate = match parse_input(input, &parse_session, config) {
739 ParseError::Error(mut diagnostic) => diagnostic.emit(),
740 ParseError::Panic => {
741 // Note that if you see this message and want more information,
742 // then go to `parse_input` and run the parse function without
743 // `catch_unwind` so rustfmt panics and you can get a backtrace.
744 should_emit_verbose(&main_file, config, || {
745 println!("The Rust parser panicked")
748 ParseError::Recovered => {}
750 summary.add_parsing_error();
751 return Ok((summary, FileMap::new(), FormatReport::new()));
755 summary.mark_parse_time();
757 // Suppress error output after parsing.
758 let silent_emitter = Box::new(EmitterWriter::new(
759 Box::new(Vec::new()),
760 Some(codemap.clone()),
764 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
766 let mut report = FormatReport::new();
768 let format_result = format_ast(
773 |file_name, file, skipped_range| {
774 // For some reason, the codemap does not include terminating
775 // newlines so we must add one on for each file. This is sad.
776 filemap::append_newline(file);
778 format_lines(file, file_name, skipped_range, config, &mut report);
780 if let Some(ref mut out) = out {
781 return filemap::write_file(file, file_name, out, config);
787 summary.mark_format_time();
789 should_emit_verbose(&main_file, config, || {
790 fn duration_to_f32(d: Duration) -> f32 {
791 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
795 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
796 duration_to_f32(summary.get_parse_time().unwrap()),
797 duration_to_f32(summary.get_format_time().unwrap()),
801 match format_result {
802 Ok((file_map, has_diff)) => {
803 if report.has_warnings() {
804 summary.add_formatting_error();
811 Ok((summary, file_map, report))
813 Err(e) => Err((e, summary)),
817 /// A single span of changed lines, with 0 or more removed lines
818 /// and a vector of 0 or more inserted lines.
819 #[derive(Debug, PartialEq, Eq)]
820 struct ModifiedChunk {
821 /// The first to be removed from the original text
822 pub line_number_orig: u32,
823 /// The number of lines which have been replaced
824 pub lines_removed: u32,
826 pub lines: Vec<String>,
829 /// Set of changed sections of a file.
830 #[derive(Debug, PartialEq, Eq)]
831 struct ModifiedLines {
832 /// The set of changed chunks.
833 pub chunks: Vec<ModifiedChunk>,
836 /// The successful result of formatting via `get_modified_lines()`.
838 struct ModifiedLinesResult {
839 /// The high level summary details
840 pub summary: Summary,
841 /// The result Filemap
842 pub filemap: FileMap,
843 /// Map of formatting errors
844 pub report: FormatReport,
845 /// The sets of updated lines.
846 pub modified_lines: ModifiedLines,
849 /// Format a file and return a `ModifiedLines` data structure describing
850 /// the changed ranges of lines.
852 fn get_modified_lines(
855 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
856 use std::io::BufRead;
858 let mut data = Vec::new();
860 let mut config = config.clone();
861 config.set().write_mode(config::WriteMode::Modified);
862 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
864 let mut lines = data.lines();
865 let mut chunks = Vec::new();
866 while let Some(Ok(header)) = lines.next() {
867 // Parse the header line
868 let values: Vec<_> = header
870 .map(|s| s.parse::<u32>().unwrap())
872 assert_eq!(values.len(), 3);
873 let line_number_orig = values[0];
874 let lines_removed = values[1];
875 let num_added = values[2];
876 let mut added_lines = Vec::new();
877 for _ in 0..num_added {
878 added_lines.push(lines.next().unwrap().unwrap());
880 chunks.push(ModifiedChunk {
886 Ok(ModifiedLinesResult {
890 modified_lines: ModifiedLines { chunks },
900 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
901 if !config.version_meets_requirement() {
902 return Err(format_err!("Version mismatch"));
904 let out = &mut stdout();
905 match format_input(input, config, Some(out)) {
906 Ok((summary, _, report)) => {
907 if report.has_warnings() {
908 match term::stderr() {
910 if use_colored_tty(config.color())
911 && t.supports_color()
912 && t.supports_attr(term::Attr::Bold) =>
914 match report.print_warnings_fancy(term::stderr().unwrap()) {
916 Err(..) => panic!("Unable to write to stderr: {}", report),
919 _ => eprintln!("{}", report),
925 Err((msg, mut summary)) => {
926 eprintln!("Error writing files: {}", msg);
927 summary.add_operational_error();
933 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
934 if config.write_mode() == WriteMode::Checkstyle {
935 let mut out = &mut stdout();
936 checkstyle::output_header(&mut out)?;
941 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
942 if config.write_mode() == WriteMode::Checkstyle {
943 let mut out = &mut stdout();
944 checkstyle::output_footer(&mut out)?;
951 use super::{format_code_block, format_snippet, Config};
954 fn test_no_panic_on_format_snippet_and_format_code_block() {
955 // `format_snippet()` and `format_code_block()` should not panic
956 // even when we cannot parse the given snippet.
958 assert!(format_snippet(snippet, &Config::default()).is_none());
959 assert!(format_code_block(snippet, &Config::default()).is_none());
962 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
964 F: Fn(&str, &Config) -> Option<String>,
966 let output = formatter(input, &Config::default());
967 output.is_some() && output.unwrap() == expected
971 fn test_format_snippet() {
972 let snippet = "fn main() { println!(\"hello, world\"); }";
973 let expected = "fn main() {\n \
974 println!(\"hello, world\");\n\
976 assert!(test_format_inner(format_snippet, snippet, expected));
980 fn test_format_code_block_fail() {
982 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
983 assert!(format_code_block(code_block, &Config::default()).is_none());
987 fn test_format_code_block() {
989 let code_block = "let x=3;";
990 let expected = "let x = 3;";
991 assert!(test_format_inner(format_code_block, code_block, expected));
993 // more complex code block, taken from chains.rs.
995 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
997 chain_indent(context, shape.add_offset(parent_rewrite.len())),
998 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1000 } else if is_block_expr(context, &parent, &parent_rewrite) {
1001 match context.config.indent_style() {
1002 // Try to put the first child on the same line with parent's last line
1003 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1004 // The parent is a block, so align the rest of the chain with the closing
1006 IndentStyle::Visual => (parent_shape, false),
1010 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1016 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1018 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1019 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1021 } else if is_block_expr(context, &parent, &parent_rewrite) {
1022 match context.config.indent_style() {
1023 // Try to put the first child on the same line with parent's last line
1024 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1025 // The parent is a block, so align the rest of the chain with the closing
1027 IndentStyle::Visual => (parent_shape, false),
1031 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1035 assert!(test_format_inner(format_code_block, code_block, expected));