From ac2ebd3a78246d2dab16aec39d2aaace618a17eb Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Thu, 30 Mar 2023 13:18:28 -0400 Subject: [PATCH] Prevent ICE when calling parse_attribute without an attribute Fixes 5729 `parse_attribute` will panic if the first token is not a `#`. To prevent this we return early instead of trying to parse an invalid attribute. --- src/parse/macros/cfg_if.rs | 5 +++++ tests/rustfmt/main.rs | 2 +- tests/target/issue_5729.rs | 5 +++++ 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 tests/target/issue_5729.rs diff --git a/src/parse/macros/cfg_if.rs b/src/parse/macros/cfg_if.rs index ac03409a7844..cbc4c90b8f98 100644 --- a/src/parse/macros/cfg_if.rs +++ b/src/parse/macros/cfg_if.rs @@ -34,6 +34,11 @@ fn parse_cfg_if_inner<'a>( if !parser.eat_keyword(kw::If) { return Err("Expected `if`"); } + + if !matches!(parser.token.kind, TokenKind::Pound) { + return Err("Failed to parse attributes"); + } + // Inner attributes are not actually syntactically permitted here, but we don't // care about inner vs outer attributes in this position. Our purpose with this // special case parsing of cfg_if macros is to ensure we can correctly resolve diff --git a/tests/rustfmt/main.rs b/tests/rustfmt/main.rs index f00b0e09604f..4936a7174636 100644 --- a/tests/rustfmt/main.rs +++ b/tests/rustfmt/main.rs @@ -178,7 +178,7 @@ fn rustfmt_emits_error_on_line_overflow_true() { #[test] #[allow(non_snake_case)] fn dont_emit_ICE() { - let files = ["tests/target/issue_5728.rs"]; + let files = ["tests/target/issue_5728.rs", "tests/target/issue_5729.rs"]; for file in files { let args = [file]; diff --git a/tests/target/issue_5729.rs b/tests/target/issue_5729.rs new file mode 100644 index 000000000000..d63c83e88f84 --- /dev/null +++ b/tests/target/issue_5729.rs @@ -0,0 +1,5 @@ +cfg_if::cfg_if! { + if { + } else if #(&cpus) { + } else [libc::CTL_HW, libc::HW_NCPU, 0, 0] +}