Skip to content

Commit 657a41f

Browse files
authored
Rollup merge of #73178 - petrochenkov:explint, r=varkor
expand: More precise locations for expansion-time lints First commit: a macro expansion doesn't have a `NodeId` associated with it, but it has a parent `DefId` which we can use for linting. The observable effect is that lints associated with macro expansions can now be `allow`ed at finer-grained level than whole crate. Second commit: each macro definition has a `NodeId` which we can use for linting, unless that macro definition was decoded from other crate.
2 parents c06799e + d60df53 commit 657a41f

File tree

14 files changed

+146
-26
lines changed

14 files changed

+146
-26
lines changed

src/librustc_builtin_macros/source_util.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ pub fn expand_include<'cx>(
122122

123123
struct ExpandResult<'a> {
124124
p: Parser<'a>,
125+
node_id: ast::NodeId,
125126
}
126127
impl<'a> base::MacResult for ExpandResult<'a> {
127128
fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
@@ -130,7 +131,7 @@ pub fn expand_include<'cx>(
130131
self.p.sess.buffer_lint(
131132
&INCOMPLETE_INCLUDE,
132133
self.p.token.span,
133-
ast::CRATE_NODE_ID,
134+
self.node_id,
134135
"include macro expected single expression in source",
135136
);
136137
}
@@ -158,7 +159,7 @@ pub fn expand_include<'cx>(
158159
}
159160
}
160161

161-
Box::new(ExpandResult { p })
162+
Box::new(ExpandResult { p, node_id: cx.resolver.lint_node_id(cx.current_expansion.id) })
162163
}
163164

164165
// include_str! : read the given file, insert it as a literal string expr

src/librustc_expand/base.rs

