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.
This commit is contained in:
parent
1842967542
commit
b944a32e5c
@ -28,6 +28,7 @@
|
||||
extern crate rustc_driver;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::cmp::min;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::io::{self, Write};
|
||||
@ -385,9 +386,15 @@ fn enclose_in_main_block(s: &str, config: &Config) -> String {
|
||||
.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 {
|
||||
|
3
tests/source/issue_5730.rs
Normal file
3
tests/source/issue_5730.rs
Normal file
@ -0,0 +1,3 @@
|
||||
macro_rules! statement {
|
||||
() => {;};
|
||||
}
|
3
tests/target/issue_5730.rs
Normal file
3
tests/target/issue_5730.rs
Normal file
@ -0,0 +1,3 @@
|
||||
macro_rules! statement {
|
||||
() => {};
|
||||
}
|
Loading…
Reference in New Issue
Block a user