Censor cfg_attr for attribute macros

This is not documented (and I discovered that from experimenting and looking at the compiler's source code), but cfg_attrs *on the same level* as the attribute macro should be processed before it is expanded. cfg_attrs *below* should not (and this is contrary to what happens with derive macros, where both should be processed).
This commit is contained in:
Chayim Refael Friedman 2025-02-10 01:28:28 +02:00
parent fc726ced6b
commit 933832008b
3 changed files with 96 additions and 24 deletions

View file

@ -17,7 +17,7 @@ use hir_expand::{
tt::{Leaf, TokenTree, TopSubtree, TopSubtreeBuilder, TtElement, TtIter},
FileRange,
};
use intern::Symbol;
use intern::{sym, Symbol};
use rustc_hash::FxHashMap;
use span::{Edition, EditionedFileId, FileId, Span};
use stdx::itertools::Itertools;
@ -511,6 +511,21 @@ pub fn issue_18898(_attr: TokenStream, input: TokenStream) -> TokenStream {
disabled: false,
},
),
(
r#"
#[proc_macro_attribute]
pub fn disallow_cfg(_attr: TokenStream, input: TokenStream) -> TokenStream {
input
}
"#
.into(),
ProcMacro {
name: Symbol::intern("disallow_cfg"),
kind: ProcMacroKind::Attr,
expander: sync::Arc::new(DisallowCfgProcMacroExpander),
disabled: false,
},
),
])
}
@ -865,3 +880,30 @@ impl ProcMacroExpander for Issue18898ProcMacroExpander {
})
}
}
// Reads ident type within string quotes, for issue #17479.
#[derive(Debug)]
struct DisallowCfgProcMacroExpander;
impl ProcMacroExpander for DisallowCfgProcMacroExpander {
fn expand(
&self,
subtree: &TopSubtree,
_: Option<&TopSubtree>,
_: &Env,
_: Span,
_: Span,
_: Span,
_: Option<String>,
) -> Result<TopSubtree, ProcMacroExpansionError> {
for tt in subtree.token_trees().flat_tokens() {
if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = tt {
if ident.sym == sym::cfg || ident.sym == sym::cfg_attr {
return Err(ProcMacroExpansionError::Panic(
"cfg or cfg_attr found in DisallowCfgProcMacroExpander".to_owned(),
));
}
}
}
Ok(subtree.clone())
}
}