+3
Original file line numberDiff line numberDiff line change
@@ -915,6 +915,9 @@ pub trait Resolver {
915915

916916
fn check_unused_macros(&mut self);
917917

918+
/// Some parent node that is close enough to the given macro call.
919+
fn lint_node_id(&mut self, expn_id: ExpnId) -> NodeId;
920+
918921
fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
919922
fn add_derive_copy(&mut self, expn_id: ExpnId);
920923
fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate>;

src/librustc_expand/mbe/macro_check.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@
106106
//! bound.
107107
use crate::mbe::{KleeneToken, TokenTree};
108108

109-
use rustc_ast::ast::NodeId;
109+
use rustc_ast::ast::{NodeId, DUMMY_NODE_ID};
110110
use rustc_ast::token::{DelimToken, Token, TokenKind};
111111
use rustc_data_structures::fx::FxHashMap;
112112
use rustc_session::lint::builtin::META_VARIABLE_MISUSE;
@@ -626,5 +626,8 @@ fn ops_is_prefix(
626626
}
627627

628628
fn buffer_lint(sess: &ParseSess, span: MultiSpan, node_id: NodeId, message: &str) {
629-
sess.buffer_lint(&META_VARIABLE_MISUSE, span, node_id, message);
629+
// Macros loaded from other crates have dummy node ids.
630+
if node_id != DUMMY_NODE_ID {
631+
sess.buffer_lint(&META_VARIABLE_MISUSE, span, node_id, message);
632+
}
630633
}

src/librustc_expand/mbe/macro_parser.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ fn nameize<I: Iterator<Item = NamedMatch>>(
383383
}
384384
}
385385
TokenTree::MetaVarDecl(span, _, id) if id.name == kw::Invalid => {
386-
if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
386+
if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() {
387387
return Err((span, "missing fragment specifier".to_string()));
388388
}
389389
}
@@ -566,7 +566,7 @@ fn inner_parse_loop<'root, 'tt>(
566566

567567
// We need to match a metavar (but the identifier is invalid)... this is an error
568568
TokenTree::MetaVarDecl(span, _, id) if id.name == kw::Invalid => {
569-
if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
569+
if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() {
570570
return Error(span, "missing fragment specifier".to_string());
571571
}
572572
}

src/librustc_expand/mbe/macro_rules.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,9 @@ pub fn compile_declarative_macro(
474474
.map(|m| {
475475
if let MatchedNonterminal(ref nt) = *m {
476476
if let NtTT(ref tt) = **nt {
477-
let tt = mbe::quoted::parse(tt.clone().into(), true, sess).pop().unwrap();
477+
let tt = mbe::quoted::parse(tt.clone().into(), true, sess, def.id)
478+
.pop()
479+
.unwrap();
478480
valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
479481
return tt;
480482
}
@@ -491,7 +493,9 @@ pub fn compile_declarative_macro(
491493
.map(|m| {
492494
if let MatchedNonterminal(ref nt) = *m {
493495
if let NtTT(ref tt) = **nt {
494-
return mbe::quoted::parse(tt.clone().into(), false, sess).pop().unwrap();
496+
return mbe::quoted::parse(tt.clone().into(), false, sess, def.id)
497+
.pop()
498+
.unwrap();
495499
}
496500
}
497501
sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
@@ -509,9 +513,7 @@ pub fn compile_declarative_macro(
509513
valid &= check_lhs_no_empty_seq(sess, slice::from_ref(lhs));
510514
}
511515

512-
// We use CRATE_NODE_ID instead of `def.id` otherwise we may emit buffered lints for a node id
513-
// that is not lint-checked and trigger the "failed to process buffered lint here" bug.
514-
valid &= macro_check::check_meta_variables(sess, ast::CRATE_NODE_ID, def.span, &lhses, &rhses);
516+
valid &= macro_check::check_meta_variables(sess, def.id, def.span, &lhses, &rhses);
515517

516518
let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules);
517519
match transparency_error {

src/librustc_expand/mbe/quoted.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::mbe::macro_parser;
22
use crate::mbe::{Delimited, KleeneOp, KleeneToken, SequenceRepetition, TokenTree};
33

4+
use rustc_ast::ast::{NodeId, DUMMY_NODE_ID};
45
use rustc_ast::token::{self, Token};
56
use rustc_ast::tokenstream;
67
use rustc_ast_pretty::pprust;
@@ -36,6 +37,7 @@ pub(super) fn parse(
3637
input: tokenstream::TokenStream,
3738
expect_matchers: bool,
3839
sess: &ParseSess,
40+
node_id: NodeId,
3941
) -> Vec<TokenTree> {
4042
// Will contain the final collection of `self::TokenTree`
4143
let mut result = Vec::new();
@@ -46,7 +48,7 @@ pub(super) fn parse(
4648
while let Some(tree) = trees.next() {
4749
// Given the parsed tree, if there is a metavar and we are expecting matchers, actually
4850
// parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
49-
let tree = parse_tree(tree, &mut trees, expect_matchers, sess);
51+
let tree = parse_tree(tree, &mut trees, expect_matchers, sess, node_id);
5052
match tree {
5153
TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
5254
let span = match trees.next() {
@@ -65,7 +67,10 @@ pub(super) fn parse(
6567
}
6668
tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(start_sp),
6769
};
68-
sess.missing_fragment_specifiers.borrow_mut().insert(span);
70+
if node_id != DUMMY_NODE_ID {
71+
// Macros loaded from other crates have dummy node ids.
72+
sess.missing_fragment_specifiers.borrow_mut().insert(span, node_id);
73+
}
6974
result.push(TokenTree::MetaVarDecl(span, ident, Ident::invalid()));
7075
}
7176

@@ -96,6 +101,7 @@ fn parse_tree(
96101
trees: &mut impl Iterator<Item = tokenstream::TokenTree>,
97102
expect_matchers: bool,
98103
sess: &ParseSess,
104+
node_id: NodeId,
99105
) -> TokenTree {
100106
// Depending on what `tree` is, we could be parsing different parts of a macro
101107
match tree {
@@ -111,7 +117,7 @@ fn parse_tree(
111117
sess.span_diagnostic.span_err(span.entire(), &msg);
112118
}
113119
// Parse the contents of the sequence itself
114-
let sequence = parse(tts, expect_matchers, sess);
120+
let sequence = parse(tts, expect_matchers, sess, node_id);
115121
// Get the Kleene operator and optional separator
116122
let (separator, kleene) = parse_sep_and_kleene_op(trees, span.entire(), sess);
117123
// Count the number of captured "names" (i.e., named metavars)
@@ -158,7 +164,7 @@ fn parse_tree(
158164
// descend into the delimited set and further parse it.
159165
tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
160166
span,
161-
Lrc::new(Delimited { delim, tts: parse(tts, expect_matchers, sess) }),
167+
Lrc::new(Delimited { delim, tts: parse(tts, expect_matchers, sess, node_id) }),
162168
),
163169
}
164170
}

src/librustc_hir/definitions.rs

+6
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,12 @@ impl Definitions {
519519
let old_index = self.placeholder_field_indices.insert(node_id, index);
520520
assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
521521
}
522+
523+
pub fn lint_node_id(&mut self, expn_id: ExpnId) -> ast::NodeId {
524+
self.invocation_parents
525+
.get(&expn_id)
526+
.map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[*id])
527+
}
522528
}
523529

524530
impl DefPathData {

src/librustc_interface/passes.rs

+10-5
Original file line numberDiff line numberDiff line change
@@ -307,16 +307,21 @@ fn configure_and_expand_inner<'a>(
307307
ecx.check_unused_macros();
308308
});
309309

310-
let mut missing_fragment_specifiers: Vec<_> =
311-
ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
312-
missing_fragment_specifiers.sort();
310+
let mut missing_fragment_specifiers: Vec<_> = ecx
311+
.parse_sess
312+
.missing_fragment_specifiers
313+
.borrow()
314+
.iter()
315+
.map(|(span, node_id)| (*span, *node_id))
316+
.collect();
317+
missing_fragment_specifiers.sort_unstable_by_key(|(span, _)| *span);
313318

314319
let recursion_limit_hit = ecx.reduced_recursion_limit.is_some();
315320

316-
for span in missing_fragment_specifiers {
321+
for (span, node_id) in missing_fragment_specifiers {
317322
let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
318323
let msg = "missing fragment specifier";
319-
resolver.lint_buffer().buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
324+
resolver.lint_buffer().buffer_lint(lint, node_id, span, msg);
320325
}
321326
if cfg!(windows) {
322327
env::set_var("PATH", &old_path);

src/librustc_resolve/macros.rs

+14-4
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,8 @@ impl<'a> base::Resolver for Resolver<'a> {
288288

289289
// Derives are not included when `invocations` are collected, so we have to add them here.
290290
let parent_scope = &ParentScope { derives, ..parent_scope };
291-
let (ext, res) = self.smart_resolve_macro_path(path, kind, parent_scope, force)?;
291+
let node_id = self.lint_node_id(eager_expansion_root);
292+
let (ext, res) = self.smart_resolve_macro_path(path, kind, parent_scope, node_id, force)?;
292293

293294
let span = invoc.span();
294295
invoc_id.set_expn_data(ext.expn_data(
@@ -338,6 +339,10 @@ impl<'a> base::Resolver for Resolver<'a> {
338339
}
339340
}
340341

342+
fn lint_node_id(&mut self, expn_id: ExpnId) -> NodeId {
343+
self.definitions.lint_node_id(expn_id)
344+
}
345+
341346
fn has_derive_copy(&self, expn_id: ExpnId) -> bool {
342347
self.containers_deriving_copy.contains(&expn_id)
343348
}
@@ -390,6 +395,7 @@ impl<'a> Resolver<'a> {
390395
path: &ast::Path,
391396
kind: MacroKind,
392397
parent_scope: &ParentScope<'a>,
398+
node_id: NodeId,
393399
force: bool,
394400
) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
395401
let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
@@ -430,7 +436,7 @@ impl<'a> Resolver<'a> {
430436
_ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
431437
};
432438

433-
self.check_stability_and_deprecation(&ext, path);
439+
self.check_stability_and_deprecation(&ext, path, node_id);
434440

435441
Ok(if ext.macro_kind() != kind {
436442
let expected = kind.descr_expected();
@@ -984,13 +990,17 @@ impl<'a> Resolver<'a> {
984990
}
985991
}
986992

987-
fn check_stability_and_deprecation(&mut self, ext: &SyntaxExtension, path: &ast::Path) {
993+
fn check_stability_and_deprecation(
994+
&mut self,
995+
ext: &SyntaxExtension,
996+
path: &ast::Path,
997+
node_id: NodeId,
998+
) {
988999
let span = path.span;
9891000
if let Some(stability) = &ext.stability {
9901001
if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
9911002
let feature = stability.feature;
9921003
if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
993-
let node_id = ast::CRATE_NODE_ID;
9941004
let lint_buffer = &mut self.lint_buffer;
9951005
let soft_handler =
9961006
|lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);

src/librustc_session/lint/builtin.rs

+1
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,7 @@ declare_lint_pass! {
606606
INLINE_NO_SANITIZE,
607607
ASM_SUB_REGISTER,
608608
UNSAFE_OP_IN_UNSAFE_FN,
609+
INCOMPLETE_INCLUDE,
609610
]
610611
}
611612

src/librustc_session/parse.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ pub struct ParseSess {
119119
pub unstable_features: UnstableFeatures,
120120
pub config: CrateConfig,
121121
pub edition: Edition,
122-
pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
122+
pub missing_fragment_specifiers: Lock<FxHashMap<Span, NodeId>>,
123123
/// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
124124
pub raw_identifier_spans: Lock<Vec<Span>>,
125125
/// Used to determine and report recursive module inclusions.
@@ -150,7 +150,7 @@ impl ParseSess {
150150
unstable_features: UnstableFeatures::from_environment(),
151151
config: FxHashSet::default(),
152152
edition: ExpnId::root().expn_data().edition,
153-
missing_fragment_specifiers: Lock::new(FxHashSet::default()),
153+
missing_fragment_specifiers: Default::default(),
154154
raw_identifier_spans: Lock::new(Vec::new()),
155155
included_mod_stack: Lock::new(vec![]),
156156
source_map,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// ignore-test auxiliary file for expansion-time.rs
2+
3+
1
4+
2

src/test/ui/lint/expansion-time.rs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// check-pass
2+
3+
#[warn(meta_variable_misuse)]
4+
macro_rules! foo {
5+
( $($i:ident)* ) => { $($i)+ }; //~ WARN meta-variable repeats with different Kleene operator
6+
}
7+
8+
#[warn(missing_fragment_specifier)]
9+
macro_rules! m { ($i) => {} } //~ WARN missing fragment specifier
10+
//~| WARN this was previously accepted
11+
12+
#[warn(soft_unstable)]
13+
mod benches {
14+
#[bench] //~ WARN use of unstable library feature 'test'
15+
//~| WARN this was previously accepted
16+
fn foo() {}
17+
}
18+
19+
#[warn(incomplete_include)]
20+
fn main() {
21+
// WARN see in the stderr file, the warning points to the included file.
22+
include!("expansion-time-include.rs");
23+
}
+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
warning: meta-variable repeats with different Kleene operator
2+
--> $DIR/expansion-time.rs:5:29
3+
|
4+
LL | ( $($i:ident)* ) => { $($i)+ };
5+
| - ^^ - conflicting repetition
6+
| |
7+
| expected repetition
8+
|
9+
note: the lint level is defined here
10+
--> $DIR/expansion-time.rs:3:8
11+
|
12+
LL | #[warn(meta_variable_misuse)]
13+
| ^^^^^^^^^^^^^^^^^^^^
14+
15+
warning: missing fragment specifier
16+
--> $DIR/expansion-time.rs:9:19
17+
|
18+
LL | macro_rules! m { ($i) => {} }
19+
| ^^
20+
|
21+
note: the lint level is defined here
22+
--> $DIR/expansion-time.rs:8:8
23+
|
24+
LL | #[warn(missing_fragment_specifier)]
25+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
26+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
27+
= note: for more information, see issue #40107 <https://github.com/rust-lang/rust/issues/40107>
28+
29+
warning: use of unstable library feature 'test': `bench` is a part of custom test frameworks which are unstable
30+
--> $DIR/expansion-time.rs:14:7
31+
|
32+
LL | #[bench]
33+
| ^^^^^
34+
|
35+
note: the lint level is defined here
36+
--> $DIR/expansion-time.rs:12:8
37+
|
38+
LL | #[warn(soft_unstable)]
39+
| ^^^^^^^^^^^^^
40+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
41+
= note: for more information, see issue #64266 <https://github.com/rust-lang/rust/issues/64266>
42+
43+
warning: include macro expected single expression in source
44+
--> $DIR/expansion-time-include.rs:4:1
45+
|
46+
LL | 2
47+
| ^
48+
|
49+
note: the lint level is defined here
50+
--> $DIR/expansion-time.rs:19:8
51+
|
52+
LL | #[warn(incomplete_include)]
53+
| ^^^^^^^^^^^^^^^^^^
54+
55+
warning: 4 warnings emitted
56+

0 commit comments

Comments
 (0)