Skip to content

Commit

Permalink
Prevent ICE when formatting an empty-ish macro arm (#5833)
Browse files Browse the repository at this point in the history
Fixes 5730

Previously rustfmt was attempting to slice a string with an invalid
range (`start > end`), leading to the ICE.

When formatting a macro transcriber snippet consisting of a lone
semicolon, the snippet was being formatted into the empty string,
leading the enclosing `fn main() {\n}` added by `format_code_block` to
be formatted into `fn main() {}`. However, rustfmt was assuming that the
enclosing function string's length had been left unchanged. This was
leading to an invalid range being constructed when attempting to trim
off the enclosing function.

The fix is to just clamp the range's start to be less than or equal
to the range's end, since if `end < start` there's nothing to iterate
over anyway.
  • Loading branch information
tdanniels authored Jul 19, 2023
1 parent 1842967 commit b944a32
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ extern crate thin_vec;
extern crate rustc_driver;

use std::cell::RefCell;
use std::cmp::min;
use std::collections::HashMap;
use std::fmt;
use std::io::{self, Write};
Expand Down Expand Up @@ -385,9 +386,15 @@ fn format_code_block(
.snippet
.rfind('}')
.unwrap_or_else(|| formatted.snippet.len());

// It's possible that `block_len < FN_MAIN_PREFIX.len()`. This can happen if the code block was
// formatted into the empty string, leading to the enclosing `fn main() {\n}` being formatted
// into `fn main() {}`. In this case no unindentation is done.
let block_start = min(FN_MAIN_PREFIX.len(), block_len);

let mut is_indented = true;
let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
for (kind, ref line) in LineClasses::new(&formatted.snippet[block_start..block_len]) {
if !is_first {
result.push('\n');
} else {
Expand Down
3 changes: 3 additions & 0 deletions tests/source/issue_5730.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
macro_rules! statement {
() => {;};
}
3 changes: 3 additions & 0 deletions tests/target/issue_5730.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
macro_rules! statement {
() => {};
}

0 comments on commit b944a32

Please sign in to comment.