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 comment::{CharClasses, FullCodeCharKind, LineClasses};
50 use issues::{BadIssueSeeker, Issue};
52 use utils::use_colored_tty;
53 use visitor::{FmtVisitor, SnippetProvider};
55 pub use config::summary::Summary;
56 pub use config::Config;
90 const STDIN: &str = "<stdin>";
92 // A map of the files of a crate, with their new content
93 pub type FileMap = Vec<FileRecord>;
95 pub type FileRecord = (FileName, String);
97 #[derive(Clone, Copy)]
99 // Line has exceeded character limit (found, maximum)
100 LineOverflow(usize, usize),
101 // Line ends in whitespace
103 // TODO or FIXME item without an issue number
105 // License check has failed
109 impl fmt::Display for ErrorKind {
110 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
112 ErrorKind::LineOverflow(found, maximum) => write!(
114 "line formatted, but exceeded maximum width (maximum: {} (see `max_width` option), found: {})",
117 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
118 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
119 ErrorKind::LicenseCheck => write!(fmt, "license check failed"),
124 // Formatting errors that are identified *after* rustfmt has run.
125 pub struct FormattingError {
133 impl FormattingError {
134 fn msg_prefix(&self) -> &str {
136 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
137 ErrorKind::LicenseCheck => "error:",
138 ErrorKind::BadIssue(_) => "warning:",
142 fn msg_suffix(&self) -> &str {
143 if self.is_comment || self.is_string {
144 "set `error_on_unformatted = false` to suppress \
145 the warning against comments or string literals\n"
152 pub fn format_len(&self) -> (usize, usize) {
154 ErrorKind::LineOverflow(found, max) => (max, found - max),
155 ErrorKind::TrailingWhitespace => {
156 let trailing_ws_start = self.line_buffer
157 .rfind(|c: char| !c.is_whitespace())
162 self.line_buffer.len() - trailing_ws_start,
170 pub struct FormatReport {
171 // Maps stringified file paths to their associated formatting errors.
172 file_error_map: HashMap<FileName, Vec<FormattingError>>,
176 fn new() -> FormatReport {
178 file_error_map: HashMap::new(),
182 pub fn warning_count(&self) -> usize {
185 .map(|(_, errors)| errors.len())
189 pub fn has_warnings(&self) -> bool {
190 self.warning_count() > 0
193 pub fn print_warnings_fancy(
195 mut t: Box<term::Terminal<Output = io::Stderr>>,
196 ) -> Result<(), term::Error> {
197 for (file, errors) in &self.file_error_map {
198 for error in errors {
199 let prefix_space_len = error.line.to_string().len();
200 let prefix_spaces = " ".repeat(1 + prefix_space_len);
202 // First line: the overview of error
203 t.fg(term::color::RED)?;
204 t.attr(term::Attr::Bold)?;
205 write!(t, "{} ", error.msg_prefix())?;
207 t.attr(term::Attr::Bold)?;
208 write!(t, "{}\n", error.kind)?;
210 // Second line: file info
211 write!(t, "{}--> ", &prefix_spaces[1..])?;
213 write!(t, "{}:{}\n", file, error.line)?;
215 // Third to fifth lines: show the line which triggered error, if available.
216 if !error.line_buffer.is_empty() {
217 let (space_len, target_len) = error.format_len();
218 t.attr(term::Attr::Bold)?;
219 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
221 write!(t, "{}\n", error.line_buffer)?;
222 t.attr(term::Attr::Bold)?;
223 write!(t, "{}| ", prefix_spaces)?;
224 t.fg(term::color::RED)?;
225 write!(t, "{}\n", target_str(space_len, target_len))?;
229 // The last line: show note if available.
230 let msg_suffix = error.msg_suffix();
231 if !msg_suffix.is_empty() {
232 t.attr(term::Attr::Bold)?;
233 write!(t, "{}= note: ", prefix_spaces)?;
235 write!(t, "{}\n", error.msg_suffix())?;
243 if !self.file_error_map.is_empty() {
244 t.attr(term::Attr::Bold)?;
245 write!(t, "warning: ")?;
249 "rustfmt may have failed to format. See previous {} errors.\n\n",
250 self.warning_count(),
258 fn target_str(space_len: usize, target_len: usize) -> String {
259 let empty_line = " ".repeat(space_len);
260 let overflowed = "^".repeat(target_len);
261 empty_line + &overflowed
264 impl fmt::Display for FormatReport {
265 // Prints all the formatting errors.
266 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
267 for (file, errors) in &self.file_error_map {
268 for error in errors {
269 let prefix_space_len = error.line.to_string().len();
270 let prefix_spaces = " ".repeat(1 + prefix_space_len);
272 let error_line_buffer = if error.line_buffer.is_empty() {
275 let (space_len, target_len) = error.format_len();
277 "{}|\n{} | {}\n{}| {}",
282 target_str(space_len, target_len)
286 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
287 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
288 let msg_suffix = error.msg_suffix();
289 let note = if msg_suffix.is_empty() {
292 format!("{}note= ", prefix_spaces)
297 "{}\n{}\n{}\n{}{}\n",
306 if !self.file_error_map.is_empty() {
309 "warning: rustfmt may have failed to format. See previous {} errors.\n",
310 self.warning_count(),
317 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
321 if config.verbose() && path.to_string() != STDIN {
326 // Formatting which depends on the AST.
329 parse_session: &mut ParseSess,
330 main_file: &FileName,
333 ) -> Result<(FileMap, bool), io::Error>
335 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
337 let mut result = FileMap::new();
338 // diff mode: check if any files are differing
339 let mut has_diff = false;
341 // We always skip children for the "Plain" write mode, since there is
342 // nothing to distinguish the nested module contents.
343 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
344 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
345 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
348 should_emit_verbose(&path, config, || println!("Formatting {}", path));
349 let filemap = parse_session
351 .lookup_char_pos(module.inner.lo())
353 let big_snippet = filemap.src.as_ref().unwrap();
354 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
355 let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
356 // Format inner attributes if available.
357 if !krate.attrs.is_empty() && path == *main_file {
358 visitor.skip_empty_lines(filemap.end_pos);
359 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
360 visitor.push_rewrite(module.inner, None);
362 visitor.format_separate_mod(module, &*filemap);
365 visitor.last_pos = filemap.start_pos;
366 visitor.skip_empty_lines(filemap.end_pos);
367 visitor.format_separate_mod(module, &*filemap);
372 ::utils::count_newlines(&format!("{}", visitor.buffer))
375 let filename = path.clone();
376 has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
377 Ok(result) => result,
379 // Create a new error with path_str to help users see which files failed
380 let err_msg = format!("{}: {}", path, e);
381 return Err(io::Error::new(e.kind(), err_msg));
385 result.push((filename, visitor.buffer));
388 Ok((result, has_diff))
391 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
392 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
395 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
398 fn should_report_error(
400 char_kind: FullCodeCharKind,
402 error_kind: ErrorKind,
404 let allow_error_report = if char_kind.is_comment() || is_string {
405 config.error_on_unformatted()
411 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
412 ErrorKind::TrailingWhitespace => allow_error_report,
417 // Formatting done on a char by char or line by line basis.
418 // FIXME(#20) other stuff for parity with make tidy
422 skipped_range: &[(usize, usize)],
424 report: &mut FormatReport,
426 let mut trims = vec![];
427 let mut last_wspace: Option<usize> = None;
428 let mut line_len = 0;
429 let mut cur_line = 1;
430 let mut newline_count = 0;
431 let mut errors = vec![];
432 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
433 let mut line_buffer = String::with_capacity(config.max_width() * 2);
434 let mut is_string = false; // true if the current line contains a string literal.
435 let mut format_line = config.file_lines().contains_line(name, cur_line);
436 let allow_issue_seek = !issue_seeker.is_disabled();
439 if let Some(ref license_template) = config.license_template {
440 if !license_template.is_match(text) {
441 errors.push(FormattingError {
443 kind: ErrorKind::LicenseCheck,
446 line_buffer: String::new(),
451 // Iterate over the chars in the file map.
452 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
457 if allow_issue_seek && format_line {
458 // Add warnings for bad todos/ fixmes
459 if let Some(issue) = issue_seeker.inspect(c) {
460 errors.push(FormattingError {
462 kind: ErrorKind::BadIssue(issue),
465 line_buffer: String::new(),
472 // Check for (and record) trailing whitespace.
473 if let Some(..) = last_wspace {
474 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
475 trims.push((cur_line, kind, line_buffer.clone()));
480 // Check for any line width errors we couldn't correct.
481 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
482 if line_len > config.max_width() && !is_skipped_line(cur_line, skipped_range)
483 && should_report_error(config, kind, is_string, error_kind)
485 errors.push(FormattingError {
488 is_comment: kind.is_comment(),
490 line_buffer: line_buffer.clone(),
497 format_line = config.file_lines().contains_line(name, cur_line);
504 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
505 if c.is_whitespace() {
506 if last_wspace.is_none() {
507 last_wspace = Some(b);
513 if kind.is_string() {
519 if newline_count > 1 {
520 debug!("track truncate: {} {}", text.len(), newline_count);
521 let line = text.len() - newline_count + 1;
525 for &(l, kind, ref b) in &trims {
526 if !is_skipped_line(l, skipped_range) {
527 errors.push(FormattingError {
529 kind: ErrorKind::TrailingWhitespace,
530 is_comment: kind.is_comment(),
531 is_string: kind.is_string(),
532 line_buffer: b.clone(),
537 report.file_error_map.insert(name.clone(), errors);
540 fn parse_input<'sess>(
542 parse_session: &'sess ParseSess,
544 ) -> Result<ast::Crate, ParseError<'sess>> {
545 let mut parser = match input {
546 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
547 Input::Text(text) => parse::new_parser_from_source_str(
549 FileName::Custom("stdin".to_owned()),
554 parser.cfg_mods = false;
555 if config.skip_children() {
556 parser.recurse_into_file_modules = false;
559 let mut parser = AssertUnwindSafe(parser);
560 let result = catch_unwind(move || parser.0.parse_crate_mod());
564 if parse_session.span_diagnostic.has_errors() {
565 // Bail out if the parser recovered from an error.
566 Err(ParseError::Recovered)
571 Ok(Err(e)) => Err(ParseError::Error(e)),
572 Err(_) => Err(ParseError::Panic),
576 /// All the ways that parsing can fail.
577 enum ParseError<'sess> {
578 /// There was an error, but the parser recovered.
580 /// There was an error (supplied) and parsing failed.
581 Error(DiagnosticBuilder<'sess>),
582 /// The parser panicked.
586 /// Format the given snippet. The snippet is expected to be *complete* code.
587 /// When we cannot parse the given snippet, this function returns `None`.
588 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
589 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
590 let input = Input::Text(snippet.into());
591 let mut config = config.clone();
592 config.set().write_mode(config::WriteMode::Plain);
593 config.set().hide_parse_errors(true);
594 match format_input(input, &config, Some(&mut out)) {
595 // `format_input()` returns an empty string on parsing error.
596 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
597 Ok(..) => String::from_utf8(out).ok(),
602 const FN_MAIN_PREFIX: &str = "fn main() {\n";
604 fn enclose_in_main_block(s: &str, config: &Config) -> String {
605 let indent = Indent::from_width(config, config.tab_spaces());
606 let mut result = String::with_capacity(s.len() * 2);
607 result.push_str(FN_MAIN_PREFIX);
608 let mut need_indent = true;
609 for (kind, line) in LineClasses::new(s) {
611 result.push_str(&indent.to_string(config));
613 result.push_str(&line);
615 need_indent = !(kind.is_string() && !line.ends_with('\\'));
621 /// Format the given code block. Mainly targeted for code block in comment.
622 /// The code block may be incomplete (i.e. parser may be unable to parse it).
623 /// To avoid panic in parser, we wrap the code block with a dummy function.
624 /// The returned code block does *not* end with newline.
625 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
626 // Wrap the given code block with `fn main()` if it does not have one.
627 let snippet = enclose_in_main_block(code_snippet, config);
628 let mut result = String::with_capacity(snippet.len());
629 let mut is_first = true;
631 // Trim "fn main() {" on the first line and "}" on the last line,
632 // then unindent the whole code block.
633 let formatted = format_snippet(&snippet, config)?;
635 let block_len = formatted.len().checked_sub(2).unwrap_or(0);
636 let mut is_indented = true;
637 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
643 let trimmed_line = if !is_indented {
645 } else if line.len() > config.max_width() {
646 // If there are lines that are larger than max width, we cannot tell
647 // whether we have succeeded but have some comments or strings that
648 // are too long, or we have failed to format code block. We will be
649 // conservative and just return `None` in this case.
651 } else if line.len() > config.tab_spaces() {
652 // Make sure that the line has leading whitespaces.
653 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
654 if line.starts_with(indent_str.as_ref()) {
655 let offset = if config.hard_tabs() {
667 result.push_str(trimmed_line);
668 is_indented = !(kind.is_string() && !line.ends_with('\\'));
673 pub fn format_input<T: Write>(
677 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
678 syntax::with_globals(|| format_input_inner(input, config, out))
681 fn format_input_inner<T: Write>(
684 mut out: Option<&mut T>,
685 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
686 let mut summary = Summary::default();
687 if config.disable_all_formatting() {
688 // When the input is from stdin, echo back the input.
689 if let Input::Text(ref buf) = input {
690 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
691 return Err((e, summary));
694 return Ok((summary, FileMap::new(), FormatReport::new()));
696 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
698 let tty_handler = if config.hide_parse_errors() {
699 let silent_emitter = Box::new(EmitterWriter::new(
700 Box::new(Vec::new()),
701 Some(codemap.clone()),
705 Handler::with_emitter(true, false, silent_emitter)
707 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
708 let color_cfg = if supports_color {
713 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
715 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
717 let main_file = match input {
718 Input::File(ref file) => FileName::Real(file.clone()),
719 Input::Text(..) => FileName::Custom("stdin".to_owned()),
722 let krate = match parse_input(input, &parse_session, config) {
726 ParseError::Error(mut diagnostic) => diagnostic.emit(),
727 ParseError::Panic => {
728 // Note that if you see this message and want more information,
729 // then go to `parse_input` and run the parse function without
730 // `catch_unwind` so rustfmt panics and you can get a backtrace.
731 should_emit_verbose(&main_file, config, || {
732 println!("The Rust parser panicked")
735 ParseError::Recovered => {}
737 summary.add_parsing_error();
738 return Ok((summary, FileMap::new(), FormatReport::new()));
742 summary.mark_parse_time();
744 // Suppress error output after parsing.
745 let silent_emitter = Box::new(EmitterWriter::new(
746 Box::new(Vec::new()),
747 Some(codemap.clone()),
751 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
753 let mut report = FormatReport::new();
755 let format_result = format_ast(
760 |file_name, file, skipped_range| {
761 // For some reason, the codemap does not include terminating
762 // newlines so we must add one on for each file. This is sad.
763 filemap::append_newline(file);
765 format_lines(file, file_name, skipped_range, config, &mut report);
767 if let Some(ref mut out) = out {
768 return filemap::write_file(file, file_name, out, config);
774 summary.mark_format_time();
776 should_emit_verbose(&main_file, config, || {
777 fn duration_to_f32(d: Duration) -> f32 {
778 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
782 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
783 duration_to_f32(summary.get_parse_time().unwrap()),
784 duration_to_f32(summary.get_format_time().unwrap()),
788 match format_result {
789 Ok((file_map, has_diff)) => {
790 if report.has_warnings() {
791 summary.add_formatting_error();
798 Ok((summary, file_map, report))
800 Err(e) => Err((e, summary)),
804 /// A single span of changed lines, with 0 or more removed lines
805 /// and a vector of 0 or more inserted lines.
806 #[derive(Debug, PartialEq, Eq)]
807 pub struct ModifiedChunk {
808 /// The first to be removed from the original text
809 pub line_number_orig: u32,
810 /// The number of lines which have been replaced
811 pub lines_removed: u32,
813 pub lines: Vec<String>,
816 /// Set of changed sections of a file.
817 #[derive(Debug, PartialEq, Eq)]
818 pub struct ModifiedLines {
819 /// The set of changed chunks.
820 pub chunks: Vec<ModifiedChunk>,
823 /// The successful result of formatting via `get_modified_lines()`.
824 pub struct ModifiedLinesResult {
825 /// The high level summary details
826 pub summary: Summary,
827 /// The result Filemap
828 pub filemap: FileMap,
829 /// Map of formatting errors
830 pub report: FormatReport,
831 /// The sets of updated lines.
832 pub modified_lines: ModifiedLines,
835 /// Format a file and return a `ModifiedLines` data structure describing
836 /// the changed ranges of lines.
837 pub fn get_modified_lines(
840 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
841 let mut data = Vec::new();
843 let mut config = config.clone();
844 config.set().write_mode(config::WriteMode::Modified);
845 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
847 let mut lines = data.lines();
848 let mut chunks = Vec::new();
849 while let Some(Ok(header)) = lines.next() {
850 // Parse the header line
851 let values: Vec<_> = header
853 .map(|s| s.parse::<u32>().unwrap())
855 assert_eq!(values.len(), 3);
856 let line_number_orig = values[0];
857 let lines_removed = values[1];
858 let num_added = values[2];
859 let mut added_lines = Vec::new();
860 for _ in 0..num_added {
861 added_lines.push(lines.next().unwrap().unwrap());
863 chunks.push(ModifiedChunk {
869 Ok(ModifiedLinesResult {
873 modified_lines: ModifiedLines { chunks },
883 pub fn run(input: Input, config: &Config) -> Summary {
884 let out = &mut stdout();
885 match format_input(input, config, Some(out)) {
886 Ok((summary, _, report)) => {
887 if report.has_warnings() {
888 match term::stderr() {
890 if use_colored_tty(config.color()) && t.supports_color()
891 && t.supports_attr(term::Attr::Bold) =>
893 match report.print_warnings_fancy(term::stderr().unwrap()) {
895 Err(..) => panic!("Unable to write to stderr: {}", report),
898 _ => msg!("{}", report),
904 Err((msg, mut summary)) => {
905 msg!("Error writing files: {}", msg);
906 summary.add_operational_error();
914 use super::{format_code_block, format_snippet, Config};
917 fn test_no_panic_on_format_snippet_and_format_code_block() {
918 // `format_snippet()` and `format_code_block()` should not panic
919 // even when we cannot parse the given snippet.
921 assert!(format_snippet(snippet, &Config::default()).is_none());
922 assert!(format_code_block(snippet, &Config::default()).is_none());
925 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
927 F: Fn(&str, &Config) -> Option<String>,
929 let output = formatter(input, &Config::default());
930 output.is_some() && output.unwrap() == expected
934 fn test_format_snippet() {
935 let snippet = "fn main() { println!(\"hello, world\"); }";
936 let expected = "fn main() {\n \
937 println!(\"hello, world\");\n\
939 assert!(test_format_inner(format_snippet, snippet, expected));
943 fn test_format_code_block_fail() {
945 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
946 assert!(format_code_block(code_block, &Config::default()).is_none());
950 fn test_format_code_block() {
952 let code_block = "let x=3;";
953 let expected = "let x = 3;";
954 assert!(test_format_inner(format_code_block, code_block, expected));
956 // more complex code block, taken from chains.rs.
958 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
960 chain_indent(context, shape.add_offset(parent_rewrite.len())),
961 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
963 } else if is_block_expr(context, &parent, &parent_rewrite) {
964 match context.config.indent_style() {
965 // Try to put the first child on the same line with parent's last line
966 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
967 // The parent is a block, so align the rest of the chain with the closing
969 IndentStyle::Visual => (parent_shape, false),
973 chain_indent(context, shape.add_offset(parent_rewrite.len())),
979 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
981 chain_indent(context, shape.add_offset(parent_rewrite.len())),
982 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
984 } else if is_block_expr(context, &parent, &parent_rewrite) {
985 match context.config.indent_style() {
986 // Try to put the first child on the same line with parent's last line
987 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
988 // The parent is a block, so align the rest of the chain with the closing
990 IndentStyle::Visual => (parent_shape, false),
994 chain_indent(context, shape.add_offset(parent_rewrite.len())),
998 assert!(test_format_inner(format_code_block, code_block, expected));