Skip to content

Commit 0bd2232

Browse files
committed
Implement the unused_macro_rules lint
1 parent 3d43be3 commit 0bd2232

File tree

8 files changed

+139
-27
lines changed

8 files changed

+139
-27
lines changed

compiler/rustc_expand/src/base.rs

+2
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,8 @@ pub trait ResolverExpand {
887887
force: bool,
888888
) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
889889

890+
fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
891+
890892
fn check_unused_macros(&mut self);
891893

892894
// Resolver interfaces for specific built-in macros.

compiler/rustc_expand/src/mbe/macro_rules.rs

+28-12
Original file line numberDiff line numberDiff line change
@@ -156,13 +156,13 @@ impl<'a> ParserAnyMacro<'a> {
156156
}
157157

158158
struct MacroRulesMacroExpander {
159+
node_id: NodeId,
159160
name: Ident,
160161
span: Span,
161162
transparency: Transparency,
162163
lhses: Vec<Vec<MatcherLoc>>,
163164
rhses: Vec<mbe::TokenTree>,
164165
valid: bool,
165-
is_local: bool,
166166
}
167167

168168
impl TTMacroExpander for MacroRulesMacroExpander {
@@ -179,12 +179,12 @@ impl TTMacroExpander for MacroRulesMacroExpander {
179179
cx,
180180
sp,
181181
self.span,
182+
self.node_id,
182183
self.name,
183184
self.transparency,
184185
input,
185186
&self.lhses,
186187
&self.rhses,
187-
self.is_local,
188188
)
189189
}
190190
}
@@ -207,14 +207,17 @@ fn generic_extension<'cx, 'tt>(
207207
cx: &'cx mut ExtCtxt<'_>,
208208
sp: Span,
209209
def_span: Span,
210+
node_id: NodeId,
210211
name: Ident,
211212
transparency: Transparency,
212213
arg: TokenStream,
213214
lhses: &'tt [Vec<MatcherLoc>],
214215
rhses: &'tt [mbe::TokenTree],
215-
is_local: bool,
216216
) -> Box<dyn MacResult + 'cx> {
217217
let sess = &cx.sess.parse_sess;
218+
// Macros defined in the current crate have a real node id,
219+
// whereas macros from an external crate have a dummy id.
220+
let is_local = node_id != DUMMY_NODE_ID;
218221

