From 5b0ce0ed120d71c879848fdbbe8b8d05c442373d Mon Sep 17 00:00:00 2001 From: rChaser53 Date: Sun, 23 Jun 2019 14:32:14 +0900 Subject: [PATCH] avoid not to truncate necessary chars (#3640) --- src/formatting.rs | 7 ++++++- src/visitor.rs | 15 ++++++++++++++- tests/source/issue-3636.rs | 10 ++++++++++ tests/target/issue-3636.rs | 8 ++++++++ 4 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 tests/source/issue-3636.rs create mode 100644 tests/target/issue-3636.rs diff --git a/src/formatting.rs b/src/formatting.rs index 522de400840..a71de71acee 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -177,7 +177,12 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> { visitor.format_separate_mod(module, &*source_file); }; - debug_assert_eq!(visitor.line_number, count_newlines(&visitor.buffer)); + debug_assert_eq!( + visitor.line_number, + count_newlines(&visitor.buffer), + "failed in format_file visitor.buffer:\n {:?}", + &visitor.buffer + ); // For some reason, the source_map does not include terminating // newlines so we must add one on for each file. This is sad. diff --git a/src/visitor.rs b/src/visitor.rs index 19200f9592c..641ff1b62fd 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -257,7 +257,20 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } else { self.config.tab_spaces() }; - self.buffer.truncate(total_len - chars_too_many); + + // FIXME this is a temporaly fix + // should be remove truncate logic in close_block + // avoid not to truncate necessary chars + let truncate_start = total_len - chars_too_many; + let target_str = &self.buffer[truncate_start..total_len]; + let truncate_length = target_str.len() - target_str.trim().len(); + + if let Some(last_char) = target_str.chars().last() { + self.buffer.truncate(total_len - truncate_length); + if last_char == '\n' { + self.buffer.push_str("\n"); + } + } } self.push_str("}"); self.block_indent = self.block_indent.block_unindent(self.config); diff --git a/tests/source/issue-3636.rs b/tests/source/issue-3636.rs new file mode 100644 index 00000000000..80355bbd2ef --- /dev/null +++ b/tests/source/issue-3636.rs @@ -0,0 +1,10 @@ +// rustfmt-file_lines: [{"file":"tests/source/issue-3636.rs","range":[4,7]}] + +fn foo() { + let x = + 42; + let y = + 42; + let z = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let z = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +} \ No newline at end of file diff --git a/tests/target/issue-3636.rs b/tests/target/issue-3636.rs new file mode 100644 index 00000000000..d8d78e88d0e --- /dev/null +++ b/tests/target/issue-3636.rs @@ -0,0 +1,8 @@ +// rustfmt-file_lines: [{"file":"tests/source/issue-3636.rs","range":[4,7]}] + +fn foo() { + let x = 42; + let y = 42; + let z = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let z = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +}