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;
36 extern crate syntax_pos;
38 extern crate unicode_segmentation;
40 use std::cell::RefCell;
41 use std::collections::HashMap;
43 use std::io::{self, Write};
44 use std::panic::{catch_unwind, AssertUnwindSafe};
45 use std::path::PathBuf;
47 use std::time::Duration;
50 use syntax::codemap::{CodeMap, FilePathMapping, Span};
51 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
52 use syntax::errors::{DiagnosticBuilder, Handler};
53 use syntax::parse::{self, ParseSess};
55 use comment::{CharClasses, FullCodeCharKind, LineClasses};
57 use issues::{BadIssueSeeker, Issue};
59 use visitor::{FmtVisitor, SnippetProvider};
61 pub use checkstyle::{footer as checkstyle_footer, header as checkstyle_header};
62 pub use config::summary::Summary;
64 load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, NewlineStyle, Range,
73 pub(crate) mod checkstyle;
75 pub(crate) mod codemap;
77 pub(crate) mod config;
79 pub(crate) mod filemap;
87 pub(crate) mod modules;
93 pub(crate) mod rustfmt_diff;
101 pub(crate) mod visitor;
103 // A map of the files of a crate, with their new content
104 pub(crate) type FileMap = Vec<FileRecord>;
106 pub(crate) type FileRecord = (FileName, String);
108 /// The various errors that can occur during formatting. Note that not all of
109 /// these can currently be propagated to clients.
110 #[derive(Fail, Debug)]
112 /// Line has exceeded character limit (found, maximum).
114 display = "line formatted, but exceeded maximum width \
115 (maximum: {} (see `max_width` option), found: {})",
119 LineOverflow(usize, usize),
120 /// Line ends in whitespace.
121 #[fail(display = "left behind trailing whitespace")]
123 /// TODO or FIXME item without an issue number.
124 #[fail(display = "found {}", _0)]
126 /// License check has failed.
127 #[fail(display = "license check failed")]
129 /// Used deprecated skip attribute.
130 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
132 /// Used a rustfmt:: attribute other than skip.
133 #[fail(display = "invalid attribute")]
135 /// An io error during reading or writing.
136 #[fail(display = "io error: {}", _0)]
138 /// Parse error occured when parsing the Input.
139 #[fail(display = "parse error")]
141 /// The user mandated a version and the current version of Rustfmt does not
142 /// satisfy that requirement.
143 #[fail(display = "Version mismatch")]
147 impl From<io::Error> for ErrorKind {
148 fn from(e: io::Error) -> ErrorKind {
149 ErrorKind::IoError(e)
153 struct FormattingError {
161 impl FormattingError {
162 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
164 line: codemap.lookup_char_pos(span.lo()).line,
169 .span_to_lines(*span)
173 .get_line(fl.lines[0].line_index)
174 .map(|l| l.into_owned())
176 .unwrap_or_else(|| String::new()),
179 fn msg_prefix(&self) -> &str {
181 ErrorKind::LineOverflow(..)
182 | ErrorKind::TrailingWhitespace
183 | ErrorKind::IoError(_)
184 | ErrorKind::ParseError => "internal error:",
185 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
186 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
190 fn msg_suffix(&self) -> &str {
191 if self.is_comment || self.is_string {
192 "set `error_on_unformatted = false` to suppress \
193 the warning against comments or string literals\n"
200 fn format_len(&self) -> (usize, usize) {
202 ErrorKind::LineOverflow(found, max) => (max, found - max),
203 ErrorKind::TrailingWhitespace | ErrorKind::DeprecatedAttr | ErrorKind::BadAttr => {
204 let trailing_ws_start = self
206 .rfind(|c: char| !c.is_whitespace())
211 self.line_buffer.len() - trailing_ws_start,
219 /// Reports on any issues that occurred during a run of Rustfmt.
221 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
223 pub struct FormatReport {
224 // Maps stringified file paths to their associated formatting errors.
225 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
228 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
230 #[derive(Default, Debug)]
231 struct ReportedErrors {
232 has_operational_errors: bool,
233 has_check_errors: bool,
237 fn new() -> FormatReport {
239 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
243 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
244 self.track_errors(&v);
249 .and_modify(|fe| fe.append(&mut v))
253 fn track_errors(&self, new_errors: &[FormattingError]) {
254 let errs = &mut self.internal.borrow_mut().1;
255 if errs.has_operational_errors && errs.has_check_errors {
258 for err in new_errors {
260 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
261 errs.has_operational_errors = true;
263 ErrorKind::BadIssue(_)
264 | ErrorKind::LicenseCheck
265 | ErrorKind::DeprecatedAttr
267 | ErrorKind::VersionMismatch => {
268 errs.has_check_errors = true;
275 fn warning_count(&self) -> usize {
280 .map(|(_, errors)| errors.len())
284 /// Whether any warnings or errors are present in the report.
285 pub fn has_warnings(&self) -> bool {
286 self.warning_count() > 0
289 /// Print the report to a terminal using colours and potentially other
293 mut t: Box<term::Terminal<Output = io::Stderr>>,
294 ) -> Result<(), term::Error> {
295 for (file, errors) in &self.internal.borrow().0 {
296 for error in errors {
297 let prefix_space_len = error.line.to_string().len();
298 let prefix_spaces = " ".repeat(1 + prefix_space_len);
300 // First line: the overview of error
301 t.fg(term::color::RED)?;
302 t.attr(term::Attr::Bold)?;
303 write!(t, "{} ", error.msg_prefix())?;
305 t.attr(term::Attr::Bold)?;
306 writeln!(t, "{}", error.kind)?;
308 // Second line: file info
309 write!(t, "{}--> ", &prefix_spaces[1..])?;
311 writeln!(t, "{}:{}", file, error.line)?;
313 // Third to fifth lines: show the line which triggered error, if available.
314 if !error.line_buffer.is_empty() {
315 let (space_len, target_len) = error.format_len();
316 t.attr(term::Attr::Bold)?;
317 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
319 writeln!(t, "{}", error.line_buffer)?;
320 t.attr(term::Attr::Bold)?;
321 write!(t, "{}| ", prefix_spaces)?;
322 t.fg(term::color::RED)?;
323 writeln!(t, "{}", target_str(space_len, target_len))?;
327 // The last line: show note if available.
328 let msg_suffix = error.msg_suffix();
329 if !msg_suffix.is_empty() {
330 t.attr(term::Attr::Bold)?;
331 write!(t, "{}= note: ", prefix_spaces)?;
333 writeln!(t, "{}", error.msg_suffix())?;
341 if !self.internal.borrow().0.is_empty() {
342 t.attr(term::Attr::Bold)?;
343 write!(t, "warning: ")?;
347 "rustfmt may have failed to format. See previous {} errors.\n\n",
348 self.warning_count(),
356 fn target_str(space_len: usize, target_len: usize) -> String {
357 let empty_line = " ".repeat(space_len);
358 let overflowed = "^".repeat(target_len);
359 empty_line + &overflowed
362 impl fmt::Display for FormatReport {
363 // Prints all the formatting errors.
364 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
365 for (file, errors) in &self.internal.borrow().0 {
366 for error in errors {
367 let prefix_space_len = error.line.to_string().len();
368 let prefix_spaces = " ".repeat(1 + prefix_space_len);
370 let error_line_buffer = if error.line_buffer.is_empty() {
373 let (space_len, target_len) = error.format_len();
375 "{}|\n{} | {}\n{}| {}",
380 target_str(space_len, target_len)
384 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
385 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
386 let msg_suffix = error.msg_suffix();
387 let note = if msg_suffix.is_empty() {
390 format!("{}note= ", prefix_spaces)
404 if !self.internal.borrow().0.is_empty() {
407 "warning: rustfmt may have failed to format. See previous {} errors.",
408 self.warning_count(),
415 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
419 if config.verbose() == Verbosity::Verbose && path != &FileName::Stdin {
424 // Formatting which depends on the AST.
427 parse_session: &mut ParseSess,
428 main_file: &FileName,
430 report: FormatReport,
432 ) -> Result<(FileMap, bool, bool), io::Error>
434 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
436 let mut result = FileMap::new();
437 // diff mode: check if any files are differing
438 let mut has_diff = false;
439 let mut has_macro_rewrite_failure = false;
441 let skip_children = config.skip_children();
442 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
443 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
446 should_emit_verbose(&path, config, || println!("Formatting {}", path));
447 let filemap = parse_session
449 .lookup_char_pos(module.inner.lo())
451 let big_snippet = filemap.src.as_ref().unwrap();
452 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
454 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
455 // Format inner attributes if available.
456 if !krate.attrs.is_empty() && path == *main_file {
457 visitor.skip_empty_lines(filemap.end_pos);
458 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
459 visitor.push_rewrite(module.inner, None);
461 visitor.format_separate_mod(module, &*filemap);
464 visitor.last_pos = filemap.start_pos;
465 visitor.skip_empty_lines(filemap.end_pos);
466 visitor.format_separate_mod(module, &*filemap);
471 ::utils::count_newlines(&visitor.buffer)
474 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
475 Ok(result) => result,
477 // Create a new error with path_str to help users see which files failed
478 let err_msg = format!("{}: {}", path, e);
479 return Err(io::Error::new(e.kind(), err_msg));
483 has_macro_rewrite_failure |= visitor.macro_rewrite_failure;
485 result.push((path.clone(), visitor.buffer));
488 Ok((result, has_diff, has_macro_rewrite_failure))
491 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
492 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
495 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
498 fn should_report_error(
500 char_kind: FullCodeCharKind,
502 error_kind: &ErrorKind,
504 let allow_error_report = if char_kind.is_comment() || is_string {
505 config.error_on_unformatted()
511 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
512 ErrorKind::TrailingWhitespace => allow_error_report,
517 // Formatting done on a char by char or line by line basis.
518 // FIXME(#20) other stuff for parity with make tidy
522 skipped_range: &[(usize, usize)],
524 report: &FormatReport,
526 let mut last_was_space = false;
527 let mut line_len = 0;
528 let mut cur_line = 1;
529 let mut newline_count = 0;
530 let mut errors = vec![];
531 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
532 let mut line_buffer = String::with_capacity(config.max_width() * 2);
533 let mut is_string = false; // true if the current line contains a string literal.
534 let mut format_line = config.file_lines().contains_line(name, cur_line);
535 let allow_issue_seek = !issue_seeker.is_disabled();
538 if let Some(ref license_template) = config.license_template {
539 if !license_template.is_match(text) {
540 errors.push(FormattingError {
542 kind: ErrorKind::LicenseCheck,
545 line_buffer: String::new(),
550 // Iterate over the chars in the file map.
551 for (kind, c) in CharClasses::new(text.chars()) {
556 if allow_issue_seek && format_line {
557 // Add warnings for bad todos/ fixmes
558 if let Some(issue) = issue_seeker.inspect(c) {
559 errors.push(FormattingError {
561 kind: ErrorKind::BadIssue(issue),
564 line_buffer: String::new(),
571 // Check for (and record) trailing whitespace.
573 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
574 && !is_skipped_line(cur_line, skipped_range)
576 errors.push(FormattingError {
578 kind: ErrorKind::TrailingWhitespace,
579 is_comment: kind.is_comment(),
580 is_string: kind.is_string(),
581 line_buffer: line_buffer.clone(),
587 // Check for any line width errors we couldn't correct.
588 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
589 if line_len > config.max_width()
590 && !is_skipped_line(cur_line, skipped_range)
591 && should_report_error(config, kind, is_string, &error_kind)
593 errors.push(FormattingError {
596 is_comment: kind.is_comment(),
598 line_buffer: line_buffer.clone(),
605 format_line = config.file_lines().contains_line(name, cur_line);
607 last_was_space = false;
612 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
613 last_was_space = c.is_whitespace();
615 if kind.is_string() {
621 if newline_count > 1 {
622 debug!("track truncate: {} {}", text.len(), newline_count);
623 let line = text.len() - newline_count + 1;
627 report.append(name.clone(), errors);
630 fn parse_input<'sess>(
632 parse_session: &'sess ParseSess,
634 ) -> Result<ast::Crate, ParseError<'sess>> {
635 let mut parser = match input {
636 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
637 Input::Text(text) => parse::new_parser_from_source_str(
639 syntax::codemap::FileName::Custom("stdin".to_owned()),
644 parser.cfg_mods = false;
645 if config.skip_children() {
646 parser.recurse_into_file_modules = false;
649 let mut parser = AssertUnwindSafe(parser);
650 let result = catch_unwind(move || parser.0.parse_crate_mod());
654 if parse_session.span_diagnostic.has_errors() {
655 // Bail out if the parser recovered from an error.
656 Err(ParseError::Recovered)
661 Ok(Err(e)) => Err(ParseError::Error(e)),
662 Err(_) => Err(ParseError::Panic),
666 /// All the ways that parsing can fail.
667 enum ParseError<'sess> {
668 /// There was an error, but the parser recovered.
670 /// There was an error (supplied) and parsing failed.
671 Error(DiagnosticBuilder<'sess>),
672 /// The parser panicked.
676 /// Format the given snippet. The snippet is expected to be *complete* code.
677 /// When we cannot parse the given snippet, this function returns `None`.
678 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
679 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
680 let input = Input::Text(snippet.into());
681 let mut config = config.clone();
682 config.set().emit_mode(config::EmitMode::Stdout);
683 config.set().verbose(Verbosity::Quiet);
684 config.set().hide_parse_errors(true);
685 match format_input(input, &config, Some(&mut out)) {
686 // `format_input()` returns an empty string on parsing error.
687 Ok((summary, _)) if summary.has_macro_formatting_failure() => None,
688 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
689 Ok(..) => String::from_utf8(out).ok(),
694 const FN_MAIN_PREFIX: &str = "fn main() {\n";
696 fn enclose_in_main_block(s: &str, config: &Config) -> String {
697 let indent = Indent::from_width(config, config.tab_spaces());
698 let mut result = String::with_capacity(s.len() * 2);
699 result.push_str(FN_MAIN_PREFIX);
700 let mut need_indent = true;
701 for (kind, line) in LineClasses::new(s) {
703 result.push_str(&indent.to_string(config));
705 result.push_str(&line);
707 need_indent = !kind.is_string() || line.ends_with('\\');
713 /// Format the given code block. Mainly targeted for code block in comment.
714 /// The code block may be incomplete (i.e. parser may be unable to parse it).
715 /// To avoid panic in parser, we wrap the code block with a dummy function.
716 /// The returned code block does *not* end with newline.
717 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
718 // Wrap the given code block with `fn main()` if it does not have one.
719 let snippet = enclose_in_main_block(code_snippet, config);
720 let mut result = String::with_capacity(snippet.len());
721 let mut is_first = true;
723 // While formatting the code, ignore the config's newline style setting and always use "\n"
724 // instead of "\r\n" for the newline characters. This is okay because the output here is
725 // not directly outputted by rustfmt command, but used by the comment formatter's input.
726 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
727 let mut config_with_unix_newline = config.clone();
728 config_with_unix_newline
730 .newline_style(NewlineStyle::Unix);
731 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
733 // Trim "fn main() {" on the first line and "}" on the last line,
734 // then unindent the whole code block.
735 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
736 let mut is_indented = true;
737 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
743 let trimmed_line = if !is_indented {
745 } else if line.len() > config.max_width() {
746 // If there are lines that are larger than max width, we cannot tell
747 // whether we have succeeded but have some comments or strings that
748 // are too long, or we have failed to format code block. We will be
749 // conservative and just return `None` in this case.
751 } else if line.len() > config.tab_spaces() {
752 // Make sure that the line has leading whitespaces.
753 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
754 if line.starts_with(indent_str.as_ref()) {
755 let offset = if config.hard_tabs() {
767 result.push_str(trimmed_line);
768 is_indented = !kind.is_string() || line.ends_with('\\');
779 /// The main entry point for Rustfmt. Formats the given input according to the
780 /// given config. `out` is only necessary if required by the configuration.
781 pub fn format_input<T: Write>(
785 ) -> Result<(Summary, FormatReport), (ErrorKind, Summary)> {
786 if !config.version_meets_requirement() {
787 return Err((ErrorKind::VersionMismatch, Summary::default()));
790 syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| (tup.0, tup.2))
793 fn format_input_inner<T: Write>(
796 mut out: Option<&mut T>,
797 ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
798 syntax_pos::hygiene::set_default_edition(config.edition().to_libsyntax_pos_edition());
799 let mut summary = Summary::default();
800 if config.disable_all_formatting() {
801 // When the input is from stdin, echo back the input.
802 if let Input::Text(ref buf) = input {
803 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
804 return Err((From::from(e), summary));
807 return Ok((summary, FileMap::new(), FormatReport::new()));
809 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
811 let tty_handler = if config.hide_parse_errors() {
812 let silent_emitter = Box::new(EmitterWriter::new(
813 Box::new(Vec::new()),
814 Some(codemap.clone()),
818 Handler::with_emitter(true, false, silent_emitter)
820 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
821 let color_cfg = if supports_color {
826 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
828 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
830 let main_file = match input {
831 Input::File(ref file) => FileName::Real(file.clone()),
832 Input::Text(..) => FileName::Stdin,
835 let krate = match parse_input(input, &parse_session, config) {
839 ParseError::Error(mut diagnostic) => diagnostic.emit(),
840 ParseError::Panic => {
841 // Note that if you see this message and want more information,
842 // then go to `parse_input` and run the parse function without
843 // `catch_unwind` so rustfmt panics and you can get a backtrace.
844 should_emit_verbose(&main_file, config, || {
845 println!("The Rust parser panicked")
848 ParseError::Recovered => {}
850 summary.add_parsing_error();
851 return Err((ErrorKind::ParseError, summary));
855 summary.mark_parse_time();
857 // Suppress error output after parsing.
858 let silent_emitter = Box::new(EmitterWriter::new(
859 Box::new(Vec::new()),
860 Some(codemap.clone()),
864 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
866 let report = FormatReport::new();
868 let format_result = format_ast(
874 |file_name, file, skipped_range, report| {
875 // For some reason, the codemap does not include terminating
876 // newlines so we must add one on for each file. This is sad.
877 filemap::append_newline(file);
879 format_lines(file, file_name, skipped_range, config, report);
880 replace_with_system_newlines(file, config);
882 if let Some(ref mut out) = out {
883 return filemap::write_file(file, file_name, out, config);
889 summary.mark_format_time();
891 should_emit_verbose(&main_file, config, || {
892 fn duration_to_f32(d: Duration) -> f32 {
893 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
897 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
898 duration_to_f32(summary.get_parse_time().unwrap()),
899 duration_to_f32(summary.get_format_time().unwrap()),
904 let report_errs = &report.internal.borrow().1;
905 if report_errs.has_check_errors {
906 summary.add_check_error();
908 if report_errs.has_operational_errors {
909 summary.add_operational_error();
913 match format_result {
914 Ok((file_map, has_diff, has_macro_rewrite_failure)) => {
915 if report.has_warnings() {
916 summary.add_formatting_error();
923 if has_macro_rewrite_failure {
924 summary.add_macro_foramt_failure();
927 Ok((summary, file_map, report))
929 Err(e) => Err((From::from(e), summary)),
933 fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
934 let style = if config.newline_style() == NewlineStyle::Native {
936 NewlineStyle::Windows
941 config.newline_style()
945 NewlineStyle::Unix => return,
946 NewlineStyle::Windows => {
947 let mut transformed = String::with_capacity(text.capacity());
948 for c in text.chars() {
950 '\n' => transformed.push_str("\r\n"),
952 c => transformed.push(c),
957 NewlineStyle::Native => unreachable!(),
961 /// A single span of changed lines, with 0 or more removed lines
962 /// and a vector of 0 or more inserted lines.
963 #[derive(Debug, PartialEq, Eq)]
964 struct ModifiedChunk {
965 /// The first to be removed from the original text
966 pub line_number_orig: u32,
967 /// The number of lines which have been replaced
968 pub lines_removed: u32,
970 pub lines: Vec<String>,
973 /// Set of changed sections of a file.
974 #[derive(Debug, PartialEq, Eq)]
975 struct ModifiedLines {
976 /// The set of changed chunks.
977 pub chunks: Vec<ModifiedChunk>,
980 /// Format a file and return a `ModifiedLines` data structure describing
981 /// the changed ranges of lines.
983 fn get_modified_lines(
986 ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
987 use std::io::BufRead;
989 let mut data = Vec::new();
991 let mut config = config.clone();
992 config.set().emit_mode(config::EmitMode::ModifiedLines);
993 format_input(input, &config, Some(&mut data))?;
995 let mut lines = data.lines();
996 let mut chunks = Vec::new();
997 while let Some(Ok(header)) = lines.next() {
998 // Parse the header line
999 let values: Vec<_> = header
1001 .map(|s| s.parse::<u32>().unwrap())
1003 assert_eq!(values.len(), 3);
1004 let line_number_orig = values[0];
1005 let lines_removed = values[1];
1006 let num_added = values[2];
1007 let mut added_lines = Vec::new();
1008 for _ in 0..num_added {
1009 added_lines.push(lines.next().unwrap().unwrap());
1011 chunks.push(ModifiedChunk {
1017 Ok(ModifiedLines { chunks })
1022 use super::{format_code_block, format_snippet, Config};
1025 fn test_no_panic_on_format_snippet_and_format_code_block() {
1026 // `format_snippet()` and `format_code_block()` should not panic
1027 // even when we cannot parse the given snippet.
1028 let snippet = "let";
1029 assert!(format_snippet(snippet, &Config::default()).is_none());
1030 assert!(format_code_block(snippet, &Config::default()).is_none());
1033 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
1035 F: Fn(&str, &Config) -> Option<String>,
1037 let output = formatter(input, &Config::default());
1038 output.is_some() && output.unwrap() == expected
1042 fn test_format_snippet() {
1043 let snippet = "fn main() { println!(\"hello, world\"); }";
1044 #[cfg(not(windows))]
1045 let expected = "fn main() {\n \
1046 println!(\"hello, world\");\n\
1049 let expected = "fn main() {\r\n \
1050 println!(\"hello, world\");\r\n\
1052 assert!(test_format_inner(format_snippet, snippet, expected));
1056 fn test_format_code_block_fail() {
1058 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1059 assert!(format_code_block(code_block, &Config::default()).is_none());
1063 fn test_format_code_block() {
1064 // simple code block
1065 let code_block = "let x=3;";
1066 let expected = "let x = 3;";
1067 assert!(test_format_inner(format_code_block, code_block, expected));
1069 // more complex code block, taken from chains.rs.
1071 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1073 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1074 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1076 } else if is_block_expr(context, &parent, &parent_rewrite) {
1077 match context.config.indent_style() {
1078 // Try to put the first child on the same line with parent's last line
1079 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1080 // The parent is a block, so align the rest of the chain with the closing
1082 IndentStyle::Visual => (parent_shape, false),
1086 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1092 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1094 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1095 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1097 } else if is_block_expr(context, &parent, &parent_rewrite) {
1098 match context.config.indent_style() {
1099 // Try to put the first child on the same line with parent's last line
1100 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1101 // The parent is a block, so align the rest of the chain with the closing
1103 IndentStyle::Visual => (parent_shape, false),
1107 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1111 assert!(test_format_inner(format_code_block, code_block, expected));