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 // TODO or FIXME 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 formatted, but exceeded maximum width (maximum: {} (see `max_width` option), 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(..) | ErrorKind::TrailingWhitespace => "internal error:",
138 ErrorKind::LicenseCheck => "error:",
139 ErrorKind::BadIssue(_) => "warning:",
143 fn msg_suffix(&self) -> &str {
144 if self.is_comment || self.is_string {
145 "set `error_on_unformatted = false` to suppress \
146 the warning against comments or string literals\n"
153 pub fn format_len(&self) -> (usize, usize) {
155 ErrorKind::LineOverflow(found, max) => (max, found - max),
156 ErrorKind::TrailingWhitespace => {
157 let trailing_ws_start = self.line_buffer
158 .rfind(|c: char| !c.is_whitespace())
163 self.line_buffer.len() - trailing_ws_start,
171 pub struct FormatReport {
172 // Maps stringified file paths to their associated formatting errors.
173 file_error_map: HashMap<FileName, Vec<FormattingError>>,
177 fn new() -> FormatReport {
179 file_error_map: HashMap::new(),
183 pub fn warning_count(&self) -> usize {
186 .map(|(_, errors)| errors.len())
190 pub fn has_warnings(&self) -> bool {
191 self.warning_count() > 0
194 pub fn print_warnings_fancy(
196 mut t: Box<term::Terminal<Output = io::Stderr>>,
197 ) -> Result<(), term::Error> {
198 for (file, errors) in &self.file_error_map {
199 for error in errors {
200 let prefix_space_len = error.line.to_string().len();
201 let prefix_spaces = " ".repeat(1 + prefix_space_len);
203 // First line: the overview of error
204 t.fg(term::color::RED)?;
205 t.attr(term::Attr::Bold)?;
206 write!(t, "{} ", error.msg_prefix())?;
208 t.attr(term::Attr::Bold)?;
209 write!(t, "{}\n", error.kind)?;
211 // Second line: file info
212 write!(t, "{}--> ", &prefix_spaces[1..])?;
214 write!(t, "{}:{}\n", file, error.line)?;
216 // Third to fifth lines: show the line which triggered error, if available.
217 if !error.line_buffer.is_empty() {
218 let (space_len, target_len) = error.format_len();
219 t.attr(term::Attr::Bold)?;
220 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
222 write!(t, "{}\n", error.line_buffer)?;
223 t.attr(term::Attr::Bold)?;
224 write!(t, "{}| ", prefix_spaces)?;
225 t.fg(term::color::RED)?;
226 write!(t, "{}\n", target_str(space_len, target_len))?;
230 // The last line: show note if available.
231 let msg_suffix = error.msg_suffix();
232 if !msg_suffix.is_empty() {
233 t.attr(term::Attr::Bold)?;
234 write!(t, "{}= note: ", prefix_spaces)?;
236 write!(t, "{}\n", error.msg_suffix())?;
244 if !self.file_error_map.is_empty() {
245 t.attr(term::Attr::Bold)?;
246 write!(t, "warning: ")?;
250 "rustfmt may have failed to format. See previous {} errors.\n\n",
251 self.warning_count(),
259 fn target_str(space_len: usize, target_len: usize) -> String {
260 let empty_line = " ".repeat(space_len);
261 let overflowed = "^".repeat(target_len);
262 empty_line + &overflowed
265 impl fmt::Display for FormatReport {
266 // Prints all the formatting errors.
267 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
268 for (file, errors) in &self.file_error_map {
269 for error in errors {
270 let prefix_space_len = error.line.to_string().len();
271 let prefix_spaces = " ".repeat(1 + prefix_space_len);
273 let error_line_buffer = if error.line_buffer.is_empty() {
276 let (space_len, target_len) = error.format_len();
278 "{}|\n{} | {}\n{}| {}",
283 target_str(space_len, target_len)
287 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
288 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
289 let msg_suffix = error.msg_suffix();
290 let note = if msg_suffix.is_empty() {
293 format!("{}note= ", prefix_spaces)
298 "{}\n{}\n{}\n{}{}\n",
307 if !self.file_error_map.is_empty() {
310 "warning: rustfmt may have failed to format. See previous {} errors.\n",
311 self.warning_count(),
318 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
322 if config.verbose() && path.to_string() != STDIN {
327 // Formatting which depends on the AST.
330 parse_session: &mut ParseSess,
331 main_file: &FileName,
334 ) -> Result<(FileMap, bool), io::Error>
336 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
338 let mut result = FileMap::new();
339 // diff mode: check if any files are differing
340 let mut has_diff = false;
342 // We always skip children for the "Plain" write mode, since there is
343 // nothing to distinguish the nested module contents.
344 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
345 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
346 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
349 should_emit_verbose(&path, config, || println!("Formatting {}", path));
350 let filemap = parse_session
352 .lookup_char_pos(module.inner.lo())
354 let big_snippet = filemap.src.as_ref().unwrap();
355 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
356 let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
357 // Format inner attributes if available.
358 if !krate.attrs.is_empty() && path == *main_file {
359 visitor.skip_empty_lines(filemap.end_pos);
360 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
361 visitor.push_rewrite(module.inner, None);
363 visitor.format_separate_mod(module, &*filemap);
366 visitor.last_pos = filemap.start_pos;
367 visitor.skip_empty_lines(filemap.end_pos);
368 visitor.format_separate_mod(module, &*filemap);
373 ::utils::count_newlines(&format!("{}", visitor.buffer))
376 let filename = path.clone();
377 has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
378 Ok(result) => result,
380 // Create a new error with path_str to help users see which files failed
381 let err_msg = format!("{}: {}", path, e);
382 return Err(io::Error::new(e.kind(), err_msg));
386 result.push((filename, visitor.buffer));
389 Ok((result, has_diff))
392 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
393 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
396 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
399 fn should_report_error(
401 char_kind: FullCodeCharKind,
403 error_kind: ErrorKind,
405 let allow_error_report = if char_kind.is_comment() || is_string {
406 config.error_on_unformatted()
412 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
413 ErrorKind::TrailingWhitespace => allow_error_report,
418 // Formatting done on a char by char or line by line basis.
419 // FIXME(#20) other stuff for parity with make tidy
423 skipped_range: &[(usize, usize)],
425 report: &mut FormatReport,
427 let mut trims = vec![];
428 let mut last_wspace: Option<usize> = None;
429 let mut line_len = 0;
430 let mut cur_line = 1;
431 let mut newline_count = 0;
432 let mut errors = vec![];
433 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
434 let mut line_buffer = String::with_capacity(config.max_width() * 2);
435 let mut is_string = false; // true if the current line contains a string literal.
436 let mut format_line = config.file_lines().contains_line(name, cur_line);
437 let allow_issue_seek = !issue_seeker.is_disabled();
440 if let Some(ref license_template) = config.license_template {
441 if !license_template.is_match(text) {
442 errors.push(FormattingError {
444 kind: ErrorKind::LicenseCheck,
447 line_buffer: String::new(),
452 // Iterate over the chars in the file map.
453 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
458 if allow_issue_seek && format_line {
459 // Add warnings for bad todos/ fixmes
460 if let Some(issue) = issue_seeker.inspect(c) {
461 errors.push(FormattingError {
463 kind: ErrorKind::BadIssue(issue),
466 line_buffer: String::new(),
473 // Check for (and record) trailing whitespace.
474 if let Some(..) = last_wspace {
475 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
476 trims.push((cur_line, kind, line_buffer.clone()));
481 // Check for any line width errors we couldn't correct.
482 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
483 if line_len > config.max_width() && !is_skipped_line(cur_line, skipped_range)
484 && should_report_error(config, kind, is_string, error_kind)
486 errors.push(FormattingError {
489 is_comment: kind.is_comment(),
491 line_buffer: line_buffer.clone(),
498 format_line = config.file_lines().contains_line(name, cur_line);
505 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
506 if c.is_whitespace() {
507 if last_wspace.is_none() {
508 last_wspace = Some(b);
514 if kind.is_string() {
520 if newline_count > 1 {
521 debug!("track truncate: {} {}", text.len(), newline_count);
522 let line = text.len() - newline_count + 1;
526 for &(l, kind, ref b) in &trims {
527 if !is_skipped_line(l, skipped_range) {
528 errors.push(FormattingError {
530 kind: ErrorKind::TrailingWhitespace,
531 is_comment: kind.is_comment(),
532 is_string: kind.is_string(),
533 line_buffer: b.clone(),
538 report.file_error_map.insert(name.clone(), errors);
541 fn parse_input<'sess>(
543 parse_session: &'sess ParseSess,
545 ) -> Result<ast::Crate, ParseError<'sess>> {
546 let mut parser = match input {
547 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
548 Input::Text(text) => parse::new_parser_from_source_str(
550 FileName::Custom("stdin".to_owned()),
555 parser.cfg_mods = false;
556 if config.skip_children() {
557 parser.recurse_into_file_modules = false;
560 let mut parser = AssertUnwindSafe(parser);
561 let result = catch_unwind(move || parser.0.parse_crate_mod());
565 if parse_session.span_diagnostic.has_errors() {
566 // Bail out if the parser recovered from an error.
567 Err(ParseError::Recovered)
572 Ok(Err(e)) => Err(ParseError::Error(e)),
573 Err(_) => Err(ParseError::Panic),
577 /// All the ways that parsing can fail.
578 enum ParseError<'sess> {
579 /// There was an error, but the parser recovered.
581 /// There was an error (supplied) and parsing failed.
582 Error(DiagnosticBuilder<'sess>),
583 /// The parser panicked.
587 /// Format the given snippet. The snippet is expected to be *complete* code.
588 /// When we cannot parse the given snippet, this function returns `None`.
589 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
590 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
591 let input = Input::Text(snippet.into());
592 let mut config = config.clone();
593 config.set().write_mode(config::WriteMode::Plain);
594 config.set().hide_parse_errors(true);
595 match format_input(input, &config, Some(&mut out)) {
596 // `format_input()` returns an empty string on parsing error.
597 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
598 Ok(..) => String::from_utf8(out).ok(),
603 const FN_MAIN_PREFIX: &str = "fn main() {\n";
605 fn enclose_in_main_block(s: &str, config: &Config) -> String {
606 let indent = Indent::from_width(config, config.tab_spaces());
607 let mut result = String::with_capacity(s.len() * 2);
608 result.push_str(FN_MAIN_PREFIX);
609 let mut need_indent = true;
610 for (kind, line) in LineClasses::new(s) {
612 result.push_str(&indent.to_string(config));
614 result.push_str(&line);
616 need_indent = !(kind.is_string() && !line.ends_with('\\'));
622 /// Format the given code block. Mainly targeted for code block in comment.
623 /// The code block may be incomplete (i.e. parser may be unable to parse it).
624 /// To avoid panic in parser, we wrap the code block with a dummy function.
625 /// The returned code block does *not* end with newline.
626 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
627 // Wrap the given code block with `fn main()` if it does not have one.
628 let snippet = enclose_in_main_block(code_snippet, config);
629 let mut result = String::with_capacity(snippet.len());
630 let mut is_first = true;
632 // Trim "fn main() {" on the first line and "}" on the last line,
633 // then unindent the whole code block.
634 let formatted = format_snippet(&snippet, config)?;
636 let block_len = formatted.len().checked_sub(2).unwrap_or(0);
637 let mut is_indented = true;
638 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
644 let trimmed_line = if !is_indented {
646 } else if line.len() > config.max_width() {
647 // If there are lines that are larger than max width, we cannot tell
648 // whether we have succeeded but have some comments or strings that
649 // are too long, or we have failed to format code block. We will be
650 // conservative and just return `None` in this case.
652 } else if line.len() > config.tab_spaces() {
653 // Make sure that the line has leading whitespaces.
654 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
655 if line.starts_with(indent_str.as_ref()) {
656 let offset = if config.hard_tabs() {
668 result.push_str(trimmed_line);
669 is_indented = !(kind.is_string() && !line.ends_with('\\'));
674 pub fn format_input<T: Write>(
678 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
679 syntax::with_globals(|| format_input_inner(input, config, out))
682 fn format_input_inner<T: Write>(
685 mut out: Option<&mut T>,
686 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
687 let mut summary = Summary::default();
688 if config.disable_all_formatting() {
689 // When the input is from stdin, echo back the input.
690 if let Input::Text(ref buf) = input {
691 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
692 return Err((e, summary));
695 return Ok((summary, FileMap::new(), FormatReport::new()));
697 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
699 let tty_handler = if config.hide_parse_errors() {
700 let silent_emitter = Box::new(EmitterWriter::new(
701 Box::new(Vec::new()),
702 Some(codemap.clone()),
706 Handler::with_emitter(true, false, silent_emitter)
708 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
709 let color_cfg = if supports_color {
714 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
716 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
718 let main_file = match input {
719 Input::File(ref file) => FileName::Real(file.clone()),
720 Input::Text(..) => FileName::Custom("stdin".to_owned()),
723 let krate = match parse_input(input, &parse_session, config) {
727 ParseError::Error(mut diagnostic) => diagnostic.emit(),
728 ParseError::Panic => {
729 // Note that if you see this message and want more information,
730 // then go to `parse_input` and run the parse function without
731 // `catch_unwind` so rustfmt panics and you can get a backtrace.
732 should_emit_verbose(&main_file, config, || {
733 println!("The Rust parser panicked")
736 ParseError::Recovered => {}
738 summary.add_parsing_error();
739 return Ok((summary, FileMap::new(), FormatReport::new()));
743 summary.mark_parse_time();
745 // Suppress error output after parsing.
746 let silent_emitter = Box::new(EmitterWriter::new(
747 Box::new(Vec::new()),
748 Some(codemap.clone()),
752 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
754 let mut report = FormatReport::new();
756 let format_result = format_ast(
761 |file_name, file, skipped_range| {
762 // For some reason, the codemap does not include terminating
763 // newlines so we must add one on for each file. This is sad.
764 filemap::append_newline(file);
766 format_lines(file, file_name, skipped_range, config, &mut report);
768 if let Some(ref mut out) = out {
769 return filemap::write_file(file, file_name, out, config);
775 summary.mark_format_time();
777 should_emit_verbose(&main_file, config, || {
778 fn duration_to_f32(d: Duration) -> f32 {
779 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
783 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
784 duration_to_f32(summary.get_parse_time().unwrap()),
785 duration_to_f32(summary.get_format_time().unwrap()),
789 match format_result {
790 Ok((file_map, has_diff)) => {
791 if report.has_warnings() {
792 summary.add_formatting_error();
799 Ok((summary, file_map, report))
801 Err(e) => Err((e, summary)),
805 /// A single span of changed lines, with 0 or more removed lines
806 /// and a vector of 0 or more inserted lines.
807 #[derive(Debug, PartialEq, Eq)]
808 pub struct ModifiedChunk {
809 /// The first to be removed from the original text
810 pub line_number_orig: u32,
811 /// The number of lines which have been replaced
812 pub lines_removed: u32,
814 pub lines: Vec<String>,
817 /// Set of changed sections of a file.
818 #[derive(Debug, PartialEq, Eq)]
819 pub struct ModifiedLines {
820 /// The set of changed chunks.
821 pub chunks: Vec<ModifiedChunk>,
824 /// The successful result of formatting via `get_modified_lines()`.
825 pub struct ModifiedLinesResult {
826 /// The high level summary details
827 pub summary: Summary,
828 /// The result Filemap
829 pub filemap: FileMap,
830 /// Map of formatting errors
831 pub report: FormatReport,
832 /// The sets of updated lines.
833 pub modified_lines: ModifiedLines,
836 /// Format a file and return a `ModifiedLines` data structure describing
837 /// the changed ranges of lines.
838 pub fn get_modified_lines(
841 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
842 let mut data = Vec::new();
844 let mut config = config.clone();
845 config.set().write_mode(config::WriteMode::Modified);
846 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
848 let mut lines = data.lines();
849 let mut chunks = Vec::new();
850 while let Some(Ok(header)) = lines.next() {
851 // Parse the header line
852 let values: Vec<_> = header
854 .map(|s| s.parse::<u32>().unwrap())
856 assert_eq!(values.len(), 3);
857 let line_number_orig = values[0];
858 let lines_removed = values[1];
859 let num_added = values[2];
860 let mut added_lines = Vec::new();
861 for _ in 0..num_added {
862 added_lines.push(lines.next().unwrap().unwrap());
864 chunks.push(ModifiedChunk {
870 Ok(ModifiedLinesResult {
874 modified_lines: ModifiedLines { chunks },
884 pub fn run(input: Input, config: &Config) -> Summary {
885 let out = &mut stdout();
886 output_header(out, config.write_mode()).ok();
887 match format_input(input, config, Some(out)) {
888 Ok((summary, _, report)) => {
889 output_footer(out, config.write_mode()).ok();
891 if report.has_warnings() {
892 match term::stderr() {
894 if use_colored_tty(config.color()) && t.supports_color()
895 && t.supports_attr(term::Attr::Bold) =>
897 match report.print_warnings_fancy(term::stderr().unwrap()) {
899 Err(..) => panic!("Unable to write to stderr: {}", report),
902 _ => msg!("{}", report),
908 Err((msg, mut summary)) => {
909 msg!("Error writing files: {}", msg);
910 summary.add_operational_error();
918 use super::{format_code_block, format_snippet, Config};
921 fn test_no_panic_on_format_snippet_and_format_code_block() {
922 // `format_snippet()` and `format_code_block()` should not panic
923 // even when we cannot parse the given snippet.
925 assert!(format_snippet(snippet, &Config::default()).is_none());
926 assert!(format_code_block(snippet, &Config::default()).is_none());
929 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
931 F: Fn(&str, &Config) -> Option<String>,
933 let output = formatter(input, &Config::default());
934 output.is_some() && output.unwrap() == expected
938 fn test_format_snippet() {
939 let snippet = "fn main() { println!(\"hello, world\"); }";
940 let expected = "fn main() {\n \
941 println!(\"hello, world\");\n\
943 assert!(test_format_inner(format_snippet, snippet, expected));
947 fn test_format_code_block_fail() {
949 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
950 assert!(format_code_block(code_block, &Config::default()).is_none());
954 fn test_format_code_block() {
956 let code_block = "let x=3;";
957 let expected = "let x = 3;";
958 assert!(test_format_inner(format_code_block, code_block, expected));
960 // more complex code block, taken from chains.rs.
962 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
964 chain_indent(context, shape.add_offset(parent_rewrite.len())),
965 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
967 } else if is_block_expr(context, &parent, &parent_rewrite) {
968 match context.config.indent_style() {
969 // Try to put the first child on the same line with parent's last line
970 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
971 // The parent is a block, so align the rest of the chain with the closing
973 IndentStyle::Visual => (parent_shape, false),
977 chain_indent(context, shape.add_offset(parent_rewrite.len())),
983 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
985 chain_indent(context, shape.add_offset(parent_rewrite.len())),
986 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
988 } else if is_block_expr(context, &parent, &parent_rewrite) {
989 match context.config.indent_style() {
990 // Try to put the first child on the same line with parent's last line
991 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
992 // The parent is a block, so align the rest of the chain with the closing
994 IndentStyle::Visual => (parent_shape, false),
998 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1002 assert!(test_format_inner(format_code_block, code_block, expected));