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)]
19 extern crate derive_new;
21 extern crate itertools;
27 extern crate serde_derive;
28 extern crate serde_json;
32 extern crate unicode_segmentation;
34 use std::collections::HashMap;
36 use std::io::{self, stdout, BufRead, Write};
37 use std::panic::{catch_unwind, AssertUnwindSafe};
38 use std::path::PathBuf;
40 use std::time::Duration;
43 pub use syntax::codemap::FileName;
44 use syntax::codemap::{CodeMap, FilePathMapping};
45 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
46 use syntax::errors::{DiagnosticBuilder, Handler};
47 use syntax::parse::{self, ParseSess};
49 use checkstyle::{output_footer, output_header};
50 use comment::{CharClasses, FullCodeCharKind, LineClasses};
51 use issues::{BadIssueSeeker, Issue};
53 use utils::use_colored_tty;
54 use visitor::{FmtVisitor, SnippetProvider};
56 pub use config::summary::Summary;
57 pub use config::Config;
91 const STDIN: &str = "<stdin>";
93 // A map of the files of a crate, with their new content
94 pub type FileMap = Vec<FileRecord>;
96 pub type FileRecord = (FileName, String);
98 #[derive(Clone, Copy)]
100 // Line has exceeded character limit (found, maximum)
101 LineOverflow(usize, usize),
102 // Line ends in whitespace
104 // TO-DO or FIX-ME item without an issue number
106 // License check has failed
110 impl fmt::Display for ErrorKind {
111 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
113 ErrorKind::LineOverflow(found, maximum) => write!(
115 "line exceeded maximum width (maximum: {}, found: {})",
118 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
119 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
120 ErrorKind::LicenseCheck => write!(fmt, "license check failed"),
125 // Formatting errors that are identified *after* rustfmt has run.
126 pub struct FormattingError {
134 impl FormattingError {
135 fn msg_prefix(&self) -> &str {
137 ErrorKind::LineOverflow(..)
138 | ErrorKind::TrailingWhitespace
139 | ErrorKind::LicenseCheck => "error:",
140 ErrorKind::BadIssue(_) => "WARNING:",
144 fn msg_suffix(&self) -> &str {
145 if self.is_comment || self.is_string {
146 "set `error_on_unformatted = false` to suppress \
147 the warning against comments or string literals\n"
154 pub fn format_len(&self) -> (usize, usize) {
156 ErrorKind::LineOverflow(found, max) => (max, found - max),
157 ErrorKind::TrailingWhitespace => {
158 let trailing_ws_start = self.line_buffer
159 .rfind(|c: char| !c.is_whitespace())
164 self.line_buffer.len() - trailing_ws_start,
172 pub struct FormatReport {
173 // Maps stringified file paths to their associated formatting errors.
174 file_error_map: HashMap<FileName, Vec<FormattingError>>,
178 fn new() -> FormatReport {
180 file_error_map: HashMap::new(),
184 pub fn warning_count(&self) -> usize {
187 .map(|(_, errors)| errors.len())
191 pub fn has_warnings(&self) -> bool {
192 self.warning_count() > 0
195 pub fn print_warnings_fancy(
197 mut t: Box<term::Terminal<Output = io::Stderr>>,
198 ) -> Result<(), term::Error> {
199 for (file, errors) in &self.file_error_map {
200 for error in errors {
201 let prefix_space_len = error.line.to_string().len();
202 let prefix_spaces = " ".repeat(1 + prefix_space_len);
204 // First line: the overview of error
205 t.fg(term::color::RED)?;
206 t.attr(term::Attr::Bold)?;
207 write!(t, "{} ", error.msg_prefix())?;
209 t.attr(term::Attr::Bold)?;
210 write!(t, "{}\n", error.kind)?;
212 // Second line: file info
213 write!(t, "{}--> ", &prefix_spaces[1..])?;
215 write!(t, "{}:{}\n", file, error.line)?;
217 // Third to fifth lines: show the line which triggered error, if available.
218 if !error.line_buffer.is_empty() {
219 let (space_len, target_len) = error.format_len();
220 t.attr(term::Attr::Bold)?;
221 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
223 write!(t, "{}\n", error.line_buffer)?;
224 t.attr(term::Attr::Bold)?;
225 write!(t, "{}| ", prefix_spaces)?;
226 t.fg(term::color::RED)?;
227 write!(t, "{}\n", target_str(space_len, target_len))?;
231 // The last line: show note if available.
232 let msg_suffix = error.msg_suffix();
233 if !msg_suffix.is_empty() {
234 t.attr(term::Attr::Bold)?;
235 write!(t, "{}= note: ", prefix_spaces)?;
237 write!(t, "{}\n", error.msg_suffix())?;
245 if !self.file_error_map.is_empty() {
246 t.attr(term::Attr::Bold)?;
247 write!(t, "warning: ")?;
251 "rustfmt may have failed to format. See previous {} errors.\n\n",
252 self.warning_count(),
260 fn target_str(space_len: usize, target_len: usize) -> String {
261 let empty_line = " ".repeat(space_len);
262 let overflowed = "^".repeat(target_len);
263 empty_line + &overflowed
266 impl fmt::Display for FormatReport {
267 // Prints all the formatting errors.
268 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
269 for (file, errors) in &self.file_error_map {
270 for error in errors {
271 let prefix_space_len = error.line.to_string().len();
272 let prefix_spaces = " ".repeat(1 + prefix_space_len);
274 let error_line_buffer = if error.line_buffer.is_empty() {
277 let (space_len, target_len) = error.format_len();
279 "{}|\n{} | {}\n{}| {}",
284 target_str(space_len, target_len)
288 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
289 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
290 let msg_suffix = error.msg_suffix();
291 let note = if msg_suffix.is_empty() {
294 format!("{}note= ", prefix_spaces)
299 "{}\n{}\n{}\n{}{}\n",
308 if !self.file_error_map.is_empty() {
311 "warning: rustfmt may have failed to format. See previous {} errors.\n",
312 self.warning_count(),
319 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
323 if config.verbose() && path.to_string() != STDIN {
328 // Formatting which depends on the AST.
331 parse_session: &mut ParseSess,
332 main_file: &FileName,
335 ) -> Result<(FileMap, bool), io::Error>
337 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
339 let mut result = FileMap::new();
340 // diff mode: check if any files are differing
341 let mut has_diff = false;
343 // We always skip children for the "Plain" write mode, since there is
344 // nothing to distinguish the nested module contents.
345 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
346 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
347 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
350 should_emit_verbose(&path, config, || println!("Formatting {}", path));
351 let filemap = parse_session
353 .lookup_char_pos(module.inner.lo())
355 let big_snippet = filemap.src.as_ref().unwrap();
356 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
357 let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
358 // Format inner attributes if available.
359 if !krate.attrs.is_empty() && path == *main_file {
360 visitor.skip_empty_lines(filemap.end_pos);
361 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
362 visitor.push_rewrite(module.inner, None);
364 visitor.format_separate_mod(module, &*filemap);
367 visitor.last_pos = filemap.start_pos;
368 visitor.skip_empty_lines(filemap.end_pos);
369 visitor.format_separate_mod(module, &*filemap);
374 ::utils::count_newlines(&format!("{}", visitor.buffer))
377 let filename = path.clone();
378 has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
379 Ok(result) => result,
381 // Create a new error with path_str to help users see which files failed
382 let err_msg = format!("{}: {}", path, e);
383 return Err(io::Error::new(e.kind(), err_msg));
387 result.push((filename, visitor.buffer));
390 Ok((result, has_diff))
393 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
394 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
397 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
400 fn should_report_error(
402 char_kind: FullCodeCharKind,
404 error_kind: ErrorKind,
406 let allow_error_report = if char_kind.is_comment() || is_string {
407 config.error_on_unformatted()
413 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
414 ErrorKind::TrailingWhitespace => allow_error_report,
419 // Formatting done on a char by char or line by line basis.
420 // FIXME(#20) other stuff for parity with make tidy
424 skipped_range: &[(usize, usize)],
426 report: &mut FormatReport,
428 let mut trims = vec![];
429 let mut last_wspace: Option<usize> = None;
430 let mut line_len = 0;
431 let mut cur_line = 1;
432 let mut newline_count = 0;
433 let mut errors = vec![];
434 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
435 let mut line_buffer = String::with_capacity(config.max_width() * 2);
436 let mut is_string = false; // true if the current line contains a string literal.
437 let mut format_line = config.file_lines().contains_line(name, cur_line);
438 let allow_issue_seek = !issue_seeker.is_disabled();
441 if let Some(ref license_template) = config.license_template {
442 if !license_template.is_match(text) {
443 errors.push(FormattingError {
445 kind: ErrorKind::LicenseCheck,
448 line_buffer: String::new(),
453 // Iterate over the chars in the file map.
454 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
459 if allow_issue_seek && format_line {
460 // Add warnings for bad todos/ fixmes
461 if let Some(issue) = issue_seeker.inspect(c) {
462 errors.push(FormattingError {
464 kind: ErrorKind::BadIssue(issue),
467 line_buffer: String::new(),
474 // Check for (and record) trailing whitespace.
475 if let Some(..) = last_wspace {
476 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
477 trims.push((cur_line, kind, line_buffer.clone()));
482 // Check for any line width errors we couldn't correct.
483 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
484 if line_len > config.max_width() && !is_skipped_line(cur_line, skipped_range)
485 && should_report_error(config, kind, is_string, error_kind)
487 errors.push(FormattingError {
490 is_comment: kind.is_comment(),
492 line_buffer: line_buffer.clone(),
499 format_line = config.file_lines().contains_line(name, cur_line);
506 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
507 if c.is_whitespace() {
508 if last_wspace.is_none() {
509 last_wspace = Some(b);
515 if kind.is_string() {
521 if newline_count > 1 {
522 debug!("track truncate: {} {}", text.len(), newline_count);
523 let line = text.len() - newline_count + 1;
527 for &(l, kind, ref b) in &trims {
528 if !is_skipped_line(l, skipped_range) {
529 errors.push(FormattingError {
531 kind: ErrorKind::TrailingWhitespace,
532 is_comment: kind.is_comment(),
533 is_string: kind.is_string(),
534 line_buffer: b.clone(),
539 report.file_error_map.insert(name.clone(), errors);
542 fn parse_input<'sess>(
544 parse_session: &'sess ParseSess,
546 ) -> Result<ast::Crate, ParseError<'sess>> {
547 let mut parser = match input {
548 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
549 Input::Text(text) => parse::new_parser_from_source_str(
551 FileName::Custom("stdin".to_owned()),
556 parser.cfg_mods = false;
557 if config.skip_children() {
558 parser.recurse_into_file_modules = false;
561 let mut parser = AssertUnwindSafe(parser);
562 let result = catch_unwind(move || parser.0.parse_crate_mod());
566 if parse_session.span_diagnostic.has_errors() {
567 // Bail out if the parser recovered from an error.
568 Err(ParseError::Recovered)
573 Ok(Err(e)) => Err(ParseError::Error(e)),
574 Err(_) => Err(ParseError::Panic),
578 /// All the ways that parsing can fail.
579 enum ParseError<'sess> {
580 /// There was an error, but the parser recovered.
582 /// There was an error (supplied) and parsing failed.
583 Error(DiagnosticBuilder<'sess>),
584 /// The parser panicked.
588 /// Format the given snippet. The snippet is expected to be *complete* code.
589 /// When we cannot parse the given snippet, this function returns `None`.
590 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
591 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
592 let input = Input::Text(snippet.into());
593 let mut config = config.clone();
594 config.set().write_mode(config::WriteMode::Plain);
595 config.set().hide_parse_errors(true);
596 match format_input(input, &config, Some(&mut out)) {
597 // `format_input()` returns an empty string on parsing error.
598 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
599 Ok(..) => String::from_utf8(out).ok(),
604 const FN_MAIN_PREFIX: &str = "fn main() {\n";
606 fn enclose_in_main_block(s: &str, config: &Config) -> String {
607 let indent = Indent::from_width(config, config.tab_spaces());
608 let mut result = String::with_capacity(s.len() * 2);
609 result.push_str(FN_MAIN_PREFIX);
610 let mut need_indent = true;
611 for (kind, line) in LineClasses::new(s) {
613 result.push_str(&indent.to_string(config));
615 result.push_str(&line);
617 need_indent = !(kind.is_string() && !line.ends_with('\\'));
623 /// Format the given code block. Mainly targeted for code block in comment.
624 /// The code block may be incomplete (i.e. parser may be unable to parse it).
625 /// To avoid panic in parser, we wrap the code block with a dummy function.
626 /// The returned code block does *not* end with newline.
627 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
628 // Wrap the given code block with `fn main()` if it does not have one.
629 let snippet = enclose_in_main_block(code_snippet, config);
630 let mut result = String::with_capacity(snippet.len());
631 let mut is_first = true;
633 // Trim "fn main() {" on the first line and "}" on the last line,
634 // then unindent the whole code block.
635 let formatted = format_snippet(&snippet, config)?;
637 let block_len = formatted.len().checked_sub(2).unwrap_or(0);
638 let mut is_indented = true;
639 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
645 let trimmed_line = if !is_indented {
647 } else if line.len() > config.max_width() {
648 // If there are lines that are larger than max width, we cannot tell
649 // whether we have succeeded but have some comments or strings that
650 // are too long, or we have failed to format code block. We will be
651 // conservative and just return `None` in this case.
653 } else if line.len() > config.tab_spaces() {
654 // Make sure that the line has leading whitespaces.
655 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
656 if line.starts_with(indent_str.as_ref()) {
657 let offset = if config.hard_tabs() {
669 result.push_str(trimmed_line);
670 is_indented = !(kind.is_string() && !line.ends_with('\\'));
675 pub fn format_input<T: Write>(
679 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
680 syntax::with_globals(|| format_input_inner(input, config, out))
683 fn format_input_inner<T: Write>(
686 mut out: Option<&mut T>,
687 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
688 let mut summary = Summary::default();
689 if config.disable_all_formatting() {
690 // When the input is from stdin, echo back the input.
691 if let Input::Text(ref buf) = input {
692 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
693 return Err((e, summary));
696 return Ok((summary, FileMap::new(), FormatReport::new()));
698 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
700 let tty_handler = if config.hide_parse_errors() {
701 let silent_emitter = Box::new(EmitterWriter::new(
702 Box::new(Vec::new()),
703 Some(codemap.clone()),
707 Handler::with_emitter(true, false, silent_emitter)
709 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
710 let color_cfg = if supports_color {
715 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
717 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
719 let main_file = match input {
720 Input::File(ref file) => FileName::Real(file.clone()),
721 Input::Text(..) => FileName::Custom("stdin".to_owned()),
724 let krate = match parse_input(input, &parse_session, config) {
728 ParseError::Error(mut diagnostic) => diagnostic.emit(),
729 ParseError::Panic => {
730 // Note that if you see this message and want more information,
731 // then go to `parse_input` and run the parse function without
732 // `catch_unwind` so rustfmt panics and you can get a backtrace.
733 should_emit_verbose(&main_file, config, || {
734 println!("The Rust parser panicked")
737 ParseError::Recovered => {}
739 summary.add_parsing_error();
740 return Ok((summary, FileMap::new(), FormatReport::new()));
744 summary.mark_parse_time();
746 // Suppress error output after parsing.
747 let silent_emitter = Box::new(EmitterWriter::new(
748 Box::new(Vec::new()),
749 Some(codemap.clone()),
753 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
755 let mut report = FormatReport::new();
757 let format_result = format_ast(
762 |file_name, file, skipped_range| {
763 // For some reason, the codemap does not include terminating
764 // newlines so we must add one on for each file. This is sad.
765 filemap::append_newline(file);
767 format_lines(file, file_name, skipped_range, config, &mut report);
769 if let Some(ref mut out) = out {
770 return filemap::write_file(file, file_name, out, config);
776 summary.mark_format_time();
778 should_emit_verbose(&main_file, config, || {
779 fn duration_to_f32(d: Duration) -> f32 {
780 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
784 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
785 duration_to_f32(summary.get_parse_time().unwrap()),
786 duration_to_f32(summary.get_format_time().unwrap()),
790 match format_result {
791 Ok((file_map, has_diff)) => {
792 if report.has_warnings() {
793 summary.add_formatting_error();
800 Ok((summary, file_map, report))
802 Err(e) => Err((e, summary)),
806 /// A single span of changed lines, with 0 or more removed lines
807 /// and a vector of 0 or more inserted lines.
808 #[derive(Debug, PartialEq, Eq)]
809 pub struct ModifiedChunk {
810 /// The first to be removed from the original text
811 pub line_number_orig: u32,
812 /// The number of lines which have been replaced
813 pub lines_removed: u32,
815 pub lines: Vec<String>,
818 /// Set of changed sections of a file.
819 #[derive(Debug, PartialEq, Eq)]
820 pub struct ModifiedLines {
821 /// The set of changed chunks.
822 pub chunks: Vec<ModifiedChunk>,
825 /// The successful result of formatting via `get_modified_lines()`.
826 pub struct ModifiedLinesResult {
827 /// The high level summary details
828 pub summary: Summary,
829 /// The result Filemap
830 pub filemap: FileMap,
831 /// Map of formatting errors
832 pub report: FormatReport,
833 /// The sets of updated lines.
834 pub modified_lines: ModifiedLines,
837 /// Format a file and return a `ModifiedLines` data structure describing
838 /// the changed ranges of lines.
839 pub fn get_modified_lines(
842 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
843 let mut data = Vec::new();
845 let mut config = config.clone();
846 config.set().write_mode(config::WriteMode::Modified);
847 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
849 let mut lines = data.lines();
850 let mut chunks = Vec::new();
851 while let Some(Ok(header)) = lines.next() {
852 // Parse the header line
853 let values: Vec<_> = header
855 .map(|s| s.parse::<u32>().unwrap())
857 assert_eq!(values.len(), 3);
858 let line_number_orig = values[0];
859 let lines_removed = values[1];
860 let num_added = values[2];
861 let mut added_lines = Vec::new();
862 for _ in 0..num_added {
863 added_lines.push(lines.next().unwrap().unwrap());
865 chunks.push(ModifiedChunk {
871 Ok(ModifiedLinesResult {
875 modified_lines: ModifiedLines { chunks },
885 pub fn run(input: Input, config: &Config) -> Summary {
886 let out = &mut stdout();
887 output_header(out, config.write_mode()).ok();
888 match format_input(input, config, Some(out)) {
889 Ok((summary, _, report)) => {
890 output_footer(out, config.write_mode()).ok();
892 if report.has_warnings() {
893 match term::stderr() {
895 if use_colored_tty(config.color()) && t.supports_color()
896 && t.supports_attr(term::Attr::Bold) =>
898 match report.print_warnings_fancy(term::stderr().unwrap()) {
900 Err(..) => panic!("Unable to write to stderr: {}", report),
903 _ => msg!("{}", report),
909 Err((msg, mut summary)) => {
910 msg!("Error writing files: {}", msg);
911 summary.add_operational_error();
919 use super::{format_code_block, format_snippet, Config};
922 fn test_no_panic_on_format_snippet_and_format_code_block() {
923 // `format_snippet()` and `format_code_block()` should not panic
924 // even when we cannot parse the given snippet.
926 assert!(format_snippet(snippet, &Config::default()).is_none());
927 assert!(format_code_block(snippet, &Config::default()).is_none());
930 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
932 F: Fn(&str, &Config) -> Option<String>,
934 let output = formatter(input, &Config::default());
935 output.is_some() && output.unwrap() == expected
939 fn test_format_snippet() {
940 let snippet = "fn main() { println!(\"hello, world\"); }";
941 let expected = "fn main() {\n \
942 println!(\"hello, world\");\n\
944 assert!(test_format_inner(format_snippet, snippet, expected));
948 fn test_format_code_block_fail() {
950 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
951 assert!(format_code_block(code_block, &Config::default()).is_none());
955 fn test_format_code_block() {
957 let code_block = "let x=3;";
958 let expected = "let x = 3;";
959 assert!(test_format_inner(format_code_block, code_block, expected));
961 // more complex code block, taken from chains.rs.
963 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
965 chain_indent(context, shape.add_offset(parent_rewrite.len())),
966 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
968 } else if is_block_expr(context, &parent, &parent_rewrite) {
969 match context.config.indent_style() {
970 // Try to put the first child on the same line with parent's last line
971 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
972 // The parent is a block, so align the rest of the chain with the closing
974 IndentStyle::Visual => (parent_shape, false),
978 chain_indent(context, shape.add_offset(parent_rewrite.len())),
984 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
986 chain_indent(context, shape.add_offset(parent_rewrite.len())),
987 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
989 } else if is_block_expr(context, &parent, &parent_rewrite) {
990 match context.config.indent_style() {
991 // Try to put the first child on the same line with parent's last line
992 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
993 // The parent is a block, so align the rest of the chain with the closing
995 IndentStyle::Visual => (parent_shape, false),
999 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1003 assert!(test_format_inner(format_code_block, code_block, expected));