1 // Copyright 2015-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![feature(custom_attribute)]
12 #![feature(decl_macro)]
13 // FIXME(cramertj) remove after match_default_bindings merges
14 #![allow(stable_features)]
15 #![allow(unused_attributes)]
16 #![feature(match_default_bindings)]
17 #![feature(type_ascription)]
18 #![feature(unicode_internals)]
21 extern crate derive_new;
26 extern crate itertools;
29 extern crate lazy_static;
33 extern crate rustc_target;
36 extern crate serde_derive;
37 extern crate serde_json;
41 extern crate unicode_segmentation;
43 use std::collections::HashMap;
45 use std::io::{self, stdout, Write};
46 use std::panic::{catch_unwind, AssertUnwindSafe};
47 use std::path::PathBuf;
49 use std::time::Duration;
52 pub use syntax::codemap::FileName;
53 use syntax::codemap::{CodeMap, FilePathMapping};
54 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
55 use syntax::errors::{DiagnosticBuilder, Handler};
56 use syntax::parse::{self, ParseSess};
58 use comment::{CharClasses, FullCodeCharKind, LineClasses};
60 use issues::{BadIssueSeeker, Issue};
62 use utils::use_colored_tty;
63 use visitor::{FmtVisitor, SnippetProvider};
65 pub use config::options::CliOptions;
66 pub use config::summary::Summary;
67 pub use config::{file_lines, load_config, Config, WriteMode};
69 pub type FmtResult<T> = std::result::Result<T, failure::Error>;
71 pub const WRITE_MODE_LIST: &str =
72 "[replace|overwrite|display|plain|diff|coverage|checkstyle|check]";
79 pub(crate) mod checkstyle;
81 pub(crate) mod codemap;
83 pub(crate) mod config;
85 pub(crate) mod filemap;
93 pub(crate) mod modules;
98 pub(crate) mod rustfmt_diff;
106 pub(crate) mod visitor;
108 const STDIN: &str = "<stdin>";
110 // A map of the files of a crate, with their new content
111 pub(crate) type FileMap = Vec<FileRecord>;
113 pub(crate) type FileRecord = (FileName, String);
115 #[derive(Fail, Debug, Clone, Copy)]
117 // Line has exceeded character limit (found, maximum)
119 display = "line formatted, but exceeded maximum width \
120 (maximum: {} (see `max_width` option), found: {})",
124 LineOverflow(usize, usize),
125 // Line ends in whitespace
126 #[fail(display = "left behind trailing whitespace")]
128 // TODO or FIXME item without an issue number
129 #[fail(display = "found {}", _0)]
131 // License check has failed
132 #[fail(display = "license check failed")]
136 // Formatting errors that are identified *after* rustfmt has run.
137 struct FormattingError {
145 impl FormattingError {
146 fn msg_prefix(&self) -> &str {
148 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "internal error:",
149 ErrorKind::LicenseCheck => "error:",
150 ErrorKind::BadIssue(_) => "warning:",
154 fn msg_suffix(&self) -> &str {
155 if self.is_comment || self.is_string {
156 "set `error_on_unformatted = false` to suppress \
157 the warning against comments or string literals\n"
164 fn format_len(&self) -> (usize, usize) {
166 ErrorKind::LineOverflow(found, max) => (max, found - max),
167 ErrorKind::TrailingWhitespace => {
168 let trailing_ws_start = self.line_buffer
169 .rfind(|c: char| !c.is_whitespace())
174 self.line_buffer.len() - trailing_ws_start,
182 pub struct FormatReport {
183 // Maps stringified file paths to their associated formatting errors.
184 file_error_map: HashMap<FileName, Vec<FormattingError>>,
188 fn new() -> FormatReport {
190 file_error_map: HashMap::new(),
194 fn warning_count(&self) -> usize {
197 .map(|(_, errors)| errors.len())
201 fn has_warnings(&self) -> bool {
202 self.warning_count() > 0
205 fn print_warnings_fancy(
207 mut t: Box<term::Terminal<Output = io::Stderr>>,
208 ) -> Result<(), term::Error> {
209 for (file, errors) in &self.file_error_map {
210 for error in errors {
211 let prefix_space_len = error.line.to_string().len();
212 let prefix_spaces = " ".repeat(1 + prefix_space_len);
214 // First line: the overview of error
215 t.fg(term::color::RED)?;
216 t.attr(term::Attr::Bold)?;
217 write!(t, "{} ", error.msg_prefix())?;
219 t.attr(term::Attr::Bold)?;
220 writeln!(t, "{}", error.kind)?;
222 // Second line: file info
223 write!(t, "{}--> ", &prefix_spaces[1..])?;
225 writeln!(t, "{}:{}", file, error.line)?;
227 // Third to fifth lines: show the line which triggered error, if available.
228 if !error.line_buffer.is_empty() {
229 let (space_len, target_len) = error.format_len();
230 t.attr(term::Attr::Bold)?;
231 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
233 writeln!(t, "{}", error.line_buffer)?;
234 t.attr(term::Attr::Bold)?;
235 write!(t, "{}| ", prefix_spaces)?;
236 t.fg(term::color::RED)?;
237 writeln!(t, "{}", target_str(space_len, target_len))?;
241 // The last line: show note if available.
242 let msg_suffix = error.msg_suffix();
243 if !msg_suffix.is_empty() {
244 t.attr(term::Attr::Bold)?;
245 write!(t, "{}= note: ", prefix_spaces)?;
247 writeln!(t, "{}", error.msg_suffix())?;
255 if !self.file_error_map.is_empty() {
256 t.attr(term::Attr::Bold)?;
257 write!(t, "warning: ")?;
261 "rustfmt may have failed to format. See previous {} errors.\n\n",
262 self.warning_count(),
270 fn target_str(space_len: usize, target_len: usize) -> String {
271 let empty_line = " ".repeat(space_len);
272 let overflowed = "^".repeat(target_len);
273 empty_line + &overflowed
276 impl fmt::Display for FormatReport {
277 // Prints all the formatting errors.
278 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
279 for (file, errors) in &self.file_error_map {
280 for error in errors {
281 let prefix_space_len = error.line.to_string().len();
282 let prefix_spaces = " ".repeat(1 + prefix_space_len);
284 let error_line_buffer = if error.line_buffer.is_empty() {
287 let (space_len, target_len) = error.format_len();
289 "{}|\n{} | {}\n{}| {}",
294 target_str(space_len, target_len)
298 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
299 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
300 let msg_suffix = error.msg_suffix();
301 let note = if msg_suffix.is_empty() {
304 format!("{}note= ", prefix_spaces)
318 if !self.file_error_map.is_empty() {
321 "warning: rustfmt may have failed to format. See previous {} errors.",
322 self.warning_count(),
329 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
333 if config.verbose() && path.to_string() != STDIN {
338 // Formatting which depends on the AST.
341 parse_session: &mut ParseSess,
342 main_file: &FileName,
345 ) -> Result<(FileMap, bool), io::Error>
347 F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
349 let mut result = FileMap::new();
350 // diff mode: check if any files are differing
351 let mut has_diff = false;
353 // We always skip children for the "Plain" write mode, since there is
354 // nothing to distinguish the nested module contents.
355 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
356 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
357 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
360 should_emit_verbose(&path, config, || println!("Formatting {}", path));
361 let filemap = parse_session
363 .lookup_char_pos(module.inner.lo())
365 let big_snippet = filemap.src.as_ref().unwrap();
366 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
367 let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
368 // Format inner attributes if available.
369 if !krate.attrs.is_empty() && path == *main_file {
370 visitor.skip_empty_lines(filemap.end_pos);
371 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
372 visitor.push_rewrite(module.inner, None);
374 visitor.format_separate_mod(module, &*filemap);
377 visitor.last_pos = filemap.start_pos;
378 visitor.skip_empty_lines(filemap.end_pos);
379 visitor.format_separate_mod(module, &*filemap);
384 ::utils::count_newlines(&visitor.buffer)
387 let filename = path.clone();
388 has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
389 Ok(result) => result,
391 // Create a new error with path_str to help users see which files failed
392 let err_msg = format!("{}: {}", path, e);
393 return Err(io::Error::new(e.kind(), err_msg));
397 result.push((filename, visitor.buffer));
400 Ok((result, has_diff))
403 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
404 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
407 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
410 fn should_report_error(
412 char_kind: FullCodeCharKind,
414 error_kind: ErrorKind,
416 let allow_error_report = if char_kind.is_comment() || is_string {
417 config.error_on_unformatted()
423 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
424 ErrorKind::TrailingWhitespace => allow_error_report,
429 // Formatting done on a char by char or line by line basis.
430 // FIXME(#20) other stuff for parity with make tidy
434 skipped_range: &[(usize, usize)],
436 report: &mut FormatReport,
438 let mut trims = vec![];
439 let mut last_wspace: Option<usize> = None;
440 let mut line_len = 0;
441 let mut cur_line = 1;
442 let mut newline_count = 0;
443 let mut errors = vec![];
444 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
445 let mut line_buffer = String::with_capacity(config.max_width() * 2);
446 let mut is_string = false; // true if the current line contains a string literal.
447 let mut format_line = config.file_lines().contains_line(name, cur_line);
448 let allow_issue_seek = !issue_seeker.is_disabled();
451 if let Some(ref license_template) = config.license_template {
452 if !license_template.is_match(text) {
453 errors.push(FormattingError {
455 kind: ErrorKind::LicenseCheck,
458 line_buffer: String::new(),
463 // Iterate over the chars in the file map.
464 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
469 if allow_issue_seek && format_line {
470 // Add warnings for bad todos/ fixmes
471 if let Some(issue) = issue_seeker.inspect(c) {
472 errors.push(FormattingError {
474 kind: ErrorKind::BadIssue(issue),
477 line_buffer: String::new(),
484 // Check for (and record) trailing whitespace.
485 if let Some(..) = last_wspace {
486 if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
487 trims.push((cur_line, kind, line_buffer.clone()));
492 // Check for any line width errors we couldn't correct.
493 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
494 if line_len > config.max_width()
495 && !is_skipped_line(cur_line, skipped_range)
496 && should_report_error(config, kind, is_string, error_kind)
498 errors.push(FormattingError {
501 is_comment: kind.is_comment(),
503 line_buffer: line_buffer.clone(),
510 format_line = config.file_lines().contains_line(name, cur_line);
517 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
518 if c.is_whitespace() {
519 if last_wspace.is_none() {
520 last_wspace = Some(b);
526 if kind.is_string() {
532 if newline_count > 1 {
533 debug!("track truncate: {} {}", text.len(), newline_count);
534 let line = text.len() - newline_count + 1;
538 for &(l, kind, ref b) in &trims {
539 if !is_skipped_line(l, skipped_range) {
540 errors.push(FormattingError {
542 kind: ErrorKind::TrailingWhitespace,
543 is_comment: kind.is_comment(),
544 is_string: kind.is_string(),
545 line_buffer: b.clone(),
550 report.file_error_map.insert(name.clone(), errors);
553 fn parse_input<'sess>(
555 parse_session: &'sess ParseSess,
557 ) -> Result<ast::Crate, ParseError<'sess>> {
558 let mut parser = match input {
559 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
560 Input::Text(text) => parse::new_parser_from_source_str(
562 FileName::Custom("stdin".to_owned()),
567 parser.cfg_mods = false;
568 if config.skip_children() {
569 parser.recurse_into_file_modules = false;
572 let mut parser = AssertUnwindSafe(parser);
573 let result = catch_unwind(move || parser.0.parse_crate_mod());
577 if parse_session.span_diagnostic.has_errors() {
578 // Bail out if the parser recovered from an error.
579 Err(ParseError::Recovered)
584 Ok(Err(e)) => Err(ParseError::Error(e)),
585 Err(_) => Err(ParseError::Panic),
589 /// All the ways that parsing can fail.
590 enum ParseError<'sess> {
591 /// There was an error, but the parser recovered.
593 /// There was an error (supplied) and parsing failed.
594 Error(DiagnosticBuilder<'sess>),
595 /// The parser panicked.
599 /// Format the given snippet. The snippet is expected to be *complete* code.
600 /// When we cannot parse the given snippet, this function returns `None`.
601 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
602 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
603 let input = Input::Text(snippet.into());
604 let mut config = config.clone();
605 config.set().write_mode(config::WriteMode::Plain);
606 config.set().hide_parse_errors(true);
607 match format_input(input, &config, Some(&mut out)) {
608 // `format_input()` returns an empty string on parsing error.
609 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
610 Ok(..) => String::from_utf8(out).ok(),
615 const FN_MAIN_PREFIX: &str = "fn main() {\n";
617 fn enclose_in_main_block(s: &str, config: &Config) -> String {
618 let indent = Indent::from_width(config, config.tab_spaces());
619 let mut result = String::with_capacity(s.len() * 2);
620 result.push_str(FN_MAIN_PREFIX);
621 let mut need_indent = true;
622 for (kind, line) in LineClasses::new(s) {
624 result.push_str(&indent.to_string(config));
626 result.push_str(&line);
628 need_indent = !kind.is_string() || line.ends_with('\\');
634 /// Format the given code block. Mainly targeted for code block in comment.
635 /// The code block may be incomplete (i.e. parser may be unable to parse it).
636 /// To avoid panic in parser, we wrap the code block with a dummy function.
637 /// The returned code block does *not* end with newline.
638 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
639 // Wrap the given code block with `fn main()` if it does not have one.
640 let snippet = enclose_in_main_block(code_snippet, config);
641 let mut result = String::with_capacity(snippet.len());
642 let mut is_first = true;
644 // Trim "fn main() {" on the first line and "}" on the last line,
645 // then unindent the whole code block.
646 let formatted = format_snippet(&snippet, config)?;
648 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
649 let mut is_indented = true;
650 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
656 let trimmed_line = if !is_indented {
658 } else if line.len() > config.max_width() {
659 // If there are lines that are larger than max width, we cannot tell
660 // whether we have succeeded but have some comments or strings that
661 // are too long, or we have failed to format code block. We will be
662 // conservative and just return `None` in this case.
664 } else if line.len() > config.tab_spaces() {
665 // Make sure that the line has leading whitespaces.
666 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
667 if line.starts_with(indent_str.as_ref()) {
668 let offset = if config.hard_tabs() {
680 result.push_str(trimmed_line);
681 is_indented = !kind.is_string() || line.ends_with('\\');
686 pub fn format_input<T: Write>(
690 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
691 syntax::with_globals(|| format_input_inner(input, config, out))
694 fn format_input_inner<T: Write>(
697 mut out: Option<&mut T>,
698 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
699 let mut summary = Summary::default();
700 if config.disable_all_formatting() {
701 // When the input is from stdin, echo back the input.
702 if let Input::Text(ref buf) = input {
703 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
704 return Err((e, summary));
707 return Ok((summary, FileMap::new(), FormatReport::new()));
709 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
711 let tty_handler = if config.hide_parse_errors() {
712 let silent_emitter = Box::new(EmitterWriter::new(
713 Box::new(Vec::new()),
714 Some(codemap.clone()),
718 Handler::with_emitter(true, false, silent_emitter)
720 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
721 let color_cfg = if supports_color {
726 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
728 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
730 let main_file = match input {
731 Input::File(ref file) => FileName::Real(file.clone()),
732 Input::Text(..) => FileName::Custom("stdin".to_owned()),
735 let krate = match parse_input(input, &parse_session, config) {
739 ParseError::Error(mut diagnostic) => diagnostic.emit(),
740 ParseError::Panic => {
741 // Note that if you see this message and want more information,
742 // then go to `parse_input` and run the parse function without
743 // `catch_unwind` so rustfmt panics and you can get a backtrace.
744 should_emit_verbose(&main_file, config, || {
745 println!("The Rust parser panicked")
748 ParseError::Recovered => {}
750 summary.add_parsing_error();
751 return Ok((summary, FileMap::new(), FormatReport::new()));
755 summary.mark_parse_time();
757 // Suppress error output after parsing.
758 let silent_emitter = Box::new(EmitterWriter::new(
759 Box::new(Vec::new()),
760 Some(codemap.clone()),
764 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
766 let mut report = FormatReport::new();
768 let format_result = format_ast(
773 |file_name, file, skipped_range| {
774 // For some reason, the codemap does not include terminating
775 // newlines so we must add one on for each file. This is sad.
776 filemap::append_newline(file);
778 format_lines(file, file_name, skipped_range, config, &mut report);
780 if let Some(ref mut out) = out {
781 return filemap::write_file(file, file_name, out, config);
787 summary.mark_format_time();
789 should_emit_verbose(&main_file, config, || {
790 fn duration_to_f32(d: Duration) -> f32 {
791 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
795 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
796 duration_to_f32(summary.get_parse_time().unwrap()),
797 duration_to_f32(summary.get_format_time().unwrap()),
801 match format_result {
802 Ok((file_map, has_diff)) => {
803 if report.has_warnings() {
804 summary.add_formatting_error();
811 Ok((summary, file_map, report))
813 Err(e) => Err((e, summary)),
817 /// A single span of changed lines, with 0 or more removed lines
818 /// and a vector of 0 or more inserted lines.
819 #[derive(Debug, PartialEq, Eq)]
820 struct ModifiedChunk {
821 /// The first to be removed from the original text
822 pub line_number_orig: u32,
823 /// The number of lines which have been replaced
824 pub lines_removed: u32,
826 pub lines: Vec<String>,
829 /// Set of changed sections of a file.
830 #[derive(Debug, PartialEq, Eq)]
831 struct ModifiedLines {
832 /// The set of changed chunks.
833 pub chunks: Vec<ModifiedChunk>,
836 /// The successful result of formatting via `get_modified_lines()`.
838 struct ModifiedLinesResult {
839 /// The high level summary details
840 pub summary: Summary,
841 /// The result Filemap
842 pub filemap: FileMap,
843 /// Map of formatting errors
844 pub report: FormatReport,
845 /// The sets of updated lines.
846 pub modified_lines: ModifiedLines,
849 /// Format a file and return a `ModifiedLines` data structure describing
850 /// the changed ranges of lines.
852 fn get_modified_lines(
855 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
856 use std::io::BufRead;
858 let mut data = Vec::new();
860 let mut config = config.clone();
861 config.set().write_mode(config::WriteMode::Modified);
862 let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?;
864 let mut lines = data.lines();
865 let mut chunks = Vec::new();
866 while let Some(Ok(header)) = lines.next() {
867 // Parse the header line
868 let values: Vec<_> = header
870 .map(|s| s.parse::<u32>().unwrap())
872 assert_eq!(values.len(), 3);
873 let line_number_orig = values[0];
874 let lines_removed = values[1];
875 let num_added = values[2];
876 let mut added_lines = Vec::new();
877 for _ in 0..num_added {
878 added_lines.push(lines.next().unwrap().unwrap());
880 chunks.push(ModifiedChunk {
886 Ok(ModifiedLinesResult {
890 modified_lines: ModifiedLines { chunks },
900 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
901 if !config.version_meets_requirement() {
902 return Err(format_err!("Version mismatch"));
904 let out = &mut stdout();
905 match format_input(input, config, Some(out)) {
906 Ok((summary, _, report)) => {
907 if report.has_warnings() {
908 match term::stderr() {
910 if use_colored_tty(config.color())
911 && t.supports_color()
912 && t.supports_attr(term::Attr::Bold) =>
914 match report.print_warnings_fancy(term::stderr().unwrap()) {
916 Err(..) => panic!("Unable to write to stderr: {}", report),
919 _ => eprintln!("{}", report),
925 Err((msg, mut summary)) => {
926 eprintln!("Error writing files: {}", msg);
927 summary.add_operational_error();
933 pub fn emit_pre_matter(config: &Config) -> FmtResult<()> {
934 if config.write_mode() == WriteMode::Checkstyle {
935 let mut out = &mut stdout();
936 checkstyle::output_header(&mut out)?;
941 pub fn emit_post_matter(config: &Config) -> FmtResult<()> {
942 if config.write_mode() == WriteMode::Checkstyle {
943 let mut out = &mut stdout();
944 checkstyle::output_footer(&mut out)?;
951 use super::{format_code_block, format_snippet, Config};
954 fn test_no_panic_on_format_snippet_and_format_code_block() {
955 // `format_snippet()` and `format_code_block()` should not panic
956 // even when we cannot parse the given snippet.
958 assert!(format_snippet(snippet, &Config::default()).is_none());
959 assert!(format_code_block(snippet, &Config::default()).is_none());
962 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
964 F: Fn(&str, &Config) -> Option<String>,
966 let output = formatter(input, &Config::default());
967 output.is_some() && output.unwrap() == expected
971 fn test_format_snippet() {
972 let snippet = "fn main() { println!(\"hello, world\"); }";
973 let expected = "fn main() {\n \
974 println!(\"hello, world\");\n\
976 assert!(test_format_inner(format_snippet, snippet, expected));
980 fn test_format_code_block_fail() {
982 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
983 assert!(format_code_block(code_block, &Config::default()).is_none());
987 fn test_format_code_block() {
989 let code_block = "let x=3;";
990 let expected = "let x = 3;";
991 assert!(test_format_inner(format_code_block, code_block, expected));
993 // more complex code block, taken from chains.rs.
995 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
997 chain_indent(context, shape.add_offset(parent_rewrite.len())),
998 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1000 } else if is_block_expr(context, &parent, &parent_rewrite) {
1001 match context.config.indent_style() {
1002 // Try to put the first child on the same line with parent's last line
1003 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1004 // The parent is a block, so align the rest of the chain with the closing
1006 IndentStyle::Visual => (parent_shape, false),
1010 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1016 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1018 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1019 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1021 } else if is_block_expr(context, &parent, &parent_rewrite) {
1022 match context.config.indent_style() {
1023 // Try to put the first child on the same line with parent's last line
1024 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1025 // The parent is a block, so align the rest of the chain with the closing
1027 IndentStyle::Visual => (parent_shape, false),
1031 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1035 assert!(test_format_inner(format_code_block, code_block, expected));