219222
if cx.trace_macros() {
220223
let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
@@ -296,6 +299,10 @@ fn generic_extension<'cx, 'tt>(
296299
let mut p = Parser::new(sess, tts, false, None);
297300
p.last_type_ascription = cx.current_expansion.prior_type_ascription;
298301

302+
if is_local {
303+
cx.resolver.record_macro_rule_usage(node_id, i);
304+
}
305+
299306
// Let the context choose how to interpret the result.
300307
// Weird, but useful for X-macros.
301308
return Box::new(ParserAnyMacro {
@@ -372,7 +379,7 @@ pub fn compile_declarative_macro(
372379
features: &Features,
373380
def: &ast::Item,
374381
edition: Edition,
375-
) -> SyntaxExtension {
382+
) -> (SyntaxExtension, Vec<Span>) {
376383
debug!("compile_declarative_macro: {:?}", def);
377384
let mk_syn_ext = |expander| {
378385
SyntaxExtension::new(
@@ -385,6 +392,7 @@ pub fn compile_declarative_macro(
385392
&def.attrs,
386393
)
387394
};
395+
let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new());
388396

389397
let diag = &sess.parse_sess.span_diagnostic;
390398
let lhs_nm = Ident::new(sym::lhs, def.span);
@@ -445,17 +453,17 @@ pub fn compile_declarative_macro(
445453
let s = parse_failure_msg(&token);
446454
let sp = token.span.substitute_dummy(def.span);
447455
sess.parse_sess.span_diagnostic.struct_span_err(sp, &s).span_label(sp, msg).emit();
448-
return mk_syn_ext(Box::new(macro_rules_dummy_expander));
456+
return dummy_syn_ext();
449457
}
450458
Error(sp, msg) => {
451459
sess.parse_sess
452460
.span_diagnostic
453461
.struct_span_err(sp.substitute_dummy(def.span), &msg)
454462
.emit();
455-
return mk_syn_ext(Box::new(macro_rules_dummy_expander));
463+
return dummy_syn_ext();
456464
}
457465
ErrorReported => {
458-
return mk_syn_ext(Box::new(macro_rules_dummy_expander));
466+
return dummy_syn_ext();
459467
}
460468
};
461469

@@ -530,6 +538,15 @@ pub fn compile_declarative_macro(
530538
None => {}
531539
}
532540

541+
// Compute the spans of the macro rules
542+
// We only take the span of the lhs here,
543+
// so that the spans of created warnings are smaller.
544+
let rule_spans = if def.id != DUMMY_NODE_ID {
545+
lhses.iter().map(|lhs| lhs.span()).collect::<Vec<_>>()
546+
} else {
547+
Vec::new()
548+
};
549+
533550
// Convert the lhses into `MatcherLoc` form, which is better for doing the
534551
// actual matching. Unless the matcher is invalid.
535552
let lhses = if valid {
@@ -549,17 +566,16 @@ pub fn compile_declarative_macro(
549566
vec![]
550567
};
551568

552-
mk_syn_ext(Box::new(MacroRulesMacroExpander {
569+
let expander = Box::new(MacroRulesMacroExpander {
553570
name: def.ident,
554571
span: def.span,
572+
node_id: def.id,
555573
transparency,
556574
lhses,
557575
rhses,
558576
valid,
559-
// Macros defined in the current crate have a real node id,
560-
// whereas macros from an external crate have a dummy id.
561-
is_local: def.id != DUMMY_NODE_ID,
562-
}))
577+
});
578+
(mk_syn_ext(expander), rule_spans)
563579
}
564580

565581
fn check_lhs_nt_follows(sess: &ParseSess, def: &ast::Item, lhs: &mbe::TokenTree) -> bool {

compiler/rustc_resolve/Cargo.toml

-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ version = "0.0.0"
44
edition = "2021"
55

66
[lib]
7-
test = false
87
doctest = false
98

109
[dependencies]

compiler/rustc_resolve/src/build_reduced_graph.rs

+18-8
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ impl<'a> Resolver<'a> {
194194
}
195195

196196
let ext = Lrc::new(match self.cstore().load_macro_untracked(def_id, &self.session) {
197-
LoadedMacro::MacroDef(item, edition) => self.compile_macro(&item, edition),
197+
LoadedMacro::MacroDef(item, edition) => self.compile_macro(&item, edition).0,
198198
LoadedMacro::ProcMacro(ext) => ext,
199199
});
200200

@@ -1218,25 +1218,35 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
12181218
// Mark the given macro as unused unless its name starts with `_`.
12191219
// Macro uses will remove items from this set, and the remaining
12201220
// items will be reported as `unused_macros`.
1221-
fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
1221+
fn insert_unused_macro(
1222+
&mut self,
1223+
ident: Ident,
1224+
def_id: LocalDefId,
1225+
node_id: NodeId,
1226+
rule_spans: &[Span],
1227+
) {
12221228
if !ident.as_str().starts_with('_') {
12231229
self.r.unused_macros.insert(def_id, (node_id, ident));
1230+
for (rule_i, rule_span) in rule_spans.iter().enumerate() {
1231+
self.r.unused_macro_rules.insert((def_id, rule_i), (ident, *rule_span));
1232+
}
12241233
}
12251234
}
12261235

12271236
fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'a> {
12281237
let parent_scope = self.parent_scope;
12291238
let expansion = parent_scope.expansion;
12301239
let def_id = self.r.local_def_id(item.id);
1231-
let (ext, ident, span, macro_rules) = match &item.kind {
1240+
let (ext, ident, span, macro_rules, rule_spans) = match &item.kind {
12321241
ItemKind::MacroDef(def) => {
1233-
let ext = Lrc::new(self.r.compile_macro(item, self.r.session.edition()));
1234-
(ext, item.ident, item.span, def.macro_rules)
1242+
let (ext, rule_spans) = self.r.compile_macro(item, self.r.session.edition());
1243+
let ext = Lrc::new(ext);
1244+
(ext, item.ident, item.span, def.macro_rules, rule_spans)
12351245
}
12361246
ItemKind::Fn(..) => match self.proc_macro_stub(item) {
12371247
Some((macro_kind, ident, span)) => {
12381248
self.r.proc_macro_stubs.insert(def_id);
1239-
(self.r.dummy_ext(macro_kind), ident, span, false)
1249+
(self.r.dummy_ext(macro_kind), ident, span, false, Vec::new())
12401250
}
12411251
None => return parent_scope.macro_rules,
12421252
},
@@ -1264,7 +1274,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
12641274
self.r.define(module, ident, MacroNS, (res, vis, span, expansion, IsMacroExport));
12651275
} else {
12661276
self.r.check_reserved_macro_name(ident, res);
1267-
self.insert_unused_macro(ident, def_id, item.id);
1277+
self.insert_unused_macro(ident, def_id, item.id, &rule_spans);
12681278
}
12691279
self.r.visibilities.insert(def_id, vis);
12701280
let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Binding(
@@ -1287,7 +1297,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
12871297
_ => self.resolve_visibility(&item.vis),
12881298
};
12891299
if vis != ty::Visibility::Public {
1290-
self.insert_unused_macro(ident, def_id, item.id);
1300+
self.insert_unused_macro(ident, def_id, item.id, &rule_spans);
12911301
}
12921302
self.r.define(module, ident, MacroNS, (res, vis, span, expansion));
12931303
self.r.visibilities.insert(def_id, vis);

compiler/rustc_resolve/src/diagnostics.rs

+14
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, Vis
3535
use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet};
3636
use crate::{Segment, UseError};
3737

38+
#[cfg(test)]
39+
mod tests;
40+
3841
type Res = def::Res<ast::NodeId>;
3942

4043
/// A vector of spans and replacements, a message and applicability.
@@ -2663,3 +2666,14 @@ fn is_span_suitable_for_use_injection(s: Span) -> bool {
26632666
// import or other generated ones
26642667
!s.from_expansion()
26652668
}
2669+
2670+
/// Convert the given number into the corresponding ordinal
2671+
crate fn ordinalize(v: usize) -> String {
2672+
let suffix = match ((11..=13).contains(&(v % 100)), v % 10) {
2673+
(false, 1) => "st",
2674+
(false, 2) => "nd",
2675+
(false, 3) => "rd",
2676+
_ => "th",
2677+
};
2678+
format!("{v}{suffix}")
2679+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use super::ordinalize;
2+
3+
#[test]
4+
fn test_ordinalize() {
5+
assert_eq!(ordinalize(1), "1st");
6+
assert_eq!(ordinalize(2), "2nd");
7+
assert_eq!(ordinalize(3), "3rd");
8+
assert_eq!(ordinalize(4), "4th");
9+
assert_eq!(ordinalize(5), "5th");
10+
// ...
11+
assert_eq!(ordinalize(10), "10th");
12+
assert_eq!(ordinalize(11), "11th");
13+
assert_eq!(ordinalize(12), "12th");
14+
assert_eq!(ordinalize(13), "13th");
15+
assert_eq!(ordinalize(14), "14th");
16+
// ...
17+
assert_eq!(ordinalize(20), "20th");
18+
assert_eq!(ordinalize(21), "21st");
19+
assert_eq!(ordinalize(22), "22nd");
20+
assert_eq!(ordinalize(23), "23rd");
21+
assert_eq!(ordinalize(24), "24th");
22+
// ...
23+
assert_eq!(ordinalize(30), "30th");
24+
assert_eq!(ordinalize(31), "31st");
25+
assert_eq!(ordinalize(32), "32nd");
26+
assert_eq!(ordinalize(33), "33rd");
27+
assert_eq!(ordinalize(34), "34th");
28+
// ...
29+
assert_eq!(ordinalize(7010), "7010th");
30+
assert_eq!(ordinalize(7011), "7011th");
31+
assert_eq!(ordinalize(7012), "7012th");
32+
assert_eq!(ordinalize(7013), "7013th");
33+
assert_eq!(ordinalize(7014), "7014th");
34+
// ...
35+
assert_eq!(ordinalize(7020), "7020th");
36+
assert_eq!(ordinalize(7021), "7021st");
37+
assert_eq!(ordinalize(7022), "7022nd");
38+
assert_eq!(ordinalize(7023), "7023rd");
39+
assert_eq!(ordinalize(7024), "7024th");
40+
}

compiler/rustc_resolve/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -973,6 +973,7 @@ pub struct Resolver<'a> {
973973
local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
974974
ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>,
975975
unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
976+
unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>,
976977
proc_macro_stubs: FxHashSet<LocalDefId>,
977978
/// Traces collected during macro resolution and validated when it's complete.
978979
single_segment_macro_resolutions:
@@ -1372,6 +1373,7 @@ impl<'a> Resolver<'a> {
13721373
potentially_unused_imports: Vec::new(),
13731374
struct_constructors: Default::default(),
13741375
unused_macros: Default::default(),
1376+
unused_macro_rules: Default::default(),
13751377
proc_macro_stubs: Default::default(),
13761378
single_segment_macro_resolutions: Default::default(),
13771379
multi_segment_macro_resolutions: Default::default(),

compiler/rustc_resolve/src/macros.rs

+35-6
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
2222
use rustc_hir::def_id::{CrateNum, LocalDefId};
2323
use rustc_middle::middle::stability;
2424
use rustc_middle::ty::RegisteredTools;
25-
use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE, UNUSED_MACROS};
25+
use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE};
26+
use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES};
2627
use rustc_session::lint::BuiltinLintDiagnostics;
2728
use rustc_session::parse::feature_err;
2829
use rustc_session::Session;
@@ -311,6 +312,11 @@ impl<'a> ResolverExpand for Resolver<'a> {
311312
Ok(ext)
312313
}
313314

315+
fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
316+
let did = self.local_def_id(id);
317+
self.unused_macro_rules.remove(&(did, rule_i));
318+
}
319+
314320
fn check_unused_macros(&mut self) {
315321
for (_, &(node_id, ident)) in self.unused_macros.iter() {
316322
self.lint_buffer.buffer_lint(
@@ -320,6 +326,23 @@ impl<'a> ResolverExpand for Resolver<'a> {
320326
&format!("unused macro definition: `{}`", ident.as_str()),
321327
);
322328
}
329+
for (&(def_id, arm_i), &(ident, rule_span)) in self.unused_macro_rules.iter() {
330+
if self.unused_macros.contains_key(&def_id) {
331+
// We already lint the entire macro as unused
332+
continue;
333+
}
334+
let node_id = self.def_id_to_node_id[def_id];
335+
self.lint_buffer.buffer_lint(
336+
UNUSED_MACRO_RULES,
337+
node_id,
338+
rule_span,
339+
&format!(
340+
"{} rule of macro `{}` is never used",
341+
crate::diagnostics::ordinalize(arm_i + 1),
342+
ident.as_str()
343+
),
344+
);
345+
}
323346
}
324347

325348
fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
@@ -830,10 +853,15 @@ impl<'a> Resolver<'a> {
830853
}
831854
}
832855

833-
/// Compile the macro into a `SyntaxExtension` and possibly replace
834-
/// its expander to a pre-defined one for built-in macros.
835-
crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
836-
let mut result = compile_declarative_macro(
856+
/// Compile the macro into a `SyntaxExtension` and its rule spans.
857+
///
858+
/// Possibly replace its expander to a pre-defined one for built-in macros.
859+
crate fn compile_macro(
860+
&mut self,
861+
item: &ast::Item,
862+
edition: Edition,
863+
) -> (SyntaxExtension, Vec<Span>) {
864+
let (mut result, mut rule_spans) = compile_declarative_macro(
837865
&self.session,
838866
self.session.features_untracked(),
839867
item,
@@ -849,6 +877,7 @@ impl<'a> Resolver<'a> {
849877
match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
850878
BuiltinMacroState::NotYetSeen(ext) => {
851879
result.kind = ext;
880+
rule_spans = Vec::new();
852881
if item.id != ast::DUMMY_NODE_ID {
853882
self.builtin_macro_kinds
854883
.insert(self.local_def_id(item.id), result.macro_kind());
@@ -871,6 +900,6 @@ impl<'a> Resolver<'a> {
871900
}
872901
}
873902

874-
result
903+
(result, rule_spans)
875904
}
876905
}

0 commit comments

Comments
 (0)