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")]
145 /// If we had formatted the given node, then we would have lost a comment.
146 #[fail(display = "not formatted because a comment would be lost")]
151 fn is_comment(&self) -> bool {
153 ErrorKind::LostComment => true,
159 impl From<io::Error> for ErrorKind {
160 fn from(e: io::Error) -> ErrorKind {
161 ErrorKind::IoError(e)
165 struct FormattingError {
173 impl FormattingError {
174 fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
176 line: codemap.lookup_char_pos(span.lo()).line,
177 is_comment: kind.is_comment(),
181 .span_to_lines(*span)
185 .get_line(fl.lines[0].line_index)
186 .map(|l| l.into_owned())
188 .unwrap_or_else(|| String::new()),
191 fn msg_prefix(&self) -> &str {
193 ErrorKind::LineOverflow(..)
194 | ErrorKind::TrailingWhitespace
195 | ErrorKind::IoError(_)
196 | ErrorKind::ParseError
197 | ErrorKind::LostComment => "internal error:",
198 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
199 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
203 fn msg_suffix(&self) -> &str {
204 if self.is_comment || self.is_string {
205 "set `error_on_unformatted = false` to suppress \
206 the warning against comments or string literals\n"
213 fn format_len(&self) -> (usize, usize) {
215 ErrorKind::LineOverflow(found, max) => (max, found - max),
216 ErrorKind::TrailingWhitespace
217 | ErrorKind::DeprecatedAttr
219 | ErrorKind::LostComment => {
220 let trailing_ws_start = self
222 .rfind(|c: char| !c.is_whitespace())
227 self.line_buffer.len() - trailing_ws_start,
235 /// Reports on any issues that occurred during a run of Rustfmt.
237 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
239 pub struct FormatReport {
240 // Maps stringified file paths to their associated formatting errors.
241 internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
244 type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
246 #[derive(Default, Debug)]
247 struct ReportedErrors {
248 has_operational_errors: bool,
249 has_check_errors: bool,
253 fn new() -> FormatReport {
255 internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
259 fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
260 self.track_errors(&v);
265 .and_modify(|fe| fe.append(&mut v))
269 fn track_errors(&self, new_errors: &[FormattingError]) {
270 let errs = &mut self.internal.borrow_mut().1;
271 if errs.has_operational_errors && errs.has_check_errors {
274 for err in new_errors {
276 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
277 errs.has_operational_errors = true;
279 ErrorKind::BadIssue(_)
280 | ErrorKind::LicenseCheck
281 | ErrorKind::DeprecatedAttr
283 | ErrorKind::VersionMismatch => {
284 errs.has_check_errors = true;
291 fn warning_count(&self) -> usize {
296 .map(|(_, errors)| errors.len())
300 /// Whether any warnings or errors are present in the report.
301 pub fn has_warnings(&self) -> bool {
302 self.warning_count() > 0
305 /// Print the report to a terminal using colours and potentially other
309 mut t: Box<term::Terminal<Output = io::Stderr>>,
310 ) -> Result<(), term::Error> {
311 for (file, errors) in &self.internal.borrow().0 {
312 for error in errors {
313 let prefix_space_len = error.line.to_string().len();
314 let prefix_spaces = " ".repeat(1 + prefix_space_len);
316 // First line: the overview of error
317 t.fg(term::color::RED)?;
318 t.attr(term::Attr::Bold)?;
319 write!(t, "{} ", error.msg_prefix())?;
321 t.attr(term::Attr::Bold)?;
322 writeln!(t, "{}", error.kind)?;
324 // Second line: file info
325 write!(t, "{}--> ", &prefix_spaces[1..])?;
327 writeln!(t, "{}:{}", file, error.line)?;
329 // Third to fifth lines: show the line which triggered error, if available.
330 if !error.line_buffer.is_empty() {
331 let (space_len, target_len) = error.format_len();
332 t.attr(term::Attr::Bold)?;
333 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
335 writeln!(t, "{}", error.line_buffer)?;
336 t.attr(term::Attr::Bold)?;
337 write!(t, "{}| ", prefix_spaces)?;
338 t.fg(term::color::RED)?;
339 writeln!(t, "{}", target_str(space_len, target_len))?;
343 // The last line: show note if available.
344 let msg_suffix = error.msg_suffix();
345 if !msg_suffix.is_empty() {
346 t.attr(term::Attr::Bold)?;
347 write!(t, "{}= note: ", prefix_spaces)?;
349 writeln!(t, "{}", error.msg_suffix())?;
357 if !self.internal.borrow().0.is_empty() {
358 t.attr(term::Attr::Bold)?;
359 write!(t, "warning: ")?;
363 "rustfmt may have failed to format. See previous {} errors.\n\n",
364 self.warning_count(),
372 fn target_str(space_len: usize, target_len: usize) -> String {
373 let empty_line = " ".repeat(space_len);
374 let overflowed = "^".repeat(target_len);
375 empty_line + &overflowed
378 impl fmt::Display for FormatReport {
379 // Prints all the formatting errors.
380 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
381 for (file, errors) in &self.internal.borrow().0 {
382 for error in errors {
383 let prefix_space_len = error.line.to_string().len();
384 let prefix_spaces = " ".repeat(1 + prefix_space_len);
386 let error_line_buffer = if error.line_buffer.is_empty() {
389 let (space_len, target_len) = error.format_len();
391 "{}|\n{} | {}\n{}| {}",
396 target_str(space_len, target_len)
400 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
401 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
402 let msg_suffix = error.msg_suffix();
403 let note = if msg_suffix.is_empty() {
406 format!("{}note= ", prefix_spaces)
420 if !self.internal.borrow().0.is_empty() {
423 "warning: rustfmt may have failed to format. See previous {} errors.",
424 self.warning_count(),
431 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
435 if config.verbose() == Verbosity::Verbose && path != &FileName::Stdin {
440 // Formatting which depends on the AST.
443 parse_session: &mut ParseSess,
444 main_file: &FileName,
446 report: FormatReport,
448 ) -> Result<(FileMap, bool, bool), io::Error>
450 F: FnMut(&FileName, &mut String, &[(usize, usize)], &FormatReport) -> Result<bool, io::Error>,
452 let mut result = FileMap::new();
453 // diff mode: check if any files are differing
454 let mut has_diff = false;
455 let mut has_macro_rewrite_failure = false;
457 let skip_children = config.skip_children();
458 for (path, module) in modules::list_files(krate, parse_session.codemap())? {
459 if (skip_children && path != *main_file) || config.ignore().skip_file(&path) {
462 should_emit_verbose(&path, config, || println!("Formatting {}", path));
463 let filemap = parse_session
465 .lookup_char_pos(module.inner.lo())
467 let big_snippet = filemap.src.as_ref().unwrap();
468 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
470 FmtVisitor::from_codemap(parse_session, config, &snippet_provider, report.clone());
471 // Format inner attributes if available.
472 if !krate.attrs.is_empty() && path == *main_file {
473 visitor.skip_empty_lines(filemap.end_pos);
474 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
475 visitor.push_rewrite(module.inner, None);
477 visitor.format_separate_mod(module, &*filemap);
480 visitor.last_pos = filemap.start_pos;
481 visitor.skip_empty_lines(filemap.end_pos);
482 visitor.format_separate_mod(module, &*filemap);
487 ::utils::count_newlines(&visitor.buffer)
490 has_diff |= match after_file(&path, &mut visitor.buffer, &visitor.skipped_range, &report) {
491 Ok(result) => result,
493 // Create a new error with path_str to help users see which files failed
494 let err_msg = format!("{}: {}", path, e);
495 return Err(io::Error::new(e.kind(), err_msg));
499 has_macro_rewrite_failure |= visitor.macro_rewrite_failure;
501 result.push((path.clone(), visitor.buffer));
504 Ok((result, has_diff, has_macro_rewrite_failure))
507 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
508 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
511 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
514 fn should_report_error(
516 char_kind: FullCodeCharKind,
518 error_kind: &ErrorKind,
520 let allow_error_report = if char_kind.is_comment() || is_string || error_kind.is_comment() {
521 config.error_on_unformatted()
527 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
528 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
533 // Formatting done on a char by char or line by line basis.
534 // FIXME(#20) other stuff for parity with make tidy
538 skipped_range: &[(usize, usize)],
540 report: &FormatReport,
542 let mut last_was_space = false;
543 let mut line_len = 0;
544 let mut cur_line = 1;
545 let mut newline_count = 0;
546 let mut errors = vec![];
547 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
548 let mut line_buffer = String::with_capacity(config.max_width() * 2);
549 let mut is_string = false; // true if the current line contains a string literal.
550 let mut format_line = config.file_lines().contains_line(name, cur_line);
551 let allow_issue_seek = !issue_seeker.is_disabled();
554 if let Some(ref license_template) = config.license_template {
555 if !license_template.is_match(text) {
556 errors.push(FormattingError {
558 kind: ErrorKind::LicenseCheck,
561 line_buffer: String::new(),
566 // Iterate over the chars in the file map.
567 for (kind, c) in CharClasses::new(text.chars()) {
572 if allow_issue_seek && format_line {
573 // Add warnings for bad todos/ fixmes
574 if let Some(issue) = issue_seeker.inspect(c) {
575 errors.push(FormattingError {
577 kind: ErrorKind::BadIssue(issue),
580 line_buffer: String::new(),
587 // Check for (and record) trailing whitespace.
589 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
590 && !is_skipped_line(cur_line, skipped_range)
592 errors.push(FormattingError {
594 kind: ErrorKind::TrailingWhitespace,
595 is_comment: kind.is_comment(),
596 is_string: kind.is_string(),
597 line_buffer: line_buffer.clone(),
603 // Check for any line width errors we couldn't correct.
604 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
605 if line_len > config.max_width()
606 && !is_skipped_line(cur_line, skipped_range)
607 && should_report_error(config, kind, is_string, &error_kind)
609 errors.push(FormattingError {
612 is_comment: kind.is_comment(),
614 line_buffer: line_buffer.clone(),
621 format_line = config.file_lines().contains_line(name, cur_line);
623 last_was_space = false;
628 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
629 last_was_space = c.is_whitespace();
631 if kind.is_string() {
637 if newline_count > 1 {
638 debug!("track truncate: {} {}", text.len(), newline_count);
639 let line = text.len() - newline_count + 1;
643 report.append(name.clone(), errors);
646 fn parse_input<'sess>(
648 parse_session: &'sess ParseSess,
650 ) -> Result<ast::Crate, ParseError<'sess>> {
651 let mut parser = match input {
652 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
653 Input::Text(text) => parse::new_parser_from_source_str(
655 syntax::codemap::FileName::Custom("stdin".to_owned()),
660 parser.cfg_mods = false;
661 if config.skip_children() {
662 parser.recurse_into_file_modules = false;
665 let mut parser = AssertUnwindSafe(parser);
666 let result = catch_unwind(move || parser.0.parse_crate_mod());
670 if parse_session.span_diagnostic.has_errors() {
671 // Bail out if the parser recovered from an error.
672 Err(ParseError::Recovered)
677 Ok(Err(e)) => Err(ParseError::Error(e)),
678 Err(_) => Err(ParseError::Panic),
682 /// All the ways that parsing can fail.
683 enum ParseError<'sess> {
684 /// There was an error, but the parser recovered.
686 /// There was an error (supplied) and parsing failed.
687 Error(DiagnosticBuilder<'sess>),
688 /// The parser panicked.
692 /// Format the given snippet. The snippet is expected to be *complete* code.
693 /// When we cannot parse the given snippet, this function returns `None`.
694 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
695 let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
696 let input = Input::Text(snippet.into());
697 let mut config = config.clone();
698 config.set().emit_mode(config::EmitMode::Stdout);
699 config.set().verbose(Verbosity::Quiet);
700 config.set().hide_parse_errors(true);
701 match format_input(input, &config, Some(&mut out)) {
702 // `format_input()` returns an empty string on parsing error.
703 Ok((summary, _)) if summary.has_macro_formatting_failure() => None,
704 Ok(..) if out.is_empty() && !snippet.is_empty() => None,
705 Ok(..) => String::from_utf8(out).ok(),
710 const FN_MAIN_PREFIX: &str = "fn main() {\n";
712 fn enclose_in_main_block(s: &str, config: &Config) -> String {
713 let indent = Indent::from_width(config, config.tab_spaces());
714 let mut result = String::with_capacity(s.len() * 2);
715 result.push_str(FN_MAIN_PREFIX);
716 let mut need_indent = true;
717 for (kind, line) in LineClasses::new(s) {
719 result.push_str(&indent.to_string(config));
721 result.push_str(&line);
723 need_indent = !kind.is_string() || line.ends_with('\\');
729 /// Format the given code block. Mainly targeted for code block in comment.
730 /// The code block may be incomplete (i.e. parser may be unable to parse it).
731 /// To avoid panic in parser, we wrap the code block with a dummy function.
732 /// The returned code block does *not* end with newline.
733 fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
734 // Wrap the given code block with `fn main()` if it does not have one.
735 let snippet = enclose_in_main_block(code_snippet, config);
736 let mut result = String::with_capacity(snippet.len());
737 let mut is_first = true;
739 // While formatting the code, ignore the config's newline style setting and always use "\n"
740 // instead of "\r\n" for the newline characters. This is okay because the output here is
741 // not directly outputted by rustfmt command, but used by the comment formatter's input.
742 // We have output-file-wide "\n" ==> "\r\n" conversion proccess after here if it's necessary.
743 let mut config_with_unix_newline = config.clone();
744 config_with_unix_newline
746 .newline_style(NewlineStyle::Unix);
747 let formatted = format_snippet(&snippet, &config_with_unix_newline)?;
749 // Trim "fn main() {" on the first line and "}" on the last line,
750 // then unindent the whole code block.
751 let block_len = formatted.rfind('}').unwrap_or(formatted.len());
752 let mut is_indented = true;
753 for (kind, ref line) in LineClasses::new(&formatted[FN_MAIN_PREFIX.len()..block_len]) {
759 let trimmed_line = if !is_indented {
761 } else if line.len() > config.max_width() {
762 // If there are lines that are larger than max width, we cannot tell
763 // whether we have succeeded but have some comments or strings that
764 // are too long, or we have failed to format code block. We will be
765 // conservative and just return `None` in this case.
767 } else if line.len() > config.tab_spaces() {
768 // Make sure that the line has leading whitespaces.
769 let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
770 if line.starts_with(indent_str.as_ref()) {
771 let offset = if config.hard_tabs() {
783 result.push_str(trimmed_line);
784 is_indented = !kind.is_string() || line.ends_with('\\');
795 /// The main entry point for Rustfmt. Formats the given input according to the
796 /// given config. `out` is only necessary if required by the configuration.
797 pub fn format_input<T: Write>(
801 ) -> Result<(Summary, FormatReport), (ErrorKind, Summary)> {
802 if !config.version_meets_requirement() {
803 return Err((ErrorKind::VersionMismatch, Summary::default()));
806 syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| (tup.0, tup.2))
809 fn format_input_inner<T: Write>(
812 mut out: Option<&mut T>,
813 ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
814 syntax_pos::hygiene::set_default_edition(config.edition().to_libsyntax_pos_edition());
815 let mut summary = Summary::default();
816 if config.disable_all_formatting() {
817 // When the input is from stdin, echo back the input.
818 if let Input::Text(ref buf) = input {
819 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
820 return Err((From::from(e), summary));
823 return Ok((summary, FileMap::new(), FormatReport::new()));
825 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
827 let tty_handler = if config.hide_parse_errors() {
828 let silent_emitter = Box::new(EmitterWriter::new(
829 Box::new(Vec::new()),
830 Some(codemap.clone()),
834 Handler::with_emitter(true, false, silent_emitter)
836 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
837 let color_cfg = if supports_color {
842 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
844 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
846 let main_file = match input {
847 Input::File(ref file) => FileName::Real(file.clone()),
848 Input::Text(..) => FileName::Stdin,
851 let krate = match parse_input(input, &parse_session, config) {
855 ParseError::Error(mut diagnostic) => diagnostic.emit(),
856 ParseError::Panic => {
857 // Note that if you see this message and want more information,
858 // then go to `parse_input` and run the parse function without
859 // `catch_unwind` so rustfmt panics and you can get a backtrace.
860 should_emit_verbose(&main_file, config, || {
861 println!("The Rust parser panicked")
864 ParseError::Recovered => {}
866 summary.add_parsing_error();
867 return Err((ErrorKind::ParseError, summary));
871 summary.mark_parse_time();
873 // Suppress error output after parsing.
874 let silent_emitter = Box::new(EmitterWriter::new(
875 Box::new(Vec::new()),
876 Some(codemap.clone()),
880 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
882 let report = FormatReport::new();
884 let format_result = format_ast(
890 |file_name, file, skipped_range, report| {
891 // For some reason, the codemap does not include terminating
892 // newlines so we must add one on for each file. This is sad.
893 filemap::append_newline(file);
895 format_lines(file, file_name, skipped_range, config, report);
896 replace_with_system_newlines(file, config);
898 if let Some(ref mut out) = out {
899 return filemap::write_file(file, file_name, out, config);
905 summary.mark_format_time();
907 should_emit_verbose(&main_file, config, || {
908 fn duration_to_f32(d: Duration) -> f32 {
909 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
913 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
914 duration_to_f32(summary.get_parse_time().unwrap()),
915 duration_to_f32(summary.get_format_time().unwrap()),
920 let report_errs = &report.internal.borrow().1;
921 if report_errs.has_check_errors {
922 summary.add_check_error();
924 if report_errs.has_operational_errors {
925 summary.add_operational_error();
929 match format_result {
930 Ok((file_map, has_diff, has_macro_rewrite_failure)) => {
931 if report.has_warnings() {
932 summary.add_formatting_error();
939 if has_macro_rewrite_failure {
940 summary.add_macro_foramt_failure();
943 Ok((summary, file_map, report))
945 Err(e) => Err((From::from(e), summary)),
949 fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
950 let style = if config.newline_style() == NewlineStyle::Native {
952 NewlineStyle::Windows
957 config.newline_style()
961 NewlineStyle::Unix => return,
962 NewlineStyle::Windows => {
963 let mut transformed = String::with_capacity(text.capacity());
964 for c in text.chars() {
966 '\n' => transformed.push_str("\r\n"),
968 c => transformed.push(c),
973 NewlineStyle::Native => unreachable!(),
977 /// A single span of changed lines, with 0 or more removed lines
978 /// and a vector of 0 or more inserted lines.
979 #[derive(Debug, PartialEq, Eq)]
980 struct ModifiedChunk {
981 /// The first to be removed from the original text
982 pub line_number_orig: u32,
983 /// The number of lines which have been replaced
984 pub lines_removed: u32,
986 pub lines: Vec<String>,
989 /// Set of changed sections of a file.
990 #[derive(Debug, PartialEq, Eq)]
991 struct ModifiedLines {
992 /// The set of changed chunks.
993 pub chunks: Vec<ModifiedChunk>,
996 /// Format a file and return a `ModifiedLines` data structure describing
997 /// the changed ranges of lines.
999 fn get_modified_lines(
1002 ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
1003 use std::io::BufRead;
1005 let mut data = Vec::new();
1007 let mut config = config.clone();
1008 config.set().emit_mode(config::EmitMode::ModifiedLines);
1009 format_input(input, &config, Some(&mut data))?;
1011 let mut lines = data.lines();
1012 let mut chunks = Vec::new();
1013 while let Some(Ok(header)) = lines.next() {
1014 // Parse the header line
1015 let values: Vec<_> = header
1017 .map(|s| s.parse::<u32>().unwrap())
1019 assert_eq!(values.len(), 3);
1020 let line_number_orig = values[0];
1021 let lines_removed = values[1];
1022 let num_added = values[2];
1023 let mut added_lines = Vec::new();
1024 for _ in 0..num_added {
1025 added_lines.push(lines.next().unwrap().unwrap());
1027 chunks.push(ModifiedChunk {
1033 Ok(ModifiedLines { chunks })
1038 use super::{format_code_block, format_snippet, Config};
1041 fn test_no_panic_on_format_snippet_and_format_code_block() {
1042 // `format_snippet()` and `format_code_block()` should not panic
1043 // even when we cannot parse the given snippet.
1044 let snippet = "let";
1045 assert!(format_snippet(snippet, &Config::default()).is_none());
1046 assert!(format_code_block(snippet, &Config::default()).is_none());
1049 fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
1051 F: Fn(&str, &Config) -> Option<String>,
1053 let output = formatter(input, &Config::default());
1054 output.is_some() && output.unwrap() == expected
1058 fn test_format_snippet() {
1059 let snippet = "fn main() { println!(\"hello, world\"); }";
1060 #[cfg(not(windows))]
1061 let expected = "fn main() {\n \
1062 println!(\"hello, world\");\n\
1065 let expected = "fn main() {\r\n \
1066 println!(\"hello, world\");\r\n\
1068 assert!(test_format_inner(format_snippet, snippet, expected));
1072 fn test_format_code_block_fail() {
1074 let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
1075 assert!(format_code_block(code_block, &Config::default()).is_none());
1079 fn test_format_code_block() {
1080 // simple code block
1081 let code_block = "let x=3;";
1082 let expected = "let x = 3;";
1083 assert!(test_format_inner(format_code_block, code_block, expected));
1085 // more complex code block, taken from chains.rs.
1087 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1089 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1090 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1092 } else if is_block_expr(context, &parent, &parent_rewrite) {
1093 match context.config.indent_style() {
1094 // Try to put the first child on the same line with parent's last line
1095 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1096 // The parent is a block, so align the rest of the chain with the closing
1098 IndentStyle::Visual => (parent_shape, false),
1102 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1108 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
1110 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1111 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
1113 } else if is_block_expr(context, &parent, &parent_rewrite) {
1114 match context.config.indent_style() {
1115 // Try to put the first child on the same line with parent's last line
1116 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
1117 // The parent is a block, so align the rest of the chain with the closing
1119 IndentStyle::Visual => (parent_shape, false),
1123 chain_indent(context, shape.add_offset(parent_rewrite.len())),
1127 assert!(test_format_inner(format_code_block, code_block, expected));