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(tool_attributes)]
12 #![feature(decl_macro)]
13 #![allow(unused_attributes)]
14 #![feature(type_ascription)]
15 #![feature(unicode_internals)]
16 #![feature(extern_prelude)]
19 extern crate derive_new;
22 extern crate itertools;
25 extern crate lazy_static;
29 extern crate rustc_target;
32 extern crate serde_derive;
33 extern crate serde_json;
36 extern crate unicode_segmentation;
38 use std::cell::RefCell;
39 use std::collections::HashMap;
41 use std::io::{self, Write};
42 use std::panic::{catch_unwind, AssertUnwindSafe};
43 use std::path::PathBuf;
45 use std::time::Duration;
48 use syntax::codemap::{CodeMap, FilePathMapping, Span};
49 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
50 use syntax::errors::{DiagnosticBuilder, Handler};
51 use syntax::parse::{self, ParseSess};
53 use comment::{CharClasses, FullCodeCharKind, LineClasses};
55 use issues::{BadIssueSeeker, Issue};
57 use visitor::{FmtVisitor, SnippetProvider};
59 pub use checkstyle::{footer as checkstyle_footer, header as checkstyle_header};
60 pub use config::summary::Summary;
62 load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, Verbosity,
64 pub use utils::use_colored_tty;
71 pub(crate) mod checkstyle;
73 pub(crate) mod codemap;
75 pub(crate) mod config;
77 pub(crate) mod filemap;
85 pub(crate) mod modules;
90 pub(crate) mod rustfmt_diff;
98 pub(crate) mod visitor;
100 // A map of the files of a crate, with their new content
101 pub(crate) type FileMap = Vec<FileRecord>;
103 pub(crate) type FileRecord = (FileName, String);
105 #[derive(Fail, Debug)]
107 // Line has exceeded character limit (found, maximum)
109 display = "line formatted, but exceeded maximum width \
110 (maximum: {} (see `max_width` option), found: {})",
114 LineOverflow(usize, usize),
115 // Line ends in whitespace
116 #[fail(display = "left behind trailing whitespace")]
118 // TODO or FIXME item without an issue number
119 #[fail(display = "found {}", _0)]
121 // License check has failed
122 #[fail(display = "license check failed")]
124 // Used deprecated skip attribute
125 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
127 // Used a rustfmt:: attribute other than skip
128 #[fail(display = "invalid attribute")]
130 #[fail(display = "io error: {}", _0)]
132 #[fail(display = "Version mismatch")]
136 impl From<io::Error> for ErrorKind {
137 fn from(e: io::Error) -> ErrorKind {
138 ErrorKind::IoError(e)
142 struct FormattingError {
150 impl FormattingError {
151 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
153 line: codemap.lookup_char_pos(span.lo()).line,
158 .span_to_lines(*span)
162 .get_line(fl.lines[0].line_index)
163 .map(|l| l.into_owned())
165 .unwrap_or_else(|| String::new()),
168 fn msg_prefix(&self) -> &str {
170 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace | ErrorKind::IoError(_) => {
173 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
174 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
178 fn msg_suffix(&self) -> &str {
179 if self.is_comment || self.is_string {
180 "set `error_on_unformatted = false` to suppress \
181 the warning against comments or string literals\n"
188 fn format_len(&self) -> (usize, usize) {
190 ErrorKind::LineOverflow(found, max) => (max, found - max),
191 ErrorKind::TrailingWhitespace | ErrorKind::DeprecatedAttr | ErrorKind::BadAttr => {
192 let trailing_ws_start = self
194 .rfind(|c: char| !c.is_whitespace())
199 self.line_buffer.len() - trailing_ws_start,
208 pub struct FormatReport {
209 // Maps stringified file paths to their associated formatting errors.
210 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
213 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
215 #[derive(Default, Debug)]
216 struct ReportedErrors {
217 has_operational_errors: bool,
218 has_check_errors: bool,
222 fn new() -> FormatReport {
224 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
228 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
229 self.track_errors(&v);
234 .and_modify(|fe| fe.append(&mut v))
238 fn track_errors(&self, new_errors: &[FormattingError]) {
239 let errs = &mut self.internal.borrow_mut().1;
240 if errs.has_operational_errors && errs.has_check_errors {
243 for err in new_errors {
245 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
246 errs.has_operational_errors = true;
248 ErrorKind::BadIssue(_)
249 | ErrorKind::LicenseCheck
250 | ErrorKind::DeprecatedAttr
252 | ErrorKind::VersionMismatch => {
253 errs.has_check_errors = true;
260 fn warning_count(&self) -> usize {
265 .map(|(_, errors)| errors.len())
269 pub fn has_warnings(&self) -> bool {
270 self.warning_count() > 0
275 mut t: Box<term::Terminal<Output = io::Stderr>>,
276 ) -> Result<(), term::Error> {
277 for (file, errors) in &self.internal.borrow().0 {
278 for error in errors {
279 let prefix_space_len = error.line.to_string().len();
280 let prefix_spaces = " ".repeat(1 + prefix_space_len);
282 // First line: the overview of error
283 t.fg(term::color::RED)?;
284 t.attr(term::Attr::Bold)?;
285 write!(t, "{} ", error.msg_prefix())?;
287 t.attr(term::Attr::Bold)?;
288 writeln!(t, "{}", error.kind)?;
290 // Second line: file info
291 write!(t, "{}--> ", &prefix_spaces[1..])?;
293 writeln!(t, "{}:{}", file, error.line)?;
295 // Third to fifth lines: show the line which triggered error, if available.
296 if !error.line_buffer.is_empty() {
297 let (space_len, target_len) = error.format_len();
298 t.attr(term::Attr::Bold)?;
299 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
301 writeln!(t, "{}", error.line_buffer)?;
302 t.attr(term::Attr::Bold)?;
303 write!(t, "{}| ", prefix_spaces)?;
304 t.fg(term::color::RED)?;
305 writeln!(t, "{}", target_str(space_len, target_len))?;
309 // The last line: show note if available.
310 let msg_suffix = error.msg_suffix();
311 if !msg_suffix.is_empty() {
312 t.attr(term::Attr::Bold)?;
313 write!(t, "{}= note: ", prefix_spaces)?;
315 writeln!(t, "{}", error.msg_suffix())?;
323 if !self.internal.borrow().0.is_empty() {
324 t.attr(term::Attr::Bold)?;
325 write!(t, "warning: ")?;
329 "rustfmt may have failed to format. See previous {} errors.\n\n",
330 self.warning_count(),
338 fn target_str(space_len: usize, target_len: usize) -> String {
339 let empty_line = " ".repeat(space_len);
340 let overflowed = "^".repeat(target_len);
341 empty_line + &overflowed
344 impl fmt::Display for FormatReport {
345 // Prints all the formatting errors.
346 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
347 for (file, errors) in &self.internal.borrow().0 {
348 for error in errors {
349 let prefix_space_len = error.line.to_string().len();
350 let prefix_spaces = " ".repeat(1 + prefix_space_len);
352 let error_line_buffer = if error.line_buffer.is_empty() {
355 let (space_len, target_len) = error.format_len();
357 "{}|\n{} | {}\n{}| {}",
362 target_str(space_len, target_len)
366 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
367 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
368 let msg_suffix = error.msg_suffix();
369 let note = if msg_suffix.is_empty() {
372 format!("{}note= ", prefix_spaces)
386 if !self.internal.borrow().0.is_empty() {
389 "warning: rustfmt may have failed to format. See previous {} errors.",
390 self.warning_count(),
397 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
401 if config.verbose() == Verbosity::Verbose && path != &FileName::Stdin {
406 // Formatting which depends on the AST.
409 parse_session: &mut ParseSess,
410 main_file: &FileName,
412 report: FormatReport,
414 ) -> Result<(FileMap, bool), io::Error>
416 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
418 let mut result = FileMap::new();
419 // diff mode: check if any files are differing
420 let mut has_diff = false;
422 let skip_children = config.skip_children();
423 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
424 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
427 should_emit_verbose(&path, config, || println!("Formatting {}", path));
428 let filemap = parse_session
430 .lookup_char_pos(module.inner.lo())
432 let big_snippet = filemap.src.as_ref().unwrap();
433 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
435 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
436 // Format inner attributes if available.
437 if !krate.attrs.is_empty() && path == *main_file {
438 visitor.skip_empty_lines(filemap.end_pos);
439 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
440 visitor.push_rewrite(module.inner, None);
442 visitor.format_separate_mod(module, &*filemap);
445 visitor.last_pos = filemap.start_pos;
446 visitor.skip_empty_lines(filemap.end_pos);
447 visitor.format_separate_mod(module, &*filemap);
452 ::utils::count_newlines(&visitor.buffer)
455 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
456 Ok(result) => result,
458 // Create a new error with path_str to help users see which files failed
459 let err_msg = format!("{}: {}", path, e);
460 return Err(io::Error::new(e.kind(), err_msg));
464 result.push((path.clone(), visitor.buffer));
467 Ok((result, has_diff))
470 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
471 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
474 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
477 fn should_report_error(
479 char_kind: FullCodeCharKind,
481 error_kind: &ErrorKind,
483 let allow_error_report = if char_kind.is_comment() || is_string {
484 config.error_on_unformatted()
490 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
491 ErrorKind::TrailingWhitespace => allow_error_report,
496 // Formatting done on a char by char or line by line basis.
497 // FIXME(#20) other stuff for parity with make tidy
501 skipped_range: &[(usize, usize)],
503 report: &FormatReport,
505 let mut trims = vec![];
506 let mut last_wspace: Option<usize> = None;
507 let mut line_len = 0;
508 let mut cur_line = 1;
509 let mut newline_count = 0;
510 let mut errors = vec![];
511 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
512 let mut line_buffer = String::with_capacity(config.max_width() * 2);
513 let mut is_string = false; // true if the current line contains a string literal.
514 let mut format_line = config.file_lines().contains_line(name, cur_line);
515 let allow_issue_seek = !issue_seeker.is_disabled();
518 if let Some(ref license_template) = config.license_template {
519 if !license_template.is_match(text) {
520 errors.push(FormattingError {
522 kind: ErrorKind::LicenseCheck,
525 line_buffer: String::new(),
530 // Iterate over the chars in the file map.
531 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
536 if allow_issue_seek && format_line {
537 // Add warnings for bad todos/ fixmes
538 if let Some(issue) = issue_seeker.inspect(c) {
539 errors.push(FormattingError {
541 kind: ErrorKind::BadIssue(issue),
544 line_buffer: String::new(),
551 // Check for (and record) trailing whitespace.
552 if let Some(..) = last_wspace {
553 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
555 trims.push((cur_line, kind, line_buffer.clone()));
560 // Check for any line width errors we couldn't correct.
561 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
562 if line_len > config.max_width()
563 && !is_skipped_line(cur_line, skipped_range)
564 && should_report_error(config, kind, is_string, &error_kind)
566 errors.push(FormattingError {
569 is_comment: kind.is_comment(),
571 line_buffer: line_buffer.clone(),
578 format_line = config.file_lines().contains_line(name, cur_line);
585 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
586 if c.is_whitespace() {
587 if last_wspace.is_none() {
588 last_wspace = Some(b);
594 if kind.is_string() {
600 if newline_count > 1 {
601 debug!("track truncate: {} {}", text.len(), newline_count);
602 let line = text.len() - newline_count + 1;
606 for &(l, kind, ref b) in &trims {
607 if !is_skipped_line(l, skipped_range) {
608 errors.push(FormattingError {
610 kind: ErrorKind::TrailingWhitespace,
611 is_comment: kind.is_comment(),
612 is_string: kind.is_string(),
613 line_buffer: b.clone(),
618 report.append(name.clone(), errors);
621 fn parse_input<'sess>(
623 parse_session: &'sess ParseSess,
625 ) -> Result<ast::Crate, ParseError<'sess>> {
626 let mut parser = match input {
627 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
628 Input::Text(text) => parse::new_parser_from_source_str(
630 syntax::codemap::FileName::Custom("stdin".to_owned()),
635 parser.cfg_mods = false;
636 if config.skip_children() {
637 parser.recurse_into_file_modules = false;
640 let mut parser = AssertUnwindSafe(parser);
641 let result = catch_unwind(move || parser.0.parse_crate_mod());
645 if parse_session.span_diagnostic.has_errors() {
646 // Bail out if the parser recovered from an error.
647 Err(ParseError::Recovered)
652 Ok(Err(e)) => Err(ParseError::Error(e)),
653 Err(_) => Err(ParseError::Panic),
657 /// All the ways that parsing can fail.
658 enum ParseError<'sess> {
659 /// There was an error, but the parser recovered.
661 /// There was an error (supplied) and parsing failed.
662 Error(DiagnosticBuilder<'sess>),
663 /// The parser panicked.
667 /// Format the given snippet. The snippet is expected to be *complete* code.
668 /// When we cannot parse the given snippet, this function returns `None`.
669 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
670 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
671 let input = Input::Text(snippet.into());
672 let mut config = config.clone();
673 config.set().emit_mode(config::EmitMode::Stdout);
674 config.set().verbose(Verbosity::Quiet);
675 config.set().hide_parse_errors(true);
676 match format_input(input, &config, Some(&mut out)) {
677 // `format_input()` returns an empty string on parsing error.
678 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
679 Ok(..) => String::from_utf8(out).ok(),
684 const FN_MAIN_PREFIX: &str = "fn main() {\n";
686 fn enclose_in_main_block(s: &str, config: &Config) -> String {
687 let indent = Indent::from_width(config, config.tab_spaces());
688 let mut result = String::with_capacity(s.len() * 2);
689 result.push_str(FN_MAIN_PREFIX);
690 let mut need_indent = true;
691 for (kind, line) in LineClasses::new(s) {
693 result.push_str(&indent.to_string(config));
695 result.push_str(&line);
697 need_indent = !kind.is_string() || line.ends_with('\\');
703 /// Format the given code block. Mainly targeted for code block in comment.
704 /// The code block may be incomplete (i.e. parser may be unable to parse it).
705 /// To avoid panic in parser, we wrap the code block with a dummy function.
706 /// The returned code block does *not* end with newline.
707 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
708 // Wrap the given code block with `fn main()` if it does not have one.
709 let snippet = enclose_in_main_block(code_snippet, config);
710 let mut result = String::with_capacity(snippet.len());
711 let mut is_first = true;
713 // Trim "fn main() {" on the first line and "}" on the last line,
714 // then unindent the whole code block.
715 let formatted = format_snippet(&snippet, config)?;
717 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
718 let mut is_indented = true;
719 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
725 let trimmed_line = if !is_indented {
727 } else if line.len() > config.max_width() {
728 // If there are lines that are larger than max width, we cannot tell
729 // whether we have succeeded but have some comments or strings that
730 // are too long, or we have failed to format code block. We will be
731 // conservative and just return `None` in this case.
733 } else if line.len() > config.tab_spaces() {
734 // Make sure that the line has leading whitespaces.
735 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
736 if line.starts_with(indent_str.as_ref()) {
737 let offset = if config.hard_tabs() {
749 result.push_str(trimmed_line);
750 is_indented = !kind.is_string() || line.ends_with('\\');
761 pub fn format_input<T: Write>(
765 ) -> Result<(Summary, FormatReport), (ErrorKind, Summary)> {
766 if !config.version_meets_requirement() {
767 return Err((ErrorKind::VersionMismatch, Summary::default()));
770 syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| (tup.0, tup.2))
773 fn format_input_inner<T: Write>(
776 mut out: Option<&mut T>,
777 ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
778 let mut summary = Summary::default();
779 if config.disable_all_formatting() {
780 // When the input is from stdin, echo back the input.
781 if let Input::Text(ref buf) = input {
782 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
783 return Err((From::from(e), summary));
786 return Ok((summary, FileMap::new(), FormatReport::new()));
788 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
790 let tty_handler = if config.hide_parse_errors() {
791 let silent_emitter = Box::new(EmitterWriter::new(
792 Box::new(Vec::new()),
793 Some(codemap.clone()),
797 Handler::with_emitter(true, false, silent_emitter)
799 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
800 let color_cfg = if supports_color {
805 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
807 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
809 let main_file = match input {
810 Input::File(ref file) => FileName::Real(file.clone()),
811 Input::Text(..) => FileName::Stdin,
814 let krate = match parse_input(input, &parse_session, config) {
818 ParseError::Error(mut diagnostic) => diagnostic.emit(),
819 ParseError::Panic => {
820 // Note that if you see this message and want more information,
821 // then go to `parse_input` and run the parse function without
822 // `catch_unwind` so rustfmt panics and you can get a backtrace.
823 should_emit_verbose(&main_file, config, || {
824 println!("The Rust parser panicked")
827 ParseError::Recovered => {}
829 summary.add_parsing_error();
830 return Ok((summary, FileMap::new(), FormatReport::new()));
834 summary.mark_parse_time();
836 // Suppress error output after parsing.
837 let silent_emitter = Box::new(EmitterWriter::new(
838 Box::new(Vec::new()),
839 Some(codemap.clone()),
843 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
845 let report = FormatReport::new();
847 let format_result = format_ast(
853 |file_name, file, skipped_range, report| {
854 // For some reason, the codemap does not include terminating
855 // newlines so we must add one on for each file. This is sad.
856 filemap::append_newline(file);
858 format_lines(file, file_name, skipped_range, config, report);
860 if let Some(ref mut out) = out {
861 return filemap::write_file(file, file_name, out, config);
867 summary.mark_format_time();
869 should_emit_verbose(&main_file, config, || {
870 fn duration_to_f32(d: Duration) -> f32 {
871 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
875 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
876 duration_to_f32(summary.get_parse_time().unwrap()),
877 duration_to_f32(summary.get_format_time().unwrap()),
882 let report_errs = &report.internal.borrow().1;
883 if report_errs.has_check_errors {
884 summary.add_check_error();
886 if report_errs.has_operational_errors {
887 summary.add_operational_error();
891 match format_result {
892 Ok((file_map, has_diff)) => {
893 if report.has_warnings() {
894 summary.add_formatting_error();
901 Ok((summary, file_map, report))
903 Err(e) => Err((From::from(e), summary)),
907 /// A single span of changed lines, with 0 or more removed lines
908 /// and a vector of 0 or more inserted lines.
909 #[derive(Debug, PartialEq, Eq)]
910 struct ModifiedChunk {
911 /// The first to be removed from the original text
912 pub line_number_orig: u32,
913 /// The number of lines which have been replaced
914 pub lines_removed: u32,
916 pub lines: Vec<String>,
919 /// Set of changed sections of a file.
920 #[derive(Debug, PartialEq, Eq)]
921 struct ModifiedLines {
922 /// The set of changed chunks.
923 pub chunks: Vec<ModifiedChunk>,
926 /// Format a file and return a `ModifiedLines` data structure describing
927 /// the changed ranges of lines.
929 fn get_modified_lines(
932 ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
933 use std::io::BufRead;
935 let mut data = Vec::new();
937 let mut config = config.clone();
938 config.set().emit_mode(config::EmitMode::ModifiedLines);
939 format_input(input, &config, Some(&mut data))?;
941 let mut lines = data.lines();
942 let mut chunks = Vec::new();
943 while let Some(Ok(header)) = lines.next() {
944 // Parse the header line
945 let values: Vec<_> = header
947 .map(|s| s.parse::<u32>().unwrap())
949 assert_eq!(values.len(), 3);
950 let line_number_orig = values[0];
951 let lines_removed = values[1];
952 let num_added = values[2];
953 let mut added_lines = Vec::new();
954 for _ in 0..num_added {
955 added_lines.push(lines.next().unwrap().unwrap());
957 chunks.push(ModifiedChunk {
963 Ok(ModifiedLines { chunks })
968 use super::{format_code_block, format_snippet, Config};
971 fn test_no_panic_on_format_snippet_and_format_code_block() {
972 // `format_snippet()` and `format_code_block()` should not panic
973 // even when we cannot parse the given snippet.
975 assert!(format_snippet(snippet, &Config::default()).is_none());
976 assert!(format_code_block(snippet, &Config::default()).is_none());
979 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
981 F: Fn(&str, &Config) -> Option<String>,
983 let output = formatter(input, &Config::default());
984 output.is_some() && output.unwrap() == expected
988 fn test_format_snippet() {
989 let snippet = "fn main() { println!(\"hello, world\"); }";
990 let expected = "fn main() {\n \
991 println!(\"hello, world\");\n\
993 assert!(test_format_inner(format_snippet, snippet, expected));
997 fn test_format_code_block_fail() {
999 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1000 assert!(format_code_block(code_block, &Config::default()).is_none());
1004 fn test_format_code_block() {
1005 // simple code block
1006 let code_block = "let x=3;";
1007 let expected = "let x = 3;";
1008 assert!(test_format_inner(format_code_block, code_block, expected));
1010 // more complex code block, taken from chains.rs.
1012 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1014 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1015 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1017 } else if is_block_expr(context, &parent, &parent_rewrite) {
1018 match context.config.indent_style() {
1019 // Try to put the first child on the same line with parent's last line
1020 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1021 // The parent is a block, so align the rest of the chain with the closing
1023 IndentStyle::Visual => (parent_shape, false),
1027 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1033 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1035 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1036 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1038 } else if is_block_expr(context, &parent, &parent_rewrite) {
1039 match context.config.indent_style() {
1040 // Try to put the first child on the same line with parent's last line
1041 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1042 // The parent is a block, so align the rest of the chain with the closing
1044 IndentStyle::Visual => (parent_shape, false),
1048 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1052 assert!(test_format_inner(format_code_block, code_block, expected));