Skip to content

Commit

Permalink
Fix panic in annotated_snippet dependency (GitHub issue #4968).
Browse files Browse the repository at this point in the history
* Internally, rustfmt preserves tabs and counts them as multiple
  characters (based on configuration).
* The annoted_snippet dependency counts tabs as 1 character.
* If rustfmt produces an error on a line containing tabs,
  annotated_snippet may think that the error is out of range and panic.
* Have rustfmt internally replace tabs with the corresponding number of
  spaces, so that columns can be counted unambiguously.
* This change is based on PR #5039 by karyon, but with the code review
  suggestions by camsteffen.
  • Loading branch information
Raekye committed Dec 7, 2022
1 parent ee2bed9 commit 1e754ac
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -574,12 +574,14 @@ impl<'a> FormatLines<'a> {
fn char(&mut self, c: char, kind: FullCodeCharKind) {
self.newline_count = 0;
self.line_len += if c == '\t' {
self.line_buffer
.push_str(&" ".repeat(self.config.tab_spaces()));
self.config.tab_spaces()
} else {
1
self.line_buffer.push(c);
c.len_utf8()
};
self.last_was_space = c.is_whitespace();
self.line_buffer.push(c);
if kind.is_string() {
self.current_line_contains_string_literal = true;
}
Expand Down
11 changes: 11 additions & 0 deletions tests/target/issue-4968.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// rustfmt-hard_tabs: true
// rustfmt-max_width: 40
// rustfmt-error_on_unformatted: true

fn foo(x: u32) {
if x > 10 {
if x > 20 {
println!("0123456789abcdefghijklmnopqrstuvwxyz");
}
}
}

0 comments on commit 1e754ac

Please sign in to comment.