Skip to content

Commit b944a32

Browse files
authored
Prevent ICE when formatting an empty-ish macro arm (#5833)
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.
1 parent 1842967 commit b944a32

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

src/lib.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ extern crate thin_vec;
2828
extern crate rustc_driver;
2929

3030
use std::cell::RefCell;
31+
use std::cmp::min;
3132
use std::collections::HashMap;
3233
use std::fmt;
3334
use std::io::{self, Write};
@@ -385,9 +386,15 @@ fn format_code_block(
385386
.snippet
386387
.rfind('}')
387388
.unwrap_or_else(|| formatted.snippet.len());
389+
390+
// It's possible that `block_len < FN_MAIN_PREFIX.len()`. This can happen if the code block was
391+
// formatted into the empty string, leading to the enclosing `fn main() {\n}` being formatted
392+
// into `fn main() {}`. In this case no unindentation is done.
393+
let block_start = min(FN_MAIN_PREFIX.len(), block_len);
394+
388395
let mut is_indented = true;
389396
let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
390-
for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
397+
for (kind, ref line) in LineClasses::new(&formatted.snippet[block_start..block_len]) {
391398
if !is_first {
392399
result.push('\n');
393400
} else {

tests/source/issue_5730.rs

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
macro_rules! statement {
2+
() => {;};
3+
}

tests/target/issue_5730.rs

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
macro_rules! statement {
2+
() => {};
3+
}

0 commit comments

Comments
 (0)