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, 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 (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.line_buffer
168 .rfind(|c: char| !c.is_whitespace())
173 self.line_buffer.len() - trailing_ws_start,
181 pub struct FormatReport {
182 // Maps stringified file paths to their associated formatting errors.
183 file_error_map: HashMap<FileName, Vec<FormattingError>>,
187 fn new() -> FormatReport {
189 file_error_map: HashMap::new(),
193 fn warning_count(&self) -> usize {
196 .map(|(_, errors)| errors.len())
200 fn has_warnings(&self) -> bool {
201 self.warning_count() > 0
204 fn print_warnings_fancy(
206 mut t: Box<term::Terminal<Output = io::Stderr>>,
207 ) -> Result<(), term::Error> {
208 for (file, errors) in &self.file_error_map {
209 for error in errors {
210 let prefix_space_len = error.line.to_string().len();
211 let prefix_spaces = " ".repeat(1 + prefix_space_len);
213 // First line: the overview of error
214 t.fg(term::color::RED)?;
215 t.attr(term::Attr::Bold)?;
216 write!(t, "{} ", error.msg_prefix())?;
218 t.attr(term::Attr::Bold)?;
219 writeln!(t, "{}", error.kind)?;
221 // Second line: file info
222 write!(t, "{}--> ", &prefix_spaces[1..])?;
224 writeln!(t, "{}:{}", file, error.line)?;
226 // Third to fifth lines: show the line which triggered error, if available.
227 if !error.line_buffer.is_empty() {
228 let (space_len, target_len) = error.format_len();
229 t.attr(term::Attr::Bold)?;
230 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
232 writeln!(t, "{}", error.line_buffer)?;
233 t.attr(term::Attr::Bold)?;
234 write!(t, "{}| ", prefix_spaces)?;
235 t.fg(term::color::RED)?;
236 writeln!(t, "{}", target_str(space_len, target_len))?;
240 // The last line: show note if available.
241 let msg_suffix = error.msg_suffix();
242 if !msg_suffix.is_empty() {
243 t.attr(term::Attr::Bold)?;
244 write!(t, "{}= note: ", prefix_spaces)?;
246 writeln!(t, "{}", error.msg_suffix())?;
254 if !self.file_error_map.is_empty() {
255 t.attr(term::Attr::Bold)?;
256 write!(t, "warning: ")?;
260 "rustfmt may have failed to format. See previous {} errors.\n\n",
261 self.warning_count(),
269 fn target_str(space_len: usize, target_len: usize) -> String {
270 let empty_line = " ".repeat(space_len);
271 let overflowed = "^".repeat(target_len);
272 empty_line + &overflowed
275 impl fmt::Display for FormatReport {
276 // Prints all the formatting errors.
277 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
278 for (file, errors) in &self.file_error_map {
279 for error in errors {
280 let prefix_space_len = error.line.to_string().len();
281 let prefix_spaces = " ".repeat(1 + prefix_space_len);
283 let error_line_buffer = if error.line_buffer.is_empty() {
286 let (space_len, target_len) = error.format_len();
288 "{}|\n{} | {}\n{}| {}",
293 target_str(space_len, target_len)
297 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
298 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
299 let msg_suffix = error.msg_suffix();
300 let note = if msg_suffix.is_empty() {
303 format!("{}note= ", prefix_spaces)
317 if !self.file_error_map.is_empty() {
320 "warning: rustfmt may have failed to format. See previous {} errors.",
321 self.warning_count(),
328 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
332 if config.verbose() && path.to_string() != STDIN {
337 // Formatting which depends on the AST.
340 parse_session: &mut ParseSess,
341 main_file: &FileName,
344 ) -> Result<(FileMap, bool), io::Error>
346 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
348 let mut result = FileMap::new();
349 // diff mode: check if any files are differing
350 let mut has_diff = false;
352 // We always skip children for the "Plain" write mode, since there is
353 // nothing to distinguish the nested module contents.
354 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
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() && !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::Plain);
604 config.set().hide_parse_errors(true);
605 match format_input(input, &config, Some(&mut out)) {
606 // `format_input()` returns an empty string on parsing error.
607 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
608 Ok(..) => String::from_utf8(out).ok(),
613 const FN_MAIN_PREFIX: &str = "fn main() {\n";
615 fn enclose_in_main_block(s: &str, config: &Config) -> String {
616 let indent = Indent::from_width(config, config.tab_spaces());
617 let mut result = String::with_capacity(s.len() * 2);
618 result.push_str(FN_MAIN_PREFIX);
619 let mut need_indent = true;
620 for (kind, line) in LineClasses::new(s) {
622 result.push_str(&indent.to_string(config));
624 result.push_str(&line);
626 need_indent = !kind.is_string() || line.ends_with('\\');
632 /// Format the given code block. Mainly targeted for code block in comment.
633 /// The code block may be incomplete (i.e. parser may be unable to parse it).
634 /// To avoid panic in parser, we wrap the code block with a dummy function.
635 /// The returned code block does *not* end with newline.
636 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
637 // Wrap the given code block with `fn main()` if it does not have one.
638 let snippet = enclose_in_main_block(code_snippet, config);
639 let mut result = String::with_capacity(snippet.len());
640 let mut is_first = true;
642 // Trim "fn main() {" on the first line and "}" on the last line,
643 // then unindent the whole code block.
644 let formatted = format_snippet(&snippet, config)?;
646 let block_len = formatted.len().checked_sub(2).unwrap_or(0);
647 let mut is_indented = true;
648 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
654 let trimmed_line = if !is_indented {
656 } else if line.len() > config.max_width() {
657 // If there are lines that are larger than max width, we cannot tell
658 // whether we have succeeded but have some comments or strings that
659 // are too long, or we have failed to format code block. We will be
660 // conservative and just return `None` in this case.
662 } else if line.len() > config.tab_spaces() {
663 // Make sure that the line has leading whitespaces.
664 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
665 if line.starts_with(indent_str.as_ref()) {
666 let offset = if config.hard_tabs() {
678 result.push_str(trimmed_line);
679 is_indented = !kind.is_string() || line.ends_with('\\');
684 pub fn format_input<T: Write>(
688 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
689 syntax::with_globals(|| format_input_inner(input, config, out))
692 fn format_input_inner<T: Write>(
695 mut out: Option<&mut T>,
696 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
697 let mut summary = Summary::default();
698 if config.disable_all_formatting() {
699 // When the input is from stdin, echo back the input.
700 if let Input::Text(ref buf) = input {
701 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
702 return Err((e, summary));
705 return Ok((summary, FileMap::new(), FormatReport::new()));
707 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
709 let tty_handler = if config.hide_parse_errors() {
710 let silent_emitter = Box::new(EmitterWriter::new(
711 Box::new(Vec::new()),
712 Some(codemap.clone()),
716 Handler::with_emitter(true, false, silent_emitter)
718 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
719 let color_cfg = if supports_color {
724 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
726 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
728 let main_file = match input {
729 Input::File(ref file) => FileName::Real(file.clone()),
730 Input::Text(..) => FileName::Custom("stdin".to_owned()),
733 let krate = match parse_input(input, &parse_session, config) {
737 ParseError::Error(mut diagnostic) => diagnostic.emit(),
738 ParseError::Panic => {
739 // Note that if you see this message and want more information,
740 // then go to `parse_input` and run the parse function without
741 // `catch_unwind` so rustfmt panics and you can get a backtrace.
742 should_emit_verbose(&main_file, config, || {
743 println!("The Rust parser panicked")
746 ParseError::Recovered => {}
748 summary.add_parsing_error();
749 return Ok((summary, FileMap::new(), FormatReport::new()));
753 summary.mark_parse_time();
755 // Suppress error output after parsing.
756 let silent_emitter = Box::new(EmitterWriter::new(
757 Box::new(Vec::new()),
758 Some(codemap.clone()),
762 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
764 let mut report = FormatReport::new();
766 let format_result = format_ast(
771 |file_name, file, skipped_range| {
772 // For some reason, the codemap does not include terminating
773 // newlines so we must add one on for each file. This is sad.
774 filemap::append_newline(file);
776 format_lines(file, file_name, skipped_range, config, &mut report);
778 if let Some(ref mut out) = out {
779 return filemap::write_file(file, file_name, out, config);
785 summary.mark_format_time();
787 should_emit_verbose(&main_file, config, || {
788 fn duration_to_f32(d: Duration) -> f32 {
789 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
793 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
794 duration_to_f32(summary.get_parse_time().unwrap()),
795 duration_to_f32(summary.get_format_time().unwrap()),
799 match format_result {
800 Ok((file_map, has_diff)) => {
801 if report.has_warnings() {
802 summary.add_formatting_error();
809 Ok((summary, file_map, report))
811 Err(e) => Err((e, summary)),
815 /// A single span of changed lines, with 0 or more removed lines
816 /// and a vector of 0 or more inserted lines.
817 #[derive(Debug, PartialEq, Eq)]
818 struct ModifiedChunk {
819 /// The first to be removed from the original text
820 pub line_number_orig: u32,
821 /// The number of lines which have been replaced
822 pub lines_removed: u32,
824 pub lines: Vec<String>,
827 /// Set of changed sections of a file.
828 #[derive(Debug, PartialEq, Eq)]
829 struct ModifiedLines {
830 /// The set of changed chunks.
831 pub chunks: Vec<ModifiedChunk>,
834 /// The successful result of formatting via `get_modified_lines()`.
836 struct ModifiedLinesResult {
837 /// The high level summary details
838 pub summary: Summary,
839 /// The result Filemap
840 pub filemap: FileMap,
841 /// Map of formatting errors
842 pub report: FormatReport,
843 /// The sets of updated lines.
844 pub modified_lines: ModifiedLines,
847 /// Format a file and return a `ModifiedLines` data structure describing
848 /// the changed ranges of lines.
850 fn get_modified_lines(
853 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
854 use std::io::BufRead;
856 let mut data = Vec::new();
858 let mut config = config.clone();
859 config.set().write_mode(config::WriteMode::Modified);
860 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
862 let mut lines = data.lines();
863 let mut chunks = Vec::new();
864 while let Some(Ok(header)) = lines.next() {
865 // Parse the header line
866 let values: Vec<_> = header
868 .map(|s| s.parse::<u32>().unwrap())
870 assert_eq!(values.len(), 3);
871 let line_number_orig = values[0];
872 let lines_removed = values[1];
873 let num_added = values[2];
874 let mut added_lines = Vec::new();
875 for _ in 0..num_added {
876 added_lines.push(lines.next().unwrap().unwrap());
878 chunks.push(ModifiedChunk {
884 Ok(ModifiedLinesResult {
888 modified_lines: ModifiedLines { chunks },
898 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
899 if !config.version_meets_requirement() {
900 return Err(format_err!("Version mismatch"));
902 let out = &mut stdout();
903 match format_input(input, config, Some(out)) {
904 Ok((summary, _, report)) => {
905 if report.has_warnings() {
906 match term::stderr() {
908 if use_colored_tty(config.color()) && t.supports_color()
909 && t.supports_attr(term::Attr::Bold) =>
911 match report.print_warnings_fancy(term::stderr().unwrap()) {
913 Err(..) => panic!("Unable to write to stderr: {}", report),
916 _ => eprintln!("{}", report),
922 Err((msg, mut summary)) => {
923 eprintln!("Error writing files: {}", msg);
924 summary.add_operational_error();
930 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
931 if config.write_mode() == WriteMode::Checkstyle {
932 let mut out = &mut stdout();
933 checkstyle::output_header(&mut out)?;
938 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
939 if config.write_mode() == WriteMode::Checkstyle {
940 let mut out = &mut stdout();
941 checkstyle::output_footer(&mut out)?;
948 use super::{format_code_block, format_snippet, Config};
951 fn test_no_panic_on_format_snippet_and_format_code_block() {
952 // `format_snippet()` and `format_code_block()` should not panic
953 // even when we cannot parse the given snippet.
955 assert!(format_snippet(snippet, &Config::default()).is_none());
956 assert!(format_code_block(snippet, &Config::default()).is_none());
959 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
961 F: Fn(&str, &Config) -> Option<String>,
963 let output = formatter(input, &Config::default());
964 output.is_some() && output.unwrap() == expected
968 fn test_format_snippet() {
969 let snippet = "fn main() { println!(\"hello, world\"); }";
970 let expected = "fn main() {\n \
971 println!(\"hello, world\");\n\
973 assert!(test_format_inner(format_snippet, snippet, expected));
977 fn test_format_code_block_fail() {
979 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
980 assert!(format_code_block(code_block, &Config::default()).is_none());
984 fn test_format_code_block() {
986 let code_block = "let x=3;";
987 let expected = "let x = 3;";
988 assert!(test_format_inner(format_code_block, code_block, expected));
990 // more complex code block, taken from chains.rs.
992 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
994 chain_indent(context, shape.add_offset(parent_rewrite.len())),
995 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
997 } else if is_block_expr(context, &parent, &parent_rewrite) {
998 match context.config.indent_style() {
999 // Try to put the first child on the same line with parent's last line
1000 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1001 // The parent is a block, so align the rest of the chain with the closing
1003 IndentStyle::Visual => (parent_shape, false),
1007 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1013 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1015 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1016 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1018 } else if is_block_expr(context, &parent, &parent_rewrite) {
1019 match context.config.indent_style() {
1020 // Try to put the first child on the same line with parent's last line
1021 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1022 // The parent is a block, so align the rest of the chain with the closing
1024 IndentStyle::Visual => (parent_shape, false),
1028 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1032 assert!(test_format_inner(format_code_block, code_block, expected));