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, NewlineStyle, Range,
72 pub(crate) mod checkstyle;
74 pub(crate) mod codemap;
76 pub(crate) mod config;
78 pub(crate) mod filemap;
86 pub(crate) mod modules;
91 pub(crate) mod rustfmt_diff;
99 pub(crate) mod visitor;
101 // A map of the files of a crate, with their new content
102 pub(crate) type FileMap = Vec<FileRecord>;
104 pub(crate) type FileRecord = (FileName, String);
106 /// The various errors that can occur during formatting. Note that not all of
107 /// these can currently be propagated to clients.
108 #[derive(Fail, Debug)]
110 /// Line has exceeded character limit (found, maximum).
112 display = "line formatted, but exceeded maximum width \
113 (maximum: {} (see `max_width` option), found: {})",
117 LineOverflow(usize, usize),
118 /// Line ends in whitespace.
119 #[fail(display = "left behind trailing whitespace")]
121 /// TODO or FIXME item without an issue number.
122 #[fail(display = "found {}", _0)]
124 /// License check has failed.
125 #[fail(display = "license check failed")]
127 /// Used deprecated skip attribute.
128 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
130 /// Used a rustfmt:: attribute other than skip.
131 #[fail(display = "invalid attribute")]
133 /// An io error during reading or writing.
134 #[fail(display = "io error: {}", _0)]
136 /// Parse error occured when parsing the Input.
137 #[fail(display = "parse error")]
139 /// The user mandated a version and the current version of Rustfmt does not
140 /// satisfy that requirement.
141 #[fail(display = "Version mismatch")]
145 impl From<io::Error> for ErrorKind {
146 fn from(e: io::Error) -> ErrorKind {
147 ErrorKind::IoError(e)
151 struct FormattingError {
159 impl FormattingError {
160 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
162 line: codemap.lookup_char_pos(span.lo()).line,
167 .span_to_lines(*span)
171 .get_line(fl.lines[0].line_index)
172 .map(|l| l.into_owned())
174 .unwrap_or_else(|| String::new()),
177 fn msg_prefix(&self) -> &str {
179 ErrorKind::LineOverflow(..)
180 | ErrorKind::TrailingWhitespace
181 | ErrorKind::IoError(_)
182 | ErrorKind::ParseError => "internal error:",
183 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
184 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
188 fn msg_suffix(&self) -> &str {
189 if self.is_comment || self.is_string {
190 "set `error_on_unformatted = false` to suppress \
191 the warning against comments or string literals\n"
198 fn format_len(&self) -> (usize, usize) {
200 ErrorKind::LineOverflow(found, max) => (max, found - max),
201 ErrorKind::TrailingWhitespace | ErrorKind::DeprecatedAttr | ErrorKind::BadAttr => {
202 let trailing_ws_start = self
204 .rfind(|c: char| !c.is_whitespace())
209 self.line_buffer.len() - trailing_ws_start,
217 /// Reports on any issues that occurred during a run of Rustfmt.
219 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
221 pub struct FormatReport {
222 // Maps stringified file paths to their associated formatting errors.
223 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
226 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
228 #[derive(Default, Debug)]
229 struct ReportedErrors {
230 has_operational_errors: bool,
231 has_check_errors: bool,
235 fn new() -> FormatReport {
237 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
241 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
242 self.track_errors(&v);
247 .and_modify(|fe| fe.append(&mut v))
251 fn track_errors(&self, new_errors: &[FormattingError]) {
252 let errs = &mut self.internal.borrow_mut().1;
253 if errs.has_operational_errors && errs.has_check_errors {
256 for err in new_errors {
258 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
259 errs.has_operational_errors = true;
261 ErrorKind::BadIssue(_)
262 | ErrorKind::LicenseCheck
263 | ErrorKind::DeprecatedAttr
265 | ErrorKind::VersionMismatch => {
266 errs.has_check_errors = true;
273 fn warning_count(&self) -> usize {
278 .map(|(_, errors)| errors.len())
282 /// Whether any warnings or errors are present in the report.
283 pub fn has_warnings(&self) -> bool {
284 self.warning_count() > 0
287 /// Print the report to a terminal using colours and potentially other
291 mut t: Box<term::Terminal<Output = io::Stderr>>,
292 ) -> Result<(), term::Error> {
293 for (file, errors) in &self.internal.borrow().0 {
294 for error in errors {
295 let prefix_space_len = error.line.to_string().len();
296 let prefix_spaces = " ".repeat(1 + prefix_space_len);
298 // First line: the overview of error
299 t.fg(term::color::RED)?;
300 t.attr(term::Attr::Bold)?;
301 write!(t, "{} ", error.msg_prefix())?;
303 t.attr(term::Attr::Bold)?;
304 writeln!(t, "{}", error.kind)?;
306 // Second line: file info
307 write!(t, "{}--> ", &prefix_spaces[1..])?;
309 writeln!(t, "{}:{}", file, error.line)?;
311 // Third to fifth lines: show the line which triggered error, if available.
312 if !error.line_buffer.is_empty() {
313 let (space_len, target_len) = error.format_len();
314 t.attr(term::Attr::Bold)?;
315 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
317 writeln!(t, "{}", error.line_buffer)?;
318 t.attr(term::Attr::Bold)?;
319 write!(t, "{}| ", prefix_spaces)?;
320 t.fg(term::color::RED)?;
321 writeln!(t, "{}", target_str(space_len, target_len))?;
325 // The last line: show note if available.
326 let msg_suffix = error.msg_suffix();
327 if !msg_suffix.is_empty() {
328 t.attr(term::Attr::Bold)?;
329 write!(t, "{}= note: ", prefix_spaces)?;
331 writeln!(t, "{}", error.msg_suffix())?;
339 if !self.internal.borrow().0.is_empty() {
340 t.attr(term::Attr::Bold)?;
341 write!(t, "warning: ")?;
345 "rustfmt may have failed to format. See previous {} errors.\n\n",
346 self.warning_count(),
354 fn target_str(space_len: usize, target_len: usize) -> String {
355 let empty_line = " ".repeat(space_len);
356 let overflowed = "^".repeat(target_len);
357 empty_line + &overflowed
360 impl fmt::Display for FormatReport {
361 // Prints all the formatting errors.
362 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
363 for (file, errors) in &self.internal.borrow().0 {
364 for error in errors {
365 let prefix_space_len = error.line.to_string().len();
366 let prefix_spaces = " ".repeat(1 + prefix_space_len);
368 let error_line_buffer = if error.line_buffer.is_empty() {
371 let (space_len, target_len) = error.format_len();
373 "{}|\n{} | {}\n{}| {}",
378 target_str(space_len, target_len)
382 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
383 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
384 let msg_suffix = error.msg_suffix();
385 let note = if msg_suffix.is_empty() {
388 format!("{}note= ", prefix_spaces)
402 if !self.internal.borrow().0.is_empty() {
405 "warning: rustfmt may have failed to format. See previous {} errors.",
406 self.warning_count(),
413 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
417 if config.verbose() == Verbosity::Verbose && path != &FileName::Stdin {
422 // Formatting which depends on the AST.
425 parse_session: &mut ParseSess,
426 main_file: &FileName,
428 report: FormatReport,
430 ) -> Result<(FileMap, bool, bool), io::Error>
432 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
434 let mut result = FileMap::new();
435 // diff mode: check if any files are differing
436 let mut has_diff = false;
437 let mut has_macro_rewrite_failure = false;
439 let skip_children = config.skip_children();
440 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
441 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
444 should_emit_verbose(&path, config, || println!("Formatting {}", path));
445 let filemap = parse_session
447 .lookup_char_pos(module.inner.lo())
449 let big_snippet = filemap.src.as_ref().unwrap();
450 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
452 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
453 // Format inner attributes if available.
454 if !krate.attrs.is_empty() && path == *main_file {
455 visitor.skip_empty_lines(filemap.end_pos);
456 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
457 visitor.push_rewrite(module.inner, None);
459 visitor.format_separate_mod(module, &*filemap);
462 visitor.last_pos = filemap.start_pos;
463 visitor.skip_empty_lines(filemap.end_pos);
464 visitor.format_separate_mod(module, &*filemap);
469 ::utils::count_newlines(&visitor.buffer)
472 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
473 Ok(result) => result,
475 // Create a new error with path_str to help users see which files failed
476 let err_msg = format!("{}: {}", path, e);
477 return Err(io::Error::new(e.kind(), err_msg));
481 has_macro_rewrite_failure |= visitor.macro_rewrite_failure;
483 result.push((path.clone(), visitor.buffer));
486 Ok((result, has_diff, has_macro_rewrite_failure))
489 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
490 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
493 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
496 fn should_report_error(
498 char_kind: FullCodeCharKind,
500 error_kind: &ErrorKind,
502 let allow_error_report = if char_kind.is_comment() || is_string {
503 config.error_on_unformatted()
509 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
510 ErrorKind::TrailingWhitespace => allow_error_report,
515 // Formatting done on a char by char or line by line basis.
516 // FIXME(#20) other stuff for parity with make tidy
520 skipped_range: &[(usize, usize)],
522 report: &FormatReport,
524 let mut last_was_space = false;
525 let mut line_len = 0;
526 let mut cur_line = 1;
527 let mut newline_count = 0;
528 let mut errors = vec![];
529 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
530 let mut line_buffer = String::with_capacity(config.max_width() * 2);
531 let mut is_string = false; // true if the current line contains a string literal.
532 let mut format_line = config.file_lines().contains_line(name, cur_line);
533 let allow_issue_seek = !issue_seeker.is_disabled();
536 if let Some(ref license_template) = config.license_template {
537 if !license_template.is_match(text) {
538 errors.push(FormattingError {
540 kind: ErrorKind::LicenseCheck,
543 line_buffer: String::new(),
548 // Iterate over the chars in the file map.
549 for (kind, c) in CharClasses::new(text.chars()) {
554 if allow_issue_seek && format_line {
555 // Add warnings for bad todos/ fixmes
556 if let Some(issue) = issue_seeker.inspect(c) {
557 errors.push(FormattingError {
559 kind: ErrorKind::BadIssue(issue),
562 line_buffer: String::new(),
569 // Check for (and record) trailing whitespace.
571 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
572 && !is_skipped_line(cur_line, skipped_range)
574 errors.push(FormattingError {
576 kind: ErrorKind::TrailingWhitespace,
577 is_comment: kind.is_comment(),
578 is_string: kind.is_string(),
579 line_buffer: line_buffer.clone(),
585 // Check for any line width errors we couldn't correct.
586 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
587 if line_len > config.max_width()
588 && !is_skipped_line(cur_line, skipped_range)
589 && should_report_error(config, kind, is_string, &error_kind)
591 errors.push(FormattingError {
594 is_comment: kind.is_comment(),
596 line_buffer: line_buffer.clone(),
603 format_line = config.file_lines().contains_line(name, cur_line);
605 last_was_space = false;
610 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
611 last_was_space = c.is_whitespace();
613 if kind.is_string() {
619 if newline_count > 1 {
620 debug!("track truncate: {} {}", text.len(), newline_count);
621 let line = text.len() - newline_count + 1;
625 report.append(name.clone(), errors);
628 fn parse_input<'sess>(
630 parse_session: &'sess ParseSess,
632 ) -> Result<ast::Crate, ParseError<'sess>> {
633 let mut parser = match input {
634 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
635 Input::Text(text) => parse::new_parser_from_source_str(
637 syntax::codemap::FileName::Custom("stdin".to_owned()),
642 parser.cfg_mods = false;
643 if config.skip_children() {
644 parser.recurse_into_file_modules = false;
647 let mut parser = AssertUnwindSafe(parser);
648 let result = catch_unwind(move || parser.0.parse_crate_mod());
652 if parse_session.span_diagnostic.has_errors() {
653 // Bail out if the parser recovered from an error.
654 Err(ParseError::Recovered)
659 Ok(Err(e)) => Err(ParseError::Error(e)),
660 Err(_) => Err(ParseError::Panic),
664 /// All the ways that parsing can fail.
665 enum ParseError<'sess> {
666 /// There was an error, but the parser recovered.
668 /// There was an error (supplied) and parsing failed.
669 Error(DiagnosticBuilder<'sess>),
670 /// The parser panicked.
674 /// Format the given snippet. The snippet is expected to be *complete* code.
675 /// When we cannot parse the given snippet, this function returns `None`.
676 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
677 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
678 let input = Input::Text(snippet.into());
679 let mut config = config.clone();
680 config.set().emit_mode(config::EmitMode::Stdout);
681 config.set().verbose(Verbosity::Quiet);
682 config.set().hide_parse_errors(true);
683 match format_input(input, &config, Some(&mut out)) {
684 // `format_input()` returns an empty string on parsing error.
685 Ok((summary, _)) if summary.has_macro_formatting_failure() => None,
686 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
687 Ok(..) => String::from_utf8(out).ok(),
692 const FN_MAIN_PREFIX: &str = "fn main() {\n";
694 fn enclose_in_main_block(s: &str, config: &Config) -> String {
695 let indent = Indent::from_width(config, config.tab_spaces());
696 let mut result = String::with_capacity(s.len() * 2);
697 result.push_str(FN_MAIN_PREFIX);
698 let mut need_indent = true;
699 for (kind, line) in LineClasses::new(s) {
701 result.push_str(&indent.to_string(config));
703 result.push_str(&line);
705 need_indent = !kind.is_string() || line.ends_with('\\');
711 /// Format the given code block. Mainly targeted for code block in comment.
712 /// The code block may be incomplete (i.e. parser may be unable to parse it).
713 /// To avoid panic in parser, we wrap the code block with a dummy function.
714 /// The returned code block does *not* end with newline.
715 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
716 // Wrap the given code block with `fn main()` if it does not have one.
717 let snippet = enclose_in_main_block(code_snippet, config);
718 let mut result = String::with_capacity(snippet.len());
719 let mut is_first = true;
721 // While formatting the code, ignore the config's newline style setting and always use "\n"
722 // instead of "\r\n" for the newline characters. This is okay because the output here is
723 // not directly outputted by rustfmt command, but used by the comment formatter's input.
724 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
725 let mut config_with_unix_newline = config.clone();
726 config_with_unix_newline
728 .newline_style(NewlineStyle::Unix);
729 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
731 // Trim "fn main() {" on the first line and "}" on the last line,
732 // then unindent the whole code block.
733 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
734 let mut is_indented = true;
735 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
741 let trimmed_line = if !is_indented {
743 } else if line.len() > config.max_width() {
744 // If there are lines that are larger than max width, we cannot tell
745 // whether we have succeeded but have some comments or strings that
746 // are too long, or we have failed to format code block. We will be
747 // conservative and just return `None` in this case.
749 } else if line.len() > config.tab_spaces() {
750 // Make sure that the line has leading whitespaces.
751 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
752 if line.starts_with(indent_str.as_ref()) {
753 let offset = if config.hard_tabs() {
765 result.push_str(trimmed_line);
766 is_indented = !kind.is_string() || line.ends_with('\\');
777 /// The main entry point for Rustfmt. Formats the given input according to the
778 /// given config. `out` is only necessary if required by the configuration.
779 pub fn format_input<T: Write>(
783 ) -> Result<(Summary, FormatReport), (ErrorKind, Summary)> {
784 if !config.version_meets_requirement() {
785 return Err((ErrorKind::VersionMismatch, Summary::default()));
788 syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| (tup.0, tup.2))
791 fn format_input_inner<T: Write>(
794 mut out: Option<&mut T>,
795 ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
796 let mut summary = Summary::default();
797 if config.disable_all_formatting() {
798 // When the input is from stdin, echo back the input.
799 if let Input::Text(ref buf) = input {
800 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
801 return Err((From::from(e), summary));
804 return Ok((summary, FileMap::new(), FormatReport::new()));
806 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
808 let tty_handler = if config.hide_parse_errors() {
809 let silent_emitter = Box::new(EmitterWriter::new(
810 Box::new(Vec::new()),
811 Some(codemap.clone()),
815 Handler::with_emitter(true, false, silent_emitter)
817 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
818 let color_cfg = if supports_color {
823 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
825 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
827 let main_file = match input {
828 Input::File(ref file) => FileName::Real(file.clone()),
829 Input::Text(..) => FileName::Stdin,
832 let krate = match parse_input(input, &parse_session, config) {
836 ParseError::Error(mut diagnostic) => diagnostic.emit(),
837 ParseError::Panic => {
838 // Note that if you see this message and want more information,
839 // then go to `parse_input` and run the parse function without
840 // `catch_unwind` so rustfmt panics and you can get a backtrace.
841 should_emit_verbose(&main_file, config, || {
842 println!("The Rust parser panicked")
845 ParseError::Recovered => {}
847 summary.add_parsing_error();
848 return Err((ErrorKind::ParseError, summary));
852 summary.mark_parse_time();
854 // Suppress error output after parsing.
855 let silent_emitter = Box::new(EmitterWriter::new(
856 Box::new(Vec::new()),
857 Some(codemap.clone()),
861 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
863 let report = FormatReport::new();
865 let format_result = format_ast(
871 |file_name, file, skipped_range, report| {
872 // For some reason, the codemap does not include terminating
873 // newlines so we must add one on for each file. This is sad.
874 filemap::append_newline(file);
876 format_lines(file, file_name, skipped_range, config, report);
877 replace_with_system_newlines(file, config);
879 if let Some(ref mut out) = out {
880 return filemap::write_file(file, file_name, out, config);
886 summary.mark_format_time();
888 should_emit_verbose(&main_file, config, || {
889 fn duration_to_f32(d: Duration) -> f32 {
890 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
894 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
895 duration_to_f32(summary.get_parse_time().unwrap()),
896 duration_to_f32(summary.get_format_time().unwrap()),
901 let report_errs = &report.internal.borrow().1;
902 if report_errs.has_check_errors {
903 summary.add_check_error();
905 if report_errs.has_operational_errors {
906 summary.add_operational_error();
910 match format_result {
911 Ok((file_map, has_diff, has_macro_rewrite_failure)) => {
912 if report.has_warnings() {
913 summary.add_formatting_error();
920 if has_macro_rewrite_failure {
921 summary.add_macro_foramt_failure();
924 Ok((summary, file_map, report))
926 Err(e) => Err((From::from(e), summary)),
930 pub fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
931 let style = if config.newline_style() == NewlineStyle::Native {
933 NewlineStyle::Windows
938 config.newline_style()
942 NewlineStyle::Unix => return,
943 NewlineStyle::Windows => {
944 let mut transformed = String::with_capacity(text.capacity());
945 for c in text.chars() {
947 '\n' => transformed.push_str("\r\n"),
949 c => transformed.push(c),
954 NewlineStyle::Native => unreachable!(),
958 /// A single span of changed lines, with 0 or more removed lines
959 /// and a vector of 0 or more inserted lines.
960 #[derive(Debug, PartialEq, Eq)]
961 struct ModifiedChunk {
962 /// The first to be removed from the original text
963 pub line_number_orig: u32,
964 /// The number of lines which have been replaced
965 pub lines_removed: u32,
967 pub lines: Vec<String>,
970 /// Set of changed sections of a file.
971 #[derive(Debug, PartialEq, Eq)]
972 struct ModifiedLines {
973 /// The set of changed chunks.
974 pub chunks: Vec<ModifiedChunk>,
977 /// Format a file and return a `ModifiedLines` data structure describing
978 /// the changed ranges of lines.
980 fn get_modified_lines(
983 ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
984 use std::io::BufRead;
986 let mut data = Vec::new();
988 let mut config = config.clone();
989 config.set().emit_mode(config::EmitMode::ModifiedLines);
990 format_input(input, &config, Some(&mut data))?;
992 let mut lines = data.lines();
993 let mut chunks = Vec::new();
994 while let Some(Ok(header)) = lines.next() {
995 // Parse the header line
996 let values: Vec<_> = header
998 .map(|s| s.parse::<u32>().unwrap())
1000 assert_eq!(values.len(), 3);
1001 let line_number_orig = values[0];
1002 let lines_removed = values[1];
1003 let num_added = values[2];
1004 let mut added_lines = Vec::new();
1005 for _ in 0..num_added {
1006 added_lines.push(lines.next().unwrap().unwrap());
1008 chunks.push(ModifiedChunk {
1014 Ok(ModifiedLines { chunks })
1019 use super::{format_code_block, format_snippet, Config};
1022 fn test_no_panic_on_format_snippet_and_format_code_block() {
1023 // `format_snippet()` and `format_code_block()` should not panic
1024 // even when we cannot parse the given snippet.
1025 let snippet = "let";
1026 assert!(format_snippet(snippet, &Config::default()).is_none());
1027 assert!(format_code_block(snippet, &Config::default()).is_none());
1030 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
1032 F: Fn(&str, &Config) -> Option<String>,
1034 let output = formatter(input, &Config::default());
1035 output.is_some() && output.unwrap() == expected
1039 fn test_format_snippet() {
1040 let snippet = "fn main() { println!(\"hello, world\"); }";
1041 #[cfg(not(windows))]
1042 let expected = "fn main() {\n \
1043 println!(\"hello, world\");\n\
1046 let expected = "fn main() {\r\n \
1047 println!(\"hello, world\");\r\n\
1049 assert!(test_format_inner(format_snippet, snippet, expected));
1053 fn test_format_code_block_fail() {
1055 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1056 assert!(format_code_block(code_block, &Config::default()).is_none());
1060 fn test_format_code_block() {
1061 // simple code block
1062 let code_block = "let x=3;";
1063 let expected = "let x = 3;";
1064 assert!(test_format_inner(format_code_block, code_block, expected));
1066 // more complex code block, taken from chains.rs.
1068 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1070 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1071 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1073 } else if is_block_expr(context, &parent, &parent_rewrite) {
1074 match context.config.indent_style() {
1075 // Try to put the first child on the same line with parent's last line
1076 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1077 // The parent is a block, so align the rest of the chain with the closing
1079 IndentStyle::Visual => (parent_shape, false),
1083 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1089 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1091 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1092 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1094 } else if is_block_expr(context, &parent, &parent_rewrite) {
1095 match context.config.indent_style() {
1096 // Try to put the first child on the same line with parent's last line
1097 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1098 // The parent is a block, so align the rest of the chain with the closing
1100 IndentStyle::Visual => (parent_shape, false),
1104 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1108 assert!(test_format_inner(format_code_block, code_block, expected));