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;
92 pub(crate) mod rustfmt_diff;
100 pub(crate) mod visitor;
102 // A map of the files of a crate, with their new content
103 pub(crate) type FileMap = Vec<FileRecord>;
105 pub(crate) type FileRecord = (FileName, String);
107 /// The various errors that can occur during formatting. Note that not all of
108 /// these can currently be propagated to clients.
109 #[derive(Fail, Debug)]
111 /// Line has exceeded character limit (found, maximum).
113 display = "line formatted, but exceeded maximum width \
114 (maximum: {} (see `max_width` option), found: {})",
118 LineOverflow(usize, usize),
119 /// Line ends in whitespace.
120 #[fail(display = "left behind trailing whitespace")]
122 /// TODO or FIXME item without an issue number.
123 #[fail(display = "found {}", _0)]
125 /// License check has failed.
126 #[fail(display = "license check failed")]
128 /// Used deprecated skip attribute.
129 #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
131 /// Used a rustfmt:: attribute other than skip.
132 #[fail(display = "invalid attribute")]
134 /// An io error during reading or writing.
135 #[fail(display = "io error: {}", _0)]
137 /// Parse error occured when parsing the Input.
138 #[fail(display = "parse error")]
140 /// The user mandated a version and the current version of Rustfmt does not
141 /// satisfy that requirement.
142 #[fail(display = "Version mismatch")]
146 impl From<io::Error> for ErrorKind {
147 fn from(e: io::Error) -> ErrorKind {
148 ErrorKind::IoError(e)
152 struct FormattingError {
160 impl FormattingError {
161 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
163 line: codemap.lookup_char_pos(span.lo()).line,
168 .span_to_lines(*span)
172 .get_line(fl.lines[0].line_index)
173 .map(|l| l.into_owned())
175 .unwrap_or_else(|| String::new()),
178 fn msg_prefix(&self) -> &str {
180 ErrorKind::LineOverflow(..)
181 | ErrorKind::TrailingWhitespace
182 | ErrorKind::IoError(_)
183 | ErrorKind::ParseError => "internal error:",
184 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
185 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
189 fn msg_suffix(&self) -> &str {
190 if self.is_comment || self.is_string {
191 "set `error_on_unformatted = false` to suppress \
192 the warning against comments or string literals\n"
199 fn format_len(&self) -> (usize, usize) {
201 ErrorKind::LineOverflow(found, max) => (max, found - max),
202 ErrorKind::TrailingWhitespace | ErrorKind::DeprecatedAttr | ErrorKind::BadAttr => {
203 let trailing_ws_start = self
205 .rfind(|c: char| !c.is_whitespace())
210 self.line_buffer.len() - trailing_ws_start,
218 /// Reports on any issues that occurred during a run of Rustfmt.
220 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
222 pub struct FormatReport {
223 // Maps stringified file paths to their associated formatting errors.
224 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
227 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
229 #[derive(Default, Debug)]
230 struct ReportedErrors {
231 has_operational_errors: bool,
232 has_check_errors: bool,
236 fn new() -> FormatReport {
238 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
242 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
243 self.track_errors(&v);
248 .and_modify(|fe| fe.append(&mut v))
252 fn track_errors(&self, new_errors: &[FormattingError]) {
253 let errs = &mut self.internal.borrow_mut().1;
254 if errs.has_operational_errors && errs.has_check_errors {
257 for err in new_errors {
259 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
260 errs.has_operational_errors = true;
262 ErrorKind::BadIssue(_)
263 | ErrorKind::LicenseCheck
264 | ErrorKind::DeprecatedAttr
266 | ErrorKind::VersionMismatch => {
267 errs.has_check_errors = true;
274 fn warning_count(&self) -> usize {
279 .map(|(_, errors)| errors.len())
283 /// Whether any warnings or errors are present in the report.
284 pub fn has_warnings(&self) -> bool {
285 self.warning_count() > 0
288 /// Print the report to a terminal using colours and potentially other
292 mut t: Box<term::Terminal<Output = io::Stderr>>,
293 ) -> Result<(), term::Error> {
294 for (file, errors) in &self.internal.borrow().0 {
295 for error in errors {
296 let prefix_space_len = error.line.to_string().len();
297 let prefix_spaces = " ".repeat(1 + prefix_space_len);
299 // First line: the overview of error
300 t.fg(term::color::RED)?;
301 t.attr(term::Attr::Bold)?;
302 write!(t, "{} ", error.msg_prefix())?;
304 t.attr(term::Attr::Bold)?;
305 writeln!(t, "{}", error.kind)?;
307 // Second line: file info
308 write!(t, "{}--> ", &prefix_spaces[1..])?;
310 writeln!(t, "{}:{}", file, error.line)?;
312 // Third to fifth lines: show the line which triggered error, if available.
313 if !error.line_buffer.is_empty() {
314 let (space_len, target_len) = error.format_len();
315 t.attr(term::Attr::Bold)?;
316 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
318 writeln!(t, "{}", error.line_buffer)?;
319 t.attr(term::Attr::Bold)?;
320 write!(t, "{}| ", prefix_spaces)?;
321 t.fg(term::color::RED)?;
322 writeln!(t, "{}", target_str(space_len, target_len))?;
326 // The last line: show note if available.
327 let msg_suffix = error.msg_suffix();
328 if !msg_suffix.is_empty() {
329 t.attr(term::Attr::Bold)?;
330 write!(t, "{}= note: ", prefix_spaces)?;
332 writeln!(t, "{}", error.msg_suffix())?;
340 if !self.internal.borrow().0.is_empty() {
341 t.attr(term::Attr::Bold)?;
342 write!(t, "warning: ")?;
346 "rustfmt may have failed to format. See previous {} errors.\n\n",
347 self.warning_count(),
355 fn target_str(space_len: usize, target_len: usize) -> String {
356 let empty_line = " ".repeat(space_len);
357 let overflowed = "^".repeat(target_len);
358 empty_line + &overflowed
361 impl fmt::Display for FormatReport {
362 // Prints all the formatting errors.
363 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
364 for (file, errors) in &self.internal.borrow().0 {
365 for error in errors {
366 let prefix_space_len = error.line.to_string().len();
367 let prefix_spaces = " ".repeat(1 + prefix_space_len);
369 let error_line_buffer = if error.line_buffer.is_empty() {
372 let (space_len, target_len) = error.format_len();
374 "{}|\n{} | {}\n{}| {}",
379 target_str(space_len, target_len)
383 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
384 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
385 let msg_suffix = error.msg_suffix();
386 let note = if msg_suffix.is_empty() {
389 format!("{}note= ", prefix_spaces)
403 if !self.internal.borrow().0.is_empty() {
406 "warning: rustfmt may have failed to format. See previous {} errors.",
407 self.warning_count(),
414 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
418 if config.verbose() == Verbosity::Verbose && path != &FileName::Stdin {
423 // Formatting which depends on the AST.
426 parse_session: &mut ParseSess,
427 main_file: &FileName,
429 report: FormatReport,
431 ) -> Result<(FileMap, bool, bool), io::Error>
433 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
435 let mut result = FileMap::new();
436 // diff mode: check if any files are differing
437 let mut has_diff = false;
438 let mut has_macro_rewrite_failure = false;
440 let skip_children = config.skip_children();
441 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
442 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
445 should_emit_verbose(&path, config, || println!("Formatting {}", path));
446 let filemap = parse_session
448 .lookup_char_pos(module.inner.lo())
450 let big_snippet = filemap.src.as_ref().unwrap();
451 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
453 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
454 // Format inner attributes if available.
455 if !krate.attrs.is_empty() && path == *main_file {
456 visitor.skip_empty_lines(filemap.end_pos);
457 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
458 visitor.push_rewrite(module.inner, None);
460 visitor.format_separate_mod(module, &*filemap);
463 visitor.last_pos = filemap.start_pos;
464 visitor.skip_empty_lines(filemap.end_pos);
465 visitor.format_separate_mod(module, &*filemap);
470 ::utils::count_newlines(&visitor.buffer)
473 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
474 Ok(result) => result,
476 // Create a new error with path_str to help users see which files failed
477 let err_msg = format!("{}: {}", path, e);
478 return Err(io::Error::new(e.kind(), err_msg));
482 has_macro_rewrite_failure |= visitor.macro_rewrite_failure;
484 result.push((path.clone(), visitor.buffer));
487 Ok((result, has_diff, has_macro_rewrite_failure))
490 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
491 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
494 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
497 fn should_report_error(
499 char_kind: FullCodeCharKind,
501 error_kind: &ErrorKind,
503 let allow_error_report = if char_kind.is_comment() || is_string {
504 config.error_on_unformatted()
510 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
511 ErrorKind::TrailingWhitespace => allow_error_report,
516 // Formatting done on a char by char or line by line basis.
517 // FIXME(#20) other stuff for parity with make tidy
521 skipped_range: &[(usize, usize)],
523 report: &FormatReport,
525 let mut last_was_space = false;
526 let mut line_len = 0;
527 let mut cur_line = 1;
528 let mut newline_count = 0;
529 let mut errors = vec![];
530 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
531 let mut line_buffer = String::with_capacity(config.max_width() * 2);
532 let mut is_string = false; // true if the current line contains a string literal.
533 let mut format_line = config.file_lines().contains_line(name, cur_line);
534 let allow_issue_seek = !issue_seeker.is_disabled();
537 if let Some(ref license_template) = config.license_template {
538 if !license_template.is_match(text) {
539 errors.push(FormattingError {
541 kind: ErrorKind::LicenseCheck,
544 line_buffer: String::new(),
549 // Iterate over the chars in the file map.
550 for (kind, c) in CharClasses::new(text.chars()) {
555 if allow_issue_seek && format_line {
556 // Add warnings for bad todos/ fixmes
557 if let Some(issue) = issue_seeker.inspect(c) {
558 errors.push(FormattingError {
560 kind: ErrorKind::BadIssue(issue),
563 line_buffer: String::new(),
570 // Check for (and record) trailing whitespace.
572 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
573 && !is_skipped_line(cur_line, skipped_range)
575 errors.push(FormattingError {
577 kind: ErrorKind::TrailingWhitespace,
578 is_comment: kind.is_comment(),
579 is_string: kind.is_string(),
580 line_buffer: line_buffer.clone(),
586 // Check for any line width errors we couldn't correct.
587 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
588 if line_len > config.max_width()
589 && !is_skipped_line(cur_line, skipped_range)
590 && should_report_error(config, kind, is_string, &error_kind)
592 errors.push(FormattingError {
595 is_comment: kind.is_comment(),
597 line_buffer: line_buffer.clone(),
604 format_line = config.file_lines().contains_line(name, cur_line);
606 last_was_space = false;
611 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
612 last_was_space = c.is_whitespace();
614 if kind.is_string() {
620 if newline_count > 1 {
621 debug!("track truncate: {} {}", text.len(), newline_count);
622 let line = text.len() - newline_count + 1;
626 report.append(name.clone(), errors);
629 fn parse_input<'sess>(
631 parse_session: &'sess ParseSess,
633 ) -> Result<ast::Crate, ParseError<'sess>> {
634 let mut parser = match input {
635 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
636 Input::Text(text) => parse::new_parser_from_source_str(
638 syntax::codemap::FileName::Custom("stdin".to_owned()),
643 parser.cfg_mods = false;
644 if config.skip_children() {
645 parser.recurse_into_file_modules = false;
648 let mut parser = AssertUnwindSafe(parser);
649 let result = catch_unwind(move || parser.0.parse_crate_mod());
653 if parse_session.span_diagnostic.has_errors() {
654 // Bail out if the parser recovered from an error.
655 Err(ParseError::Recovered)
660 Ok(Err(e)) => Err(ParseError::Error(e)),
661 Err(_) => Err(ParseError::Panic),
665 /// All the ways that parsing can fail.
666 enum ParseError<'sess> {
667 /// There was an error, but the parser recovered.
669 /// There was an error (supplied) and parsing failed.
670 Error(DiagnosticBuilder<'sess>),
671 /// The parser panicked.
675 /// Format the given snippet. The snippet is expected to be *complete* code.
676 /// When we cannot parse the given snippet, this function returns `None`.
677 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
678 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
679 let input = Input::Text(snippet.into());
680 let mut config = config.clone();
681 config.set().emit_mode(config::EmitMode::Stdout);
682 config.set().verbose(Verbosity::Quiet);
683 config.set().hide_parse_errors(true);
684 match format_input(input, &config, Some(&mut out)) {
685 // `format_input()` returns an empty string on parsing error.
686 Ok((summary, _)) if summary.has_macro_formatting_failure() => None,
687 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
688 Ok(..) => String::from_utf8(out).ok(),
693 const FN_MAIN_PREFIX: &str = "fn main() {\n";
695 fn enclose_in_main_block(s: &str, config: &Config) -> String {
696 let indent = Indent::from_width(config, config.tab_spaces());
697 let mut result = String::with_capacity(s.len() * 2);
698 result.push_str(FN_MAIN_PREFIX);
699 let mut need_indent = true;
700 for (kind, line) in LineClasses::new(s) {
702 result.push_str(&indent.to_string(config));
704 result.push_str(&line);
706 need_indent = !kind.is_string() || line.ends_with('\\');
712 /// Format the given code block. Mainly targeted for code block in comment.
713 /// The code block may be incomplete (i.e. parser may be unable to parse it).
714 /// To avoid panic in parser, we wrap the code block with a dummy function.
715 /// The returned code block does *not* end with newline.
716 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
717 // Wrap the given code block with `fn main()` if it does not have one.
718 let snippet = enclose_in_main_block(code_snippet, config);
719 let mut result = String::with_capacity(snippet.len());
720 let mut is_first = true;
722 // While formatting the code, ignore the config's newline style setting and always use "\n"
723 // instead of "\r\n" for the newline characters. This is okay because the output here is
724 // not directly outputted by rustfmt command, but used by the comment formatter's input.
725 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
726 let mut config_with_unix_newline = config.clone();
727 config_with_unix_newline
729 .newline_style(NewlineStyle::Unix);
730 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
732 // Trim "fn main() {" on the first line and "}" on the last line,
733 // then unindent the whole code block.
734 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
735 let mut is_indented = true;
736 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
742 let trimmed_line = if !is_indented {
744 } else if line.len() > config.max_width() {
745 // If there are lines that are larger than max width, we cannot tell
746 // whether we have succeeded but have some comments or strings that
747 // are too long, or we have failed to format code block. We will be
748 // conservative and just return `None` in this case.
750 } else if line.len() > config.tab_spaces() {
751 // Make sure that the line has leading whitespaces.
752 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
753 if line.starts_with(indent_str.as_ref()) {
754 let offset = if config.hard_tabs() {
766 result.push_str(trimmed_line);
767 is_indented = !kind.is_string() || line.ends_with('\\');
778 /// The main entry point for Rustfmt. Formats the given input according to the
779 /// given config. `out` is only necessary if required by the configuration.
780 pub fn format_input<T: Write>(
784 ) -> Result<(Summary, FormatReport), (ErrorKind, Summary)> {
785 if !config.version_meets_requirement() {
786 return Err((ErrorKind::VersionMismatch, Summary::default()));
789 syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| (tup.0, tup.2))
792 fn format_input_inner<T: Write>(
795 mut out: Option<&mut T>,
796 ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
797 syntax_pos::hygiene::set_default_edition(config.edition().to_libsyntax_pos_edition());
798 let mut summary = Summary::default();
799 if config.disable_all_formatting() {
800 // When the input is from stdin, echo back the input.
801 if let Input::Text(ref buf) = input {
802 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
803 return Err((From::from(e), summary));
806 return Ok((summary, FileMap::new(), FormatReport::new()));
808 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
810 let tty_handler = if config.hide_parse_errors() {
811 let silent_emitter = Box::new(EmitterWriter::new(
812 Box::new(Vec::new()),
813 Some(codemap.clone()),
817 Handler::with_emitter(true, false, silent_emitter)
819 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
820 let color_cfg = if supports_color {
825 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
827 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
829 let main_file = match input {
830 Input::File(ref file) => FileName::Real(file.clone()),
831 Input::Text(..) => FileName::Stdin,
834 let krate = match parse_input(input, &parse_session, config) {
838 ParseError::Error(mut diagnostic) => diagnostic.emit(),
839 ParseError::Panic => {
840 // Note that if you see this message and want more information,
841 // then go to `parse_input` and run the parse function without
842 // `catch_unwind` so rustfmt panics and you can get a backtrace.
843 should_emit_verbose(&main_file, config, || {
844 println!("The Rust parser panicked")
847 ParseError::Recovered => {}
849 summary.add_parsing_error();
850 return Err((ErrorKind::ParseError, summary));
854 summary.mark_parse_time();
856 // Suppress error output after parsing.
857 let silent_emitter = Box::new(EmitterWriter::new(
858 Box::new(Vec::new()),
859 Some(codemap.clone()),
863 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
865 let report = FormatReport::new();
867 let format_result = format_ast(
873 |file_name, file, skipped_range, report| {
874 // For some reason, the codemap does not include terminating
875 // newlines so we must add one on for each file. This is sad.
876 filemap::append_newline(file);
878 format_lines(file, file_name, skipped_range, config, report);
879 replace_with_system_newlines(file, config);
881 if let Some(ref mut out) = out {
882 return filemap::write_file(file, file_name, out, config);
888 summary.mark_format_time();
890 should_emit_verbose(&main_file, config, || {
891 fn duration_to_f32(d: Duration) -> f32 {
892 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
896 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
897 duration_to_f32(summary.get_parse_time().unwrap()),
898 duration_to_f32(summary.get_format_time().unwrap()),
903 let report_errs = &report.internal.borrow().1;
904 if report_errs.has_check_errors {
905 summary.add_check_error();
907 if report_errs.has_operational_errors {
908 summary.add_operational_error();
912 match format_result {
913 Ok((file_map, has_diff, has_macro_rewrite_failure)) => {
914 if report.has_warnings() {
915 summary.add_formatting_error();
922 if has_macro_rewrite_failure {
923 summary.add_macro_foramt_failure();
926 Ok((summary, file_map, report))
928 Err(e) => Err((From::from(e), summary)),
932 pub fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
933 let style = if config.newline_style() == NewlineStyle::Native {
935 NewlineStyle::Windows
940 config.newline_style()
944 NewlineStyle::Unix => return,
945 NewlineStyle::Windows => {
946 let mut transformed = String::with_capacity(text.capacity());
947 for c in text.chars() {
949 '\n' => transformed.push_str("\r\n"),
951 c => transformed.push(c),
956 NewlineStyle::Native => unreachable!(),
960 /// A single span of changed lines, with 0 or more removed lines
961 /// and a vector of 0 or more inserted lines.
962 #[derive(Debug, PartialEq, Eq)]
963 struct ModifiedChunk {
964 /// The first to be removed from the original text
965 pub line_number_orig: u32,
966 /// The number of lines which have been replaced
967 pub lines_removed: u32,
969 pub lines: Vec<String>,
972 /// Set of changed sections of a file.
973 #[derive(Debug, PartialEq, Eq)]
974 struct ModifiedLines {
975 /// The set of changed chunks.
976 pub chunks: Vec<ModifiedChunk>,
979 /// Format a file and return a `ModifiedLines` data structure describing
980 /// the changed ranges of lines.
982 fn get_modified_lines(
985 ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
986 use std::io::BufRead;
988 let mut data = Vec::new();
990 let mut config = config.clone();
991 config.set().emit_mode(config::EmitMode::ModifiedLines);
992 format_input(input, &config, Some(&mut data))?;
994 let mut lines = data.lines();
995 let mut chunks = Vec::new();
996 while let Some(Ok(header)) = lines.next() {
997 // Parse the header line
998 let values: Vec<_> = header
1000 .map(|s| s.parse::<u32>().unwrap())
1002 assert_eq!(values.len(), 3);
1003 let line_number_orig = values[0];
1004 let lines_removed = values[1];
1005 let num_added = values[2];
1006 let mut added_lines = Vec::new();
1007 for _ in 0..num_added {
1008 added_lines.push(lines.next().unwrap().unwrap());
1010 chunks.push(ModifiedChunk {
1016 Ok(ModifiedLines { chunks })
1021 use super::{format_code_block, format_snippet, Config};
1024 fn test_no_panic_on_format_snippet_and_format_code_block() {
1025 // `format_snippet()` and `format_code_block()` should not panic
1026 // even when we cannot parse the given snippet.
1027 let snippet = "let";
1028 assert!(format_snippet(snippet, &Config::default()).is_none());
1029 assert!(format_code_block(snippet, &Config::default()).is_none());
1032 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
1034 F: Fn(&str, &Config) -> Option<String>,
1036 let output = formatter(input, &Config::default());
1037 output.is_some() && output.unwrap() == expected
1041 fn test_format_snippet() {
1042 let snippet = "fn main() { println!(\"hello, world\"); }";
1043 let expected = "fn main() {\n \
1044 println!(\"hello, world\");\n\
1046 assert!(test_format_inner(format_snippet, snippet, expected));
1050 fn test_format_code_block_fail() {
1052 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1053 assert!(format_code_block(code_block, &Config::default()).is_none());
1057 fn test_format_code_block() {
1058 // simple code block
1059 let code_block = "let x=3;";
1060 let expected = "let x = 3;";
1061 assert!(test_format_inner(format_code_block, code_block, expected));
1063 // more complex code block, taken from chains.rs.
1065 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1067 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1068 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1070 } else if is_block_expr(context, &parent, &parent_rewrite) {
1071 match context.config.indent_style() {
1072 // Try to put the first child on the same line with parent's last line
1073 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1074 // The parent is a block, so align the rest of the chain with the closing
1076 IndentStyle::Visual => (parent_shape, false),
1080 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1086 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1088 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1089 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1091 } else if is_block_expr(context, &parent, &parent_rewrite) {
1092 match context.config.indent_style() {
1093 // Try to put the first child on the same line with parent's last line
1094 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1095 // The parent is a block, so align the rest of the chain with the closing
1097 IndentStyle::Visual => (parent_shape, false),
1101 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1105 assert!(test_format_inner(format_code_block, code_block, expected));