From b944a32e5cd153344ec93827821d8607c3988a09 Mon Sep 17 00:00:00 2001 From: tdanniels Date: Tue, 18 Jul 2023 18:48:57 -0700 Subject: [PATCH] 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. --- src/lib.rs | 9 ++++++++- tests/source/issue_5730.rs | 3 +++ tests/target/issue_5730.rs | 3 +++ 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 tests/source/issue_5730.rs create mode 100644 tests/target/issue_5730.rs diff --git a/src/lib.rs b/src/lib.rs index b9ab3ffd989..8800e200fa4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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}; @@ -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 { diff --git a/tests/source/issue_5730.rs b/tests/source/issue_5730.rs new file mode 100644 index 00000000000..9a3f4f0d07a --- /dev/null +++ b/tests/source/issue_5730.rs @@ -0,0 +1,3 @@ +macro_rules! statement { + () => {;}; +} diff --git a/tests/target/issue_5730.rs b/tests/target/issue_5730.rs new file mode 100644 index 00000000000..7922fdcc90f --- /dev/null +++ b/tests/target/issue_5730.rs @@ -0,0 +1,3 @@ +macro_rules! statement { + () => {}; +}