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;
23 extern crate itertools;
26 extern crate lazy_static;
30 extern crate rustc_target;
33 extern crate serde_derive;
34 extern crate serde_json;
37 extern crate unicode_segmentation;
39 use std::cell::RefCell;
40 use std::collections::HashMap;
42 use std::io::{self, Write};
43 use std::panic::{catch_unwind, AssertUnwindSafe};
44 use std::path::PathBuf;
46 use std::time::Duration;
49 use syntax::codemap::{CodeMap, FilePathMapping, Span};
50 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
51 use syntax::errors::{DiagnosticBuilder, Handler};
52 use syntax::parse::{self, ParseSess};
54 use comment::{CharClasses, FullCodeCharKind, LineClasses};
56 use issues::{BadIssueSeeker, Issue};
58 use visitor::{FmtVisitor, SnippetProvider};
60 pub use checkstyle::{footer as checkstyle_footer, header as checkstyle_header};
61 pub use config::summary::Summary;
63 load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, Range, Verbosity,
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 /// The various errors that can occur during formatting. Note that not all of
106 /// these can currently be propagated to clients.
107 #[derive(Fail, Debug)]
109 /// Line has exceeded character limit (found, maximum).
111 display = "line formatted, but exceeded maximum width \
112 (maximum: {} (see `max_width` option), found: {})",
116 LineOverflow(usize, usize),
117 /// Line ends in whitespace.
118 #[fail(display = "left behind trailing whitespace")]
120 /// TODO or FIXME item without an issue number.
121 #[fail(display = "found {}", _0)]
123 /// License check has failed.
124 #[fail(display = "license check failed")]
126 /// Used deprecated skip attribute.
127 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
129 /// Used a rustfmt:: attribute other than skip.
130 #[fail(display = "invalid attribute")]
132 /// An io error during reading or writing.
133 #[fail(display = "io error: {}", _0)]
135 /// The user mandated a version and the current version of Rustfmt does not
136 /// satisfy that requirement.
137 #[fail(display = "Version mismatch")]
141 impl From<io::Error> for ErrorKind {
142 fn from(e: io::Error) -> ErrorKind {
143 ErrorKind::IoError(e)
147 struct FormattingError {
155 impl FormattingError {
156 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
158 line: codemap.lookup_char_pos(span.lo()).line,
163 .span_to_lines(*span)
167 .get_line(fl.lines[0].line_index)
168 .map(|l| l.into_owned())
170 .unwrap_or_else(|| String::new()),
173 fn msg_prefix(&self) -> &str {
175 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace | ErrorKind::IoError(_) => {
178 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
179 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
183 fn msg_suffix(&self) -> &str {
184 if self.is_comment || self.is_string {
185 "set `error_on_unformatted = false` to suppress \
186 the warning against comments or string literals\n"
193 fn format_len(&self) -> (usize, usize) {
195 ErrorKind::LineOverflow(found, max) => (max, found - max),
196 ErrorKind::TrailingWhitespace | ErrorKind::DeprecatedAttr | ErrorKind::BadAttr => {
197 let trailing_ws_start = self
199 .rfind(|c: char| !c.is_whitespace())
204 self.line_buffer.len() - trailing_ws_start,
212 /// Reports on any issues that occurred during a run of Rustfmt.
214 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
216 pub struct FormatReport {
217 // Maps stringified file paths to their associated formatting errors.
218 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
221 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
223 #[derive(Default, Debug)]
224 struct ReportedErrors {
225 has_operational_errors: bool,
226 has_check_errors: bool,
230 fn new() -> FormatReport {
232 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
236 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
237 self.track_errors(&v);
242 .and_modify(|fe| fe.append(&mut v))
246 fn track_errors(&self, new_errors: &[FormattingError]) {
247 let errs = &mut self.internal.borrow_mut().1;
248 if errs.has_operational_errors && errs.has_check_errors {
251 for err in new_errors {
253 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
254 errs.has_operational_errors = true;
256 ErrorKind::BadIssue(_)
257 | ErrorKind::LicenseCheck
258 | ErrorKind::DeprecatedAttr
260 | ErrorKind::VersionMismatch => {
261 errs.has_check_errors = true;
268 fn warning_count(&self) -> usize {
273 .map(|(_, errors)| errors.len())
277 /// Whether any warnings or errors are present in the report.
278 pub fn has_warnings(&self) -> bool {
279 self.warning_count() > 0
282 /// Print the report to a terminal using colours and potentially other
286 mut t: Box<term::Terminal<Output = io::Stderr>>,
287 ) -> Result<(), term::Error> {
288 for (file, errors) in &self.internal.borrow().0 {
289 for error in errors {
290 let prefix_space_len = error.line.to_string().len();
291 let prefix_spaces = " ".repeat(1 + prefix_space_len);
293 // First line: the overview of error
294 t.fg(term::color::RED)?;
295 t.attr(term::Attr::Bold)?;
296 write!(t, "{} ", error.msg_prefix())?;
298 t.attr(term::Attr::Bold)?;
299 writeln!(t, "{}", error.kind)?;
301 // Second line: file info
302 write!(t, "{}--> ", &prefix_spaces[1..])?;
304 writeln!(t, "{}:{}", file, error.line)?;
306 // Third to fifth lines: show the line which triggered error, if available.
307 if !error.line_buffer.is_empty() {
308 let (space_len, target_len) = error.format_len();
309 t.attr(term::Attr::Bold)?;
310 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
312 writeln!(t, "{}", error.line_buffer)?;
313 t.attr(term::Attr::Bold)?;
314 write!(t, "{}| ", prefix_spaces)?;
315 t.fg(term::color::RED)?;
316 writeln!(t, "{}", target_str(space_len, target_len))?;
320 // The last line: show note if available.
321 let msg_suffix = error.msg_suffix();
322 if !msg_suffix.is_empty() {
323 t.attr(term::Attr::Bold)?;
324 write!(t, "{}= note: ", prefix_spaces)?;
326 writeln!(t, "{}", error.msg_suffix())?;
334 if !self.internal.borrow().0.is_empty() {
335 t.attr(term::Attr::Bold)?;
336 write!(t, "warning: ")?;
340 "rustfmt may have failed to format. See previous {} errors.\n\n",
341 self.warning_count(),
349 fn target_str(space_len: usize, target_len: usize) -> String {
350 let empty_line = " ".repeat(space_len);
351 let overflowed = "^".repeat(target_len);
352 empty_line + &overflowed
355 impl fmt::Display for FormatReport {
356 // Prints all the formatting errors.
357 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
358 for (file, errors) in &self.internal.borrow().0 {
359 for error in errors {
360 let prefix_space_len = error.line.to_string().len();
361 let prefix_spaces = " ".repeat(1 + prefix_space_len);
363 let error_line_buffer = if error.line_buffer.is_empty() {
366 let (space_len, target_len) = error.format_len();
368 "{}|\n{} | {}\n{}| {}",
373 target_str(space_len, target_len)
377 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
378 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
379 let msg_suffix = error.msg_suffix();
380 let note = if msg_suffix.is_empty() {
383 format!("{}note= ", prefix_spaces)
397 if !self.internal.borrow().0.is_empty() {
400 "warning: rustfmt may have failed to format. See previous {} errors.",
401 self.warning_count(),
408 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
412 if config.verbose() == Verbosity::Verbose && path != &FileName::Stdin {
417 // Formatting which depends on the AST.
420 parse_session: &mut ParseSess,
421 main_file: &FileName,
423 report: FormatReport,
425 ) -> Result<(FileMap, bool, bool), io::Error>
427 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
429 let mut result = FileMap::new();
430 // diff mode: check if any files are differing
431 let mut has_diff = false;
432 let mut has_macro_rewrite_failure = false;
434 let skip_children = config.skip_children();
435 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
436 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
439 should_emit_verbose(&path, config, || println!("Formatting {}", path));
440 let filemap = parse_session
442 .lookup_char_pos(module.inner.lo())
444 let big_snippet = filemap.src.as_ref().unwrap();
445 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
447 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
448 // Format inner attributes if available.
449 if !krate.attrs.is_empty() && path == *main_file {
450 visitor.skip_empty_lines(filemap.end_pos);
451 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
452 visitor.push_rewrite(module.inner, None);
454 visitor.format_separate_mod(module, &*filemap);
457 visitor.last_pos = filemap.start_pos;
458 visitor.skip_empty_lines(filemap.end_pos);
459 visitor.format_separate_mod(module, &*filemap);
464 ::utils::count_newlines(&visitor.buffer)
467 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
468 Ok(result) => result,
470 // Create a new error with path_str to help users see which files failed
471 let err_msg = format!("{}: {}", path, e);
472 return Err(io::Error::new(e.kind(), err_msg));
476 has_macro_rewrite_failure |= visitor.macro_rewrite_failure;
478 result.push((path.clone(), visitor.buffer));
481 Ok((result, has_diff, has_macro_rewrite_failure))
484 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
485 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
488 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
491 fn should_report_error(
493 char_kind: FullCodeCharKind,
495 error_kind: &ErrorKind,
497 let allow_error_report = if char_kind.is_comment() || is_string {
498 config.error_on_unformatted()
504 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
505 ErrorKind::TrailingWhitespace => allow_error_report,
510 // Formatting done on a char by char or line by line basis.
511 // FIXME(#20) other stuff for parity with make tidy
515 skipped_range: &[(usize, usize)],
517 report: &FormatReport,
519 let mut trims = vec![];
520 let mut last_wspace: Option<usize> = None;
521 let mut line_len = 0;
522 let mut cur_line = 1;
523 let mut newline_count = 0;
524 let mut errors = vec![];
525 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
526 let mut line_buffer = String::with_capacity(config.max_width() * 2);
527 let mut is_string = false; // true if the current line contains a string literal.
528 let mut format_line = config.file_lines().contains_line(name, cur_line);
529 let allow_issue_seek = !issue_seeker.is_disabled();
532 if let Some(ref license_template) = config.license_template {
533 if !license_template.is_match(text) {
534 errors.push(FormattingError {
536 kind: ErrorKind::LicenseCheck,
539 line_buffer: String::new(),
544 // Iterate over the chars in the file map.
545 for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
550 if allow_issue_seek && format_line {
551 // Add warnings for bad todos/ fixmes
552 if let Some(issue) = issue_seeker.inspect(c) {
553 errors.push(FormattingError {
555 kind: ErrorKind::BadIssue(issue),
558 line_buffer: String::new(),
565 // Check for (and record) trailing whitespace.
566 if let Some(..) = last_wspace {
567 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
569 trims.push((cur_line, kind, line_buffer.clone()));
574 // Check for any line width errors we couldn't correct.
575 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
576 if line_len > config.max_width()
577 && !is_skipped_line(cur_line, skipped_range)
578 && should_report_error(config, kind, is_string, &error_kind)
580 errors.push(FormattingError {
583 is_comment: kind.is_comment(),
585 line_buffer: line_buffer.clone(),
592 format_line = config.file_lines().contains_line(name, cur_line);
599 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
600 if c.is_whitespace() {
601 if last_wspace.is_none() {
602 last_wspace = Some(b);
608 if kind.is_string() {
614 if newline_count > 1 {
615 debug!("track truncate: {} {}", text.len(), newline_count);
616 let line = text.len() - newline_count + 1;
620 for &(l, kind, ref b) in &trims {
621 if !is_skipped_line(l, skipped_range) {
622 errors.push(FormattingError {
624 kind: ErrorKind::TrailingWhitespace,
625 is_comment: kind.is_comment(),
626 is_string: kind.is_string(),
627 line_buffer: b.clone(),
632 report.append(name.clone(), errors);
635 fn parse_input<'sess>(
637 parse_session: &'sess ParseSess,
639 ) -> Result<ast::Crate, ParseError<'sess>> {
640 let mut parser = match input {
641 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
642 Input::Text(text) => parse::new_parser_from_source_str(
644 syntax::codemap::FileName::Custom("stdin".to_owned()),
649 parser.cfg_mods = false;
650 if config.skip_children() {
651 parser.recurse_into_file_modules = false;
654 let mut parser = AssertUnwindSafe(parser);
655 let result = catch_unwind(move || parser.0.parse_crate_mod());
659 if parse_session.span_diagnostic.has_errors() {
660 // Bail out if the parser recovered from an error.
661 Err(ParseError::Recovered)
666 Ok(Err(e)) => Err(ParseError::Error(e)),
667 Err(_) => Err(ParseError::Panic),
671 /// All the ways that parsing can fail.
672 enum ParseError<'sess> {
673 /// There was an error, but the parser recovered.
675 /// There was an error (supplied) and parsing failed.
676 Error(DiagnosticBuilder<'sess>),
677 /// The parser panicked.
681 /// Format the given snippet. The snippet is expected to be *complete* code.
682 /// When we cannot parse the given snippet, this function returns `None`.
683 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
684 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
685 let input = Input::Text(snippet.into());
686 let mut config = config.clone();
687 config.set().emit_mode(config::EmitMode::Stdout);
688 config.set().verbose(Verbosity::Quiet);
689 config.set().hide_parse_errors(true);
690 match format_input(input, &config, Some(&mut out)) {
691 // `format_input()` returns an empty string on parsing error.
692 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
693 Ok(..) => String::from_utf8(out).ok(),
698 const FN_MAIN_PREFIX: &str = "fn main() {\n";
700 fn enclose_in_main_block(s: &str, config: &Config) -> String {
701 let indent = Indent::from_width(config, config.tab_spaces());
702 let mut result = String::with_capacity(s.len() * 2);
703 result.push_str(FN_MAIN_PREFIX);
704 let mut need_indent = true;
705 for (kind, line) in LineClasses::new(s) {
707 result.push_str(&indent.to_string(config));
709 result.push_str(&line);
711 need_indent = !kind.is_string() || line.ends_with('\\');
717 /// Format the given code block. Mainly targeted for code block in comment.
718 /// The code block may be incomplete (i.e. parser may be unable to parse it).
719 /// To avoid panic in parser, we wrap the code block with a dummy function.
720 /// The returned code block does *not* end with newline.
721 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
722 // Wrap the given code block with `fn main()` if it does not have one.
723 let snippet = enclose_in_main_block(code_snippet, config);
724 let mut result = String::with_capacity(snippet.len());
725 let mut is_first = true;
727 // Trim "fn main() {" on the first line and "}" on the last line,
728 // then unindent the whole code block.
729 let formatted = format_snippet(&snippet, config)?;
731 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
732 let mut is_indented = true;
733 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
739 let trimmed_line = if !is_indented {
741 } else if line.len() > config.max_width() {
742 // If there are lines that are larger than max width, we cannot tell
743 // whether we have succeeded but have some comments or strings that
744 // are too long, or we have failed to format code block. We will be
745 // conservative and just return `None` in this case.
747 } else if line.len() > config.tab_spaces() {
748 // Make sure that the line has leading whitespaces.
749 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
750 if line.starts_with(indent_str.as_ref()) {
751 let offset = if config.hard_tabs() {
763 result.push_str(trimmed_line);
764 is_indented = !kind.is_string() || line.ends_with('\\');
775 /// The main entry point for Rustfmt. Formats the given input according to the
776 /// given config. `out` is only necessary if required by the configuration.
777 pub fn format_input<T: Write>(
781 ) -> Result<(Summary, FormatReport), (ErrorKind, Summary)> {
782 if !config.version_meets_requirement() {
783 return Err((ErrorKind::VersionMismatch, Summary::default()));
786 syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| (tup.0, tup.2))
789 fn format_input_inner<T: Write>(
792 mut out: Option<&mut T>,
793 ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
794 let mut summary = Summary::default();
795 if config.disable_all_formatting() {
796 // When the input is from stdin, echo back the input.
797 if let Input::Text(ref buf) = input {
798 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
799 return Err((From::from(e), summary));
802 return Ok((summary, FileMap::new(), FormatReport::new()));
804 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
806 let tty_handler = if config.hide_parse_errors() {
807 let silent_emitter = Box::new(EmitterWriter::new(
808 Box::new(Vec::new()),
809 Some(codemap.clone()),
813 Handler::with_emitter(true, false, silent_emitter)
815 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
816 let color_cfg = if supports_color {
821 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
823 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
825 let main_file = match input {
826 Input::File(ref file) => FileName::Real(file.clone()),
827 Input::Text(..) => FileName::Stdin,
830 let krate = match parse_input(input, &parse_session, config) {
834 ParseError::Error(mut diagnostic) => diagnostic.emit(),
835 ParseError::Panic => {
836 // Note that if you see this message and want more information,
837 // then go to `parse_input` and run the parse function without
838 // `catch_unwind` so rustfmt panics and you can get a backtrace.
839 should_emit_verbose(&main_file, config, || {
840 println!("The Rust parser panicked")
843 ParseError::Recovered => {}
845 summary.add_parsing_error();
846 return Ok((summary, FileMap::new(), FormatReport::new()));
850 summary.mark_parse_time();
852 // Suppress error output after parsing.
853 let silent_emitter = Box::new(EmitterWriter::new(
854 Box::new(Vec::new()),
855 Some(codemap.clone()),
859 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
861 let report = FormatReport::new();
863 let format_result = format_ast(
869 |file_name, file, skipped_range, report| {
870 // For some reason, the codemap does not include terminating
871 // newlines so we must add one on for each file. This is sad.
872 filemap::append_newline(file);
874 format_lines(file, file_name, skipped_range, config, report);
876 if let Some(ref mut out) = out {
877 return filemap::write_file(file, file_name, out, config);
883 summary.mark_format_time();
885 should_emit_verbose(&main_file, config, || {
886 fn duration_to_f32(d: Duration) -> f32 {
887 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
891 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
892 duration_to_f32(summary.get_parse_time().unwrap()),
893 duration_to_f32(summary.get_format_time().unwrap()),
898 let report_errs = &report.internal.borrow().1;
899 if report_errs.has_check_errors {
900 summary.add_check_error();
902 if report_errs.has_operational_errors {
903 summary.add_operational_error();
907 match format_result {
908 Ok((file_map, has_diff, has_macro_rewrite_failure)) => {
909 if report.has_warnings() {
910 summary.add_formatting_error();
917 if has_macro_rewrite_failure {
918 summary.add_macro_foramt_failure();
921 Ok((summary, file_map, report))
923 Err(e) => Err((From::from(e), summary)),
927 /// A single span of changed lines, with 0 or more removed lines
928 /// and a vector of 0 or more inserted lines.
929 #[derive(Debug, PartialEq, Eq)]
930 struct ModifiedChunk {
931 /// The first to be removed from the original text
932 pub line_number_orig: u32,
933 /// The number of lines which have been replaced
934 pub lines_removed: u32,
936 pub lines: Vec<String>,
939 /// Set of changed sections of a file.
940 #[derive(Debug, PartialEq, Eq)]
941 struct ModifiedLines {
942 /// The set of changed chunks.
943 pub chunks: Vec<ModifiedChunk>,
946 /// Format a file and return a `ModifiedLines` data structure describing
947 /// the changed ranges of lines.
949 fn get_modified_lines(
952 ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
953 use std::io::BufRead;
955 let mut data = Vec::new();
957 let mut config = config.clone();
958 config.set().emit_mode(config::EmitMode::ModifiedLines);
959 format_input(input, &config, Some(&mut data))?;
961 let mut lines = data.lines();
962 let mut chunks = Vec::new();
963 while let Some(Ok(header)) = lines.next() {
964 // Parse the header line
965 let values: Vec<_> = header
967 .map(|s| s.parse::<u32>().unwrap())
969 assert_eq!(values.len(), 3);
970 let line_number_orig = values[0];
971 let lines_removed = values[1];
972 let num_added = values[2];
973 let mut added_lines = Vec::new();
974 for _ in 0..num_added {
975 added_lines.push(lines.next().unwrap().unwrap());
977 chunks.push(ModifiedChunk {
983 Ok(ModifiedLines { chunks })
988 use super::{format_code_block, format_snippet, Config};
991 fn test_no_panic_on_format_snippet_and_format_code_block() {
992 // `format_snippet()` and `format_code_block()` should not panic
993 // even when we cannot parse the given snippet.
995 assert!(format_snippet(snippet, &Config::default()).is_none());
996 assert!(format_code_block(snippet, &Config::default()).is_none());
999 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
1001 F: Fn(&str, &Config) -> Option<String>,
1003 let output = formatter(input, &Config::default());
1004 output.is_some() && output.unwrap() == expected
1008 fn test_format_snippet() {
1009 let snippet = "fn main() { println!(\"hello, world\"); }";
1010 let expected = "fn main() {\n \
1011 println!(\"hello, world\");\n\
1013 assert!(test_format_inner(format_snippet, snippet, expected));
1017 fn test_format_code_block_fail() {
1019 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1020 assert!(format_code_block(code_block, &Config::default()).is_none());
1024 fn test_format_code_block() {
1025 // simple code block
1026 let code_block = "let x=3;";
1027 let expected = "let x = 3;";
1028 assert!(test_format_inner(format_code_block, code_block, expected));
1030 // more complex code block, taken from chains.rs.
1032 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1034 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1035 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1037 } else if is_block_expr(context, &parent, &parent_rewrite) {
1038 match context.config.indent_style() {
1039 // Try to put the first child on the same line with parent's last line
1040 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1041 // The parent is a block, so align the rest of the chain with the closing
1043 IndentStyle::Visual => (parent_shape, false),
1047 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1053 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1055 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1056 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1058 } else if is_block_expr(context, &parent, &parent_rewrite) {
1059 match context.config.indent_style() {
1060 // Try to put the first child on the same line with parent's last line
1061 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1062 // The parent is a block, so align the rest of the chain with the closing
1064 IndentStyle::Visual => (parent_shape, false),
1068 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1072 assert!(test_format_inner(format_code_block, code_block, expected));