Skip to content

Commit a651624

Browse files
authored
Rollup merge of rust-lang#145153 - joshtriplett:macro-kinds-plural, r=petrochenkov
Handle macros with multiple kinds, and improve errors (I recommend reviewing this commit-by-commit.) Switch to a bitflags `MacroKinds` to support macros with more than one kind Review everything that uses `MacroKind`, and switch anything that could refer to more than one kind to use `MacroKinds`. Add a new `SyntaxExtensionKind::MacroRules` for `macro_rules!` macros, using the concrete `MacroRulesMacroExpander` type, and have it track which kinds it can handle. Eliminate the separate optional `attr_ext`, now that a `SyntaxExtension` can handle multiple macro kinds. This also avoids the need to downcast when calling methods on `MacroRulesMacroExpander`, such as `get_unused_rule`. Integrate macro kind checking into name resolution's `sub_namespace_match`, so that we only find a macro if it's the right type, and eliminate the special-case hack for attributes. This allows detecting and report macro kind mismatches early, and more precisely, improving various error messages. In particular, this eliminates the case in `failed_to_match_macro` to check for a function-like invocation of a macro with no function-like rules. Instead, macro kind mismatches now result in an unresolved macro, and we detect this case in `unresolved_macro_suggestions`, which now carefully distinguishes between a kind mismatch and other errors. This also handles cases of forward-referenced attributes and cyclic attributes. ---- In this PR, I've minimally fixed up `rustdoc` so that it compiles and passes tests. This is just the minimal necessary fixes to handle the switch to `MacroKinds`, and it only works for macros that don't actually have multiple kinds. This will panic (with a `todo!`) if it encounters a macro with multiple kinds. rustdoc needs further fixes to handle macros with multiple kinds, and to handle attributes and derive macros that aren't proc macros. I'd appreciate some help from a rustdoc expert on that. ---- r? `@petrochenkov`
2 parents d02905a + e1fc89a commit a651624

File tree

33 files changed

+405
-211
lines changed

33 files changed

+405
-211
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3889,6 +3889,7 @@ dependencies = [
38893889
name = "rustc_hir"
38903890
version = "0.0.0"
38913891
dependencies = [
3892+
"bitflags",
38923893
"odht",
38933894
"rustc_abi",
38943895
"rustc_arena",

compiler/rustc_ast_lowering/src/item.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,14 +436,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
436436
let body = Box::new(self.lower_delim_args(body));
437437
let def_id = self.local_def_id(id);
438438
let def_kind = self.tcx.def_kind(def_id);
439-
let DefKind::Macro(macro_kind) = def_kind else {
439+
let DefKind::Macro(macro_kinds) = def_kind else {
440440
unreachable!(
441441
"expected DefKind::Macro for macro item, found {}",
442442
def_kind.descr(def_id.to_def_id())
443443
);
444444
};
445445
let macro_def = self.arena.alloc(ast::MacroDef { body, macro_rules: *macro_rules });
446-
hir::ItemKind::Macro(ident, macro_def, macro_kind)
446+
hir::ItemKind::Macro(ident, macro_def, macro_kinds)
447447
}
448448
ItemKind::Delegation(box delegation) => {
449449
let delegation_results = self.lower_delegation(delegation, id, false);

compiler/rustc_expand/src/base.rs

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, PResult};
1717
use rustc_feature::Features;
1818
use rustc_hir as hir;
1919
use rustc_hir::attrs::{AttributeKind, CfgEntry, Deprecation};
20+
use rustc_hir::def::MacroKinds;
2021
use rustc_hir::{Stability, find_attr};
2122
use rustc_lint_defs::{BufferedEarlyLint, RegisteredTools};
2223
use rustc_parse::MACRO_ARGUMENTS;
@@ -718,6 +719,9 @@ impl MacResult for DummyResult {
718719
/// A syntax extension kind.
719720
#[derive(Clone)]
720721
pub enum SyntaxExtensionKind {
722+
/// A `macro_rules!` macro that can work as any `MacroKind`
723+
MacroRules(Arc<crate::MacroRulesMacroExpander>),
724+
721725
/// A token-based function-like macro.
722726
Bang(
723727
/// An expander with signature TokenStream -> TokenStream.
@@ -772,9 +776,39 @@ pub enum SyntaxExtensionKind {
772776
),
773777

774778
/// A glob delegation.
779+
///
780+
/// This is for delegated function implementations, and has nothing to do with glob imports.
775781
GlobDelegation(Arc<dyn GlobDelegationExpander + sync::DynSync + sync::DynSend>),
776782
}
777783

784+
impl SyntaxExtensionKind {
785+
/// Returns `Some(expander)` for a macro usable as a `LegacyBang`; otherwise returns `None`
786+
///
787+
/// This includes a `MacroRules` with function-like rules.
788+
pub fn as_legacy_bang(&self) -> Option<&(dyn TTMacroExpander + sync::DynSync + sync::DynSend)> {
789+
match self {
790+
SyntaxExtensionKind::LegacyBang(exp) => Some(exp.as_ref()),
791+
SyntaxExtensionKind::MacroRules(exp) if exp.kinds().contains(MacroKinds::BANG) => {
792+
Some(exp.as_ref())
793+
}
794+
_ => None,
795+
}
796+
}
797+
798+
/// Returns `Some(expander)` for a macro usable as an `Attr`; otherwise returns `None`
799+
///
800+
/// This includes a `MacroRules` with `attr` rules.
801+
pub fn as_attr(&self) -> Option<&(dyn AttrProcMacro + sync::DynSync + sync::DynSend)> {
802+
match self {
803+
SyntaxExtensionKind::Attr(exp) => Some(exp.as_ref()),
804+
SyntaxExtensionKind::MacroRules(exp) if exp.kinds().contains(MacroKinds::ATTR) => {
805+
Some(exp.as_ref())
806+
}
807+
_ => None,
808+
}
809+
}
810+
}
811+
778812
/// A struct representing a macro definition in "lowered" form ready for expansion.
779813
pub struct SyntaxExtension {
780814
/// A syntax extension kind.
@@ -804,18 +838,19 @@ pub struct SyntaxExtension {
804838
}
805839

806840
impl SyntaxExtension {
807-
/// Returns which kind of macro calls this syntax extension.
808-
pub fn macro_kind(&self) -> MacroKind {
841+
/// Returns which kinds of macro call this syntax extension.
842+
pub fn macro_kinds(&self) -> MacroKinds {
809843
match self.kind {
810844
SyntaxExtensionKind::Bang(..)
811845
| SyntaxExtensionKind::LegacyBang(..)
812-
| SyntaxExtensionKind::GlobDelegation(..) => MacroKind::Bang,
846+
| SyntaxExtensionKind::GlobDelegation(..) => MacroKinds::BANG,
813847
SyntaxExtensionKind::Attr(..)
814848
| SyntaxExtensionKind::LegacyAttr(..)
815-
| SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
849+
| SyntaxExtensionKind::NonMacroAttr => MacroKinds::ATTR,
816850
SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
817-
MacroKind::Derive
851+
MacroKinds::DERIVE
818852
}
853+
SyntaxExtensionKind::MacroRules(ref m) => m.kinds(),
819854
}
820855
}
821856

@@ -1024,11 +1059,12 @@ impl SyntaxExtension {
10241059
parent: LocalExpnId,
10251060
call_site: Span,
10261061
descr: Symbol,
1062+
kind: MacroKind,
10271063
macro_def_id: Option<DefId>,
10281064
parent_module: Option<DefId>,
10291065
) -> ExpnData {
10301066
ExpnData::new(
1031-
ExpnKind::Macro(self.macro_kind(), descr),
1067+
ExpnKind::Macro(kind, descr),
10321068
parent.to_expn_id(),
10331069
call_site,
10341070
self.span,

compiler/rustc_expand/src/expand.rs

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -736,8 +736,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
736736

737737
let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
738738
ExpandResult::Ready(match invoc.kind {
739-
InvocationKind::Bang { mac, span } => match ext {
740-
SyntaxExtensionKind::Bang(expander) => {
739+
InvocationKind::Bang { mac, span } => {
740+
if let SyntaxExtensionKind::Bang(expander) = ext {
741741
match expander.expand(self.cx, span, mac.args.tokens.clone()) {
742742
Ok(tok_result) => {
743743
let fragment =
@@ -755,8 +755,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
755755
}
756756
Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
757757
}
758-
}
759-
SyntaxExtensionKind::LegacyBang(expander) => {
758+
} else if let Some(expander) = ext.as_legacy_bang() {
760759
let tok_result = match expander.expand(self.cx, span, mac.args.tokens.clone()) {
761760
ExpandResult::Ready(tok_result) => tok_result,
762761
ExpandResult::Retry(_) => {
@@ -776,11 +775,12 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
776775
let guar = self.error_wrong_fragment_kind(fragment_kind, &mac, span);
777776
fragment_kind.dummy(span, guar)
778777
}
778+
} else {
779+
unreachable!();
779780
}
780-
_ => unreachable!(),
781-
},
782-
InvocationKind::Attr { attr, pos, mut item, derives } => match ext {
783-
SyntaxExtensionKind::Attr(expander) => {
781+
}
782+
InvocationKind::Attr { attr, pos, mut item, derives } => {
783+
if let Some(expander) = ext.as_attr() {
784784
self.gate_proc_macro_input(&item);
785785
self.gate_proc_macro_attr_item(span, &item);
786786
let tokens = match &item {
@@ -835,8 +835,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
835835
}
836836
Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
837837
}
838-
}
839-
SyntaxExtensionKind::LegacyAttr(expander) => {
838+
} else if let SyntaxExtensionKind::LegacyAttr(expander) = ext {
840839
match validate_attr::parse_meta(&self.cx.sess.psess, &attr) {
841840
Ok(meta) => {
842841
let item_clone = macro_stats.then(|| item.clone());
@@ -878,15 +877,15 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
878877
fragment_kind.expect_from_annotatables(iter::once(item))
879878
}
880879
}
881-
}
882-
SyntaxExtensionKind::NonMacroAttr => {
880+
} else if let SyntaxExtensionKind::NonMacroAttr = ext {
883881
// `-Zmacro-stats` ignores these because they don't do any real expansion.
884882
self.cx.expanded_inert_attrs.mark(&attr);
885883
item.visit_attrs(|attrs| attrs.insert(pos, attr));
886884
fragment_kind.expect_from_annotatables(iter::once(item))
885+
} else {
886+
unreachable!();
887887
}
888-
_ => unreachable!(),
889-
},
888+
}
890889
InvocationKind::Derive { path, item, is_const } => match ext {
891890
SyntaxExtensionKind::Derive(expander)
892891
| SyntaxExtensionKind::LegacyDerive(expander) => {

compiler/rustc_expand/src/mbe/diagnostics.rs

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,18 +58,6 @@ pub(super) fn failed_to_match_macro(
5858

5959
let Some(BestFailure { token, msg: label, remaining_matcher, .. }) = tracker.best_failure
6060
else {
61-
// FIXME: we should report this at macro resolution time, as we do for
62-
// `resolve_macro_cannot_use_as_attr`. We can do that once we track multiple macro kinds for a
63-
// Def.
64-
if attr_args.is_none() && !rules.iter().any(|rule| matches!(rule, MacroRule::Func { .. })) {
65-
let msg = format!("macro has no rules for function-like invocation `{name}!`");
66-
let mut err = psess.dcx().struct_span_err(sp, msg);
67-
if !def_head_span.is_dummy() {
68-
let msg = "this macro has no rules for function-like invocation";
69-
err.span_label(def_head_span, msg);
70-
}
71-
return (sp, err.emit());
72-
}
7361
return (sp, psess.dcx().span_delayed_bug(sp, "failed to match a macro"));
7462
};
7563

compiler/rustc_expand/src/mbe/macro_check.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -357,10 +357,10 @@ enum NestedMacroState {
357357
/// The token `macro_rules` was processed.
358358
MacroRules,
359359
/// The tokens `macro_rules!` were processed.
360-
MacroRulesNot,
360+
MacroRulesBang,
361361
/// The tokens `macro_rules!` followed by a name were processed. The name may be either directly
362362
/// an identifier or a meta-variable (that hopefully would be instantiated by an identifier).
363-
MacroRulesNotName,
363+
MacroRulesBangName,
364364
/// The keyword `macro` was processed.
365365
Macro,
366366
/// The keyword `macro` followed by a name was processed.
@@ -408,24 +408,24 @@ fn check_nested_occurrences(
408408
NestedMacroState::MacroRules,
409409
&TokenTree::Token(Token { kind: TokenKind::Bang, .. }),
410410
) => {
411-
state = NestedMacroState::MacroRulesNot;
411+
state = NestedMacroState::MacroRulesBang;
412412
}
413413
(
414-
NestedMacroState::MacroRulesNot,
414+
NestedMacroState::MacroRulesBang,
415415
&TokenTree::Token(Token { kind: TokenKind::Ident(..), .. }),
416416
) => {
417-
state = NestedMacroState::MacroRulesNotName;
417+
state = NestedMacroState::MacroRulesBangName;
418418
}
419-
(NestedMacroState::MacroRulesNot, &TokenTree::MetaVar(..)) => {
420-
state = NestedMacroState::MacroRulesNotName;
419+
(NestedMacroState::MacroRulesBang, &TokenTree::MetaVar(..)) => {
420+
state = NestedMacroState::MacroRulesBangName;
421421
// We check that the meta-variable is correctly used.
422422
check_occurrences(psess, node_id, tt, macros, binders, ops, guar);
423423
}
424-
(NestedMacroState::MacroRulesNotName, TokenTree::Delimited(.., del))
424+
(NestedMacroState::MacroRulesBangName, TokenTree::Delimited(.., del))
425425
| (NestedMacroState::MacroName, TokenTree::Delimited(.., del))
426426
if del.delim == Delimiter::Brace =>
427427
{
428-
let macro_rules = state == NestedMacroState::MacroRulesNotName;
428+
let macro_rules = state == NestedMacroState::MacroRulesBangName;
429429
state = NestedMacroState::Empty;
430430
let rest =
431431
check_nested_macro(psess, node_id, macro_rules, &del.tts, &nested_macros, guar);

compiler/rustc_expand/src/mbe/macro_rules.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan};
1515
use rustc_feature::Features;
1616
use rustc_hir as hir;
1717
use rustc_hir::attrs::AttributeKind;
18+
use rustc_hir::def::MacroKinds;
1819
use rustc_hir::find_attr;
1920
use rustc_lint_defs::BuiltinLintDiag;
2021
use rustc_lint_defs::builtin::{
@@ -144,6 +145,7 @@ pub struct MacroRulesMacroExpander {
144145
name: Ident,
145146
span: Span,
146147
transparency: Transparency,
148+
kinds: MacroKinds,
147149
rules: Vec<MacroRule>,
148150
}
149151

@@ -158,6 +160,10 @@ impl MacroRulesMacroExpander {
158160
};
159161
if has_compile_error_macro(rhs) { None } else { Some((&self.name, span)) }
160162
}
163+
164+
pub fn kinds(&self) -> MacroKinds {
165+
self.kinds
166+
}
161167
}
162168

163169
impl TTMacroExpander for MacroRulesMacroExpander {
@@ -540,13 +546,13 @@ pub fn compile_declarative_macro(
540546
span: Span,
541547
node_id: NodeId,
542548
edition: Edition,
543-
) -> (SyntaxExtension, Option<Arc<SyntaxExtension>>, usize) {
549+
) -> (SyntaxExtension, usize) {
544550
let mk_syn_ext = |kind| {
545551
let is_local = is_defined_in_current_crate(node_id);
546552
SyntaxExtension::new(sess, kind, span, Vec::new(), edition, ident.name, attrs, is_local)
547553
};
548-
let mk_bang_ext = |expander| mk_syn_ext(SyntaxExtensionKind::LegacyBang(expander));
549-
let dummy_syn_ext = |guar| (mk_bang_ext(Arc::new(DummyExpander(guar))), None, 0);
554+
let dummy_syn_ext =
555+
|guar| (mk_syn_ext(SyntaxExtensionKind::LegacyBang(Arc::new(DummyExpander(guar)))), 0);
550556

551557
let macro_rules = macro_def.macro_rules;
552558
let exp_sep = if macro_rules { exp!(Semi) } else { exp!(Comma) };
@@ -559,12 +565,12 @@ pub fn compile_declarative_macro(
559565
let mut guar = None;
560566
let mut check_emission = |ret: Result<(), ErrorGuaranteed>| guar = guar.or(ret.err());
561567

562-
let mut has_attr_rules = false;
568+
let mut kinds = MacroKinds::empty();
563569
let mut rules = Vec::new();
564570

565571
while p.token != token::Eof {
566572
let args = if p.eat_keyword_noexpect(sym::attr) {
567-
has_attr_rules = true;
573+
kinds |= MacroKinds::ATTR;
568574
if !features.macro_attr() {
569575
feature_err(sess, sym::macro_attr, span, "`macro_rules!` attributes are unstable")
570576
.emit();
@@ -581,6 +587,7 @@ pub fn compile_declarative_macro(
581587
}
582588
Some(args)
583589
} else {
590+
kinds |= MacroKinds::BANG;
584591
None
585592
};
586593
let lhs_tt = p.parse_token_tree();
@@ -627,6 +634,7 @@ pub fn compile_declarative_macro(
627634
let guar = sess.dcx().span_err(span, "macros must contain at least one rule");
628635
return dummy_syn_ext(guar);
629636
}
637+
assert!(!kinds.is_empty());
630638

631639
let transparency = find_attr!(attrs, AttributeKind::MacroTransparency(x) => *x)
632640
.unwrap_or(Transparency::fallback(macro_rules));
@@ -640,12 +648,8 @@ pub fn compile_declarative_macro(
640648
// Return the number of rules for unused rule linting, if this is a local macro.
641649
let nrules = if is_defined_in_current_crate(node_id) { rules.len() } else { 0 };
642650

643-
let exp = Arc::new(MacroRulesMacroExpander { name: ident, span, node_id, transparency, rules });
644-
let opt_attr_ext = has_attr_rules.then(|| {
645-
let exp = Arc::clone(&exp);
646-
Arc::new(mk_syn_ext(SyntaxExtensionKind::Attr(exp)))
647-
});
648-
(mk_bang_ext(exp), opt_attr_ext, nrules)
651+
let exp = MacroRulesMacroExpander { name: ident, kinds, span, node_id, transparency, rules };
652+
(mk_syn_ext(SyntaxExtensionKind::MacroRules(Arc::new(exp))), nrules)
649653
}
650654

651655
fn check_no_eof(sess: &Session, p: &Parser<'_>, msg: &'static str) -> Option<ErrorGuaranteed> {

compiler/rustc_hir/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ edition = "2024"
55

66
[dependencies]
77
# tidy-alphabetical-start
8+
bitflags = "2.9.1"
89
odht = { version = "0.3.1", features = ["nightly"] }
910
rustc_abi = { path = "../rustc_abi" }
1011
rustc_arena = { path = "../rustc_arena" }

0 commit comments

Comments
 (0)