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;
32 extern crate rustc_target;
35 extern crate serde_derive;
36 extern crate serde_json;
40 extern crate unicode_segmentation;
42 use std::collections::HashMap;
44 use std::io::{self, stdout, Write};
45 use std::panic::{catch_unwind, AssertUnwindSafe};
46 use std::path::PathBuf;
48 use std::time::Duration;
51 pub use syntax::codemap::FileName;
52 use syntax::codemap::{CodeMap, FilePathMapping};
53 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
54 use syntax::errors::{DiagnosticBuilder, Handler};
55 use syntax::parse::{self, ParseSess};
57 use comment::{CharClasses, FullCodeCharKind, LineClasses};
59 use issues::{BadIssueSeeker, Issue};
61 use utils::use_colored_tty;
62 use visitor::{FmtVisitor, SnippetProvider};
64 pub use config::options::CliOptions;
65 pub use config::summary::Summary;
66 pub use config::{file_lines, load_config, Config, WriteMode};
68 pub type FmtResult<T> = std::result::Result<T, failure::Error>;
70 pub const WRITE_MODE_LIST: &str =
71 "[replace|overwrite|display|plain|diff|coverage|checkstyle|check]";
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 (maximum: {} (see `max_width` option), found: {})",
122 LineOverflow(usize, usize),
123 // Line ends in whitespace
124 #[fail(display = "left behind trailing whitespace")]
126 // TODO or FIXME item without an issue number
127 #[fail(display = "found {}", _0)]
129 // License check has failed
130 #[fail(display = "license check failed")]
134 // Formatting errors that are identified *after* rustfmt has run.
135 struct FormattingError {
143 impl FormattingError {
144 fn msg_prefix(&self) -> &str {
146 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
147 ErrorKind::LicenseCheck => "error:",
148 ErrorKind::BadIssue(_) => "warning:",
152 fn msg_suffix(&self) -> &str {
153 if self.is_comment || self.is_string {
154 "set `error_on_unformatted = false` to suppress \
155 the warning against comments or string literals\n"
162 fn format_len(&self) -> (usize, usize) {
164 ErrorKind::LineOverflow(found, max) => (max, found - max),
165 ErrorKind::TrailingWhitespace => {
166 let trailing_ws_start = self.line_buffer
167 .rfind(|c: char| !c.is_whitespace())
172 self.line_buffer.len() - trailing_ws_start,
180 pub struct FormatReport {
181 // Maps stringified file paths to their associated formatting errors.
182 file_error_map: HashMap<FileName, Vec<FormattingError>>,
186 fn new() -> FormatReport {
188 file_error_map: HashMap::new(),
192 fn warning_count(&self) -> usize {
195 .map(|(_, errors)| errors.len())
199 fn has_warnings(&self) -> bool {
200 self.warning_count() > 0
203 fn print_warnings_fancy(
205 mut t: Box<term::Terminal<Output = io::Stderr>>,
206 ) -> Result<(), term::Error> {
207 for (file, errors) in &self.file_error_map {
208 for error in errors {
209 let prefix_space_len = error.line.to_string().len();
210 let prefix_spaces = " ".repeat(1 + prefix_space_len);
212 // First line: the overview of error
213 t.fg(term::color::RED)?;
214 t.attr(term::Attr::Bold)?;
215 write!(t, "{} ", error.msg_prefix())?;
217 t.attr(term::Attr::Bold)?;
218 writeln!(t, "{}", error.kind)?;
220 // Second line: file info
221 write!(t, "{}--> ", &prefix_spaces[1..])?;
223 writeln!(t, "{}:{}", file, error.line)?;
225 // Third to fifth lines: show the line which triggered error, if available.
226 if !error.line_buffer.is_empty() {
227 let (space_len, target_len) = error.format_len();
228 t.attr(term::Attr::Bold)?;
229 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
231 writeln!(t, "{}", error.line_buffer)?;
232 t.attr(term::Attr::Bold)?;
233 write!(t, "{}| ", prefix_spaces)?;
234 t.fg(term::color::RED)?;
235 writeln!(t, "{}", target_str(space_len, target_len))?;
239 // The last line: show note if available.
240 let msg_suffix = error.msg_suffix();
241 if !msg_suffix.is_empty() {
242 t.attr(term::Attr::Bold)?;
243 write!(t, "{}= note: ", prefix_spaces)?;
245 writeln!(t, "{}", error.msg_suffix())?;
253 if !self.file_error_map.is_empty() {
254 t.attr(term::Attr::Bold)?;
255 write!(t, "warning: ")?;
259 "rustfmt may have failed to format. See previous {} errors.\n\n",
260 self.warning_count(),
268 fn target_str(space_len: usize, target_len: usize) -> String {
269 let empty_line = " ".repeat(space_len);
270 let overflowed = "^".repeat(target_len);
271 empty_line + &overflowed
274 impl fmt::Display for FormatReport {
275 // Prints all the formatting errors.
276 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
277 for (file, errors) in &self.file_error_map {
278 for error in errors {
279 let prefix_space_len = error.line.to_string().len();
280 let prefix_spaces = " ".repeat(1 + prefix_space_len);
282 let error_line_buffer = if error.line_buffer.is_empty() {
285 let (space_len, target_len) = error.format_len();
287 "{}|\n{} | {}\n{}| {}",
292 target_str(space_len, target_len)
296 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
297 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
298 let msg_suffix = error.msg_suffix();
299 let note = if msg_suffix.is_empty() {
302 format!("{}note= ", prefix_spaces)
316 if !self.file_error_map.is_empty() {
319 "warning: rustfmt may have failed to format. See previous {} errors.",
320 self.warning_count(),
327 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
331 if config.verbose() && path.to_string() != STDIN {
336 // Formatting which depends on the AST.
339 parse_session: &mut ParseSess,
340 main_file: &FileName,
343 ) -> Result<(FileMap, bool), io::Error>
345 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
347 let mut result = FileMap::new();
348 // diff mode: check if any files are differing
349 let mut has_diff = false;
351 // We always skip children for the "Plain" write mode, since there is
352 // nothing to distinguish the nested module contents.
353 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
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() && !is_skipped_line(cur_line, skipped_range)
493 && should_report_error(config, kind, is_string, error_kind)
495 errors.push(FormattingError {
498 is_comment: kind.is_comment(),
500 line_buffer: line_buffer.clone(),
507 format_line = config.file_lines().contains_line(name, cur_line);
514 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
515 if c.is_whitespace() {
516 if last_wspace.is_none() {
517 last_wspace = Some(b);
523 if kind.is_string() {
529 if newline_count > 1 {
530 debug!("track truncate: {} {}", text.len(), newline_count);
531 let line = text.len() - newline_count + 1;
535 for &(l, kind, ref b) in &trims {
536 if !is_skipped_line(l, skipped_range) {
537 errors.push(FormattingError {
539 kind: ErrorKind::TrailingWhitespace,
540 is_comment: kind.is_comment(),
541 is_string: kind.is_string(),
542 line_buffer: b.clone(),
547 report.file_error_map.insert(name.clone(), errors);
550 fn parse_input<'sess>(
552 parse_session: &'sess ParseSess,
554 ) -> Result<ast::Crate, ParseError<'sess>> {
555 let mut parser = match input {
556 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
557 Input::Text(text) => parse::new_parser_from_source_str(
559 FileName::Custom("stdin".to_owned()),
564 parser.cfg_mods = false;
565 if config.skip_children() {
566 parser.recurse_into_file_modules = false;
569 let mut parser = AssertUnwindSafe(parser);
570 let result = catch_unwind(move || parser.0.parse_crate_mod());
574 if parse_session.span_diagnostic.has_errors() {
575 // Bail out if the parser recovered from an error.
576 Err(ParseError::Recovered)
581 Ok(Err(e)) => Err(ParseError::Error(e)),
582 Err(_) => Err(ParseError::Panic),
586 /// All the ways that parsing can fail.
587 enum ParseError<'sess> {
588 /// There was an error, but the parser recovered.
590 /// There was an error (supplied) and parsing failed.
591 Error(DiagnosticBuilder<'sess>),
592 /// The parser panicked.
596 /// Format the given snippet. The snippet is expected to be *complete* code.
597 /// When we cannot parse the given snippet, this function returns `None`.
598 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
599 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
600 let input = Input::Text(snippet.into());
601 let mut config = config.clone();
602 config.set().write_mode(config::WriteMode::Plain);
603 config.set().hide_parse_errors(true);
604 match format_input(input, &config, Some(&mut out)) {
605 // `format_input()` returns an empty string on parsing error.
606 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
607 Ok(..) => String::from_utf8(out).ok(),
612 const FN_MAIN_PREFIX: &str = "fn main() {\n";
614 fn enclose_in_main_block(s: &str, config: &Config) -> String {
615 let indent = Indent::from_width(config, config.tab_spaces());
616 let mut result = String::with_capacity(s.len() * 2);
617 result.push_str(FN_MAIN_PREFIX);
618 let mut need_indent = true;
619 for (kind, line) in LineClasses::new(s) {
621 result.push_str(&indent.to_string(config));
623 result.push_str(&line);
625 need_indent = !kind.is_string() || line.ends_with('\\');
631 /// Format the given code block. Mainly targeted for code block in comment.
632 /// The code block may be incomplete (i.e. parser may be unable to parse it).
633 /// To avoid panic in parser, we wrap the code block with a dummy function.
634 /// The returned code block does *not* end with newline.
635 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
636 // Wrap the given code block with `fn main()` if it does not have one.
637 let snippet = enclose_in_main_block(code_snippet, config);
638 let mut result = String::with_capacity(snippet.len());
639 let mut is_first = true;
641 // Trim "fn main() {" on the first line and "}" on the last line,
642 // then unindent the whole code block.
643 let formatted = format_snippet(&snippet, config)?;
645 let block_len = formatted.len().checked_sub(2).unwrap_or(0);
646 let mut is_indented = true;
647 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
653 let trimmed_line = if !is_indented {
655 } else if line.len() > config.max_width() {
656 // If there are lines that are larger than max width, we cannot tell
657 // whether we have succeeded but have some comments or strings that
658 // are too long, or we have failed to format code block. We will be
659 // conservative and just return `None` in this case.
661 } else if line.len() > config.tab_spaces() {
662 // Make sure that the line has leading whitespaces.
663 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
664 if line.starts_with(indent_str.as_ref()) {
665 let offset = if config.hard_tabs() {
677 result.push_str(trimmed_line);
678 is_indented = !kind.is_string() || line.ends_with('\\');
683 pub fn format_input<T: Write>(
687 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
688 syntax::with_globals(|| format_input_inner(input, config, out))
691 fn format_input_inner<T: Write>(
694 mut out: Option<&mut T>,
695 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
696 let mut summary = Summary::default();
697 if config.disable_all_formatting() {
698 // When the input is from stdin, echo back the input.
699 if let Input::Text(ref buf) = input {
700 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
701 return Err((e, summary));
704 return Ok((summary, FileMap::new(), FormatReport::new()));
706 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
708 let tty_handler = if config.hide_parse_errors() {
709 let silent_emitter = Box::new(EmitterWriter::new(
710 Box::new(Vec::new()),
711 Some(codemap.clone()),
715 Handler::with_emitter(true, false, silent_emitter)
717 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
718 let color_cfg = if supports_color {
723 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
725 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
727 let main_file = match input {
728 Input::File(ref file) => FileName::Real(file.clone()),
729 Input::Text(..) => FileName::Custom("stdin".to_owned()),
732 let krate = match parse_input(input, &parse_session, config) {
736 ParseError::Error(mut diagnostic) => diagnostic.emit(),
737 ParseError::Panic => {
738 // Note that if you see this message and want more information,
739 // then go to `parse_input` and run the parse function without
740 // `catch_unwind` so rustfmt panics and you can get a backtrace.
741 should_emit_verbose(&main_file, config, || {
742 println!("The Rust parser panicked")
745 ParseError::Recovered => {}
747 summary.add_parsing_error();
748 return Ok((summary, FileMap::new(), FormatReport::new()));
752 summary.mark_parse_time();
754 // Suppress error output after parsing.
755 let silent_emitter = Box::new(EmitterWriter::new(
756 Box::new(Vec::new()),
757 Some(codemap.clone()),
761 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
763 let mut report = FormatReport::new();
765 let format_result = format_ast(
770 |file_name, file, skipped_range| {
771 // For some reason, the codemap does not include terminating
772 // newlines so we must add one on for each file. This is sad.
773 filemap::append_newline(file);
775 format_lines(file, file_name, skipped_range, config, &mut report);
777 if let Some(ref mut out) = out {
778 return filemap::write_file(file, file_name, out, config);
784 summary.mark_format_time();
786 should_emit_verbose(&main_file, config, || {
787 fn duration_to_f32(d: Duration) -> f32 {
788 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
792 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
793 duration_to_f32(summary.get_parse_time().unwrap()),
794 duration_to_f32(summary.get_format_time().unwrap()),
798 match format_result {
799 Ok((file_map, has_diff)) => {
800 if report.has_warnings() {
801 summary.add_formatting_error();
808 Ok((summary, file_map, report))
810 Err(e) => Err((e, summary)),
814 /// A single span of changed lines, with 0 or more removed lines
815 /// and a vector of 0 or more inserted lines.
816 #[derive(Debug, PartialEq, Eq)]
817 struct ModifiedChunk {
818 /// The first to be removed from the original text
819 pub line_number_orig: u32,
820 /// The number of lines which have been replaced
821 pub lines_removed: u32,
823 pub lines: Vec<String>,
826 /// Set of changed sections of a file.
827 #[derive(Debug, PartialEq, Eq)]
828 struct ModifiedLines {
829 /// The set of changed chunks.
830 pub chunks: Vec<ModifiedChunk>,
833 /// The successful result of formatting via `get_modified_lines()`.
835 struct ModifiedLinesResult {
836 /// The high level summary details
837 pub summary: Summary,
838 /// The result Filemap
839 pub filemap: FileMap,
840 /// Map of formatting errors
841 pub report: FormatReport,
842 /// The sets of updated lines.
843 pub modified_lines: ModifiedLines,
846 /// Format a file and return a `ModifiedLines` data structure describing
847 /// the changed ranges of lines.
849 fn get_modified_lines(
852 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
853 use std::io::BufRead;
855 let mut data = Vec::new();
857 let mut config = config.clone();
858 config.set().write_mode(config::WriteMode::Modified);
859 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
861 let mut lines = data.lines();
862 let mut chunks = Vec::new();
863 while let Some(Ok(header)) = lines.next() {
864 // Parse the header line
865 let values: Vec<_> = header
867 .map(|s| s.parse::<u32>().unwrap())
869 assert_eq!(values.len(), 3);
870 let line_number_orig = values[0];
871 let lines_removed = values[1];
872 let num_added = values[2];
873 let mut added_lines = Vec::new();
874 for _ in 0..num_added {
875 added_lines.push(lines.next().unwrap().unwrap());
877 chunks.push(ModifiedChunk {
883 Ok(ModifiedLinesResult {
887 modified_lines: ModifiedLines { chunks },
897 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
898 if !config.version_meets_requirement() {
899 return Err(format_err!("Version mismatch"));
901 let out = &mut stdout();
902 match format_input(input, config, Some(out)) {
903 Ok((summary, _, report)) => {
904 if report.has_warnings() {
905 match term::stderr() {
907 if use_colored_tty(config.color()) && t.supports_color()
908 && t.supports_attr(term::Attr::Bold) =>
910 match report.print_warnings_fancy(term::stderr().unwrap()) {
912 Err(..) => panic!("Unable to write to stderr: {}", report),
915 _ => eprintln!("{}", report),
921 Err((msg, mut summary)) => {
922 eprintln!("Error writing files: {}", msg);
923 summary.add_operational_error();
929 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
930 if config.write_mode() == WriteMode::Checkstyle {
931 let mut out = &mut stdout();
932 checkstyle::output_header(&mut out)?;
937 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
938 if config.write_mode() == WriteMode::Checkstyle {
939 let mut out = &mut stdout();
940 checkstyle::output_footer(&mut out)?;
947 use super::{format_code_block, format_snippet, Config};
950 fn test_no_panic_on_format_snippet_and_format_code_block() {
951 // `format_snippet()` and `format_code_block()` should not panic
952 // even when we cannot parse the given snippet.
954 assert!(format_snippet(snippet, &Config::default()).is_none());
955 assert!(format_code_block(snippet, &Config::default()).is_none());
958 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
960 F: Fn(&str, &Config) -> Option<String>,
962 let output = formatter(input, &Config::default());
963 output.is_some() && output.unwrap() == expected
967 fn test_format_snippet() {
968 let snippet = "fn main() { println!(\"hello, world\"); }";
969 let expected = "fn main() {\n \
970 println!(\"hello, world\");\n\
972 assert!(test_format_inner(format_snippet, snippet, expected));
976 fn test_format_code_block_fail() {
978 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
979 assert!(format_code_block(code_block, &Config::default()).is_none());
983 fn test_format_code_block() {
985 let code_block = "let x=3;";
986 let expected = "let x = 3;";
987 assert!(test_format_inner(format_code_block, code_block, expected));
989 // more complex code block, taken from chains.rs.
991 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
993 chain_indent(context, shape.add_offset(parent_rewrite.len())),
994 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
996 } else if is_block_expr(context, &parent, &parent_rewrite) {
997 match context.config.indent_style() {
998 // Try to put the first child on the same line with parent's last line
999 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1000 // The parent is a block, so align the rest of the chain with the closing
1002 IndentStyle::Visual => (parent_shape, false),
1006 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1012 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1014 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1015 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1017 } else if is_block_expr(context, &parent, &parent_rewrite) {
1018 match context.config.indent_style() {
1019 // Try to put the first child on the same line with parent's last line
1020 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1021 // The parent is a block, so align the rest of the chain with the closing
1023 IndentStyle::Visual => (parent_shape, false),
1027 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1031 assert!(test_format_inner(format_code_block, code_block, expected));