]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_lint/src/early.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / compiler / rustc_lint / src / early.rs
CommitLineData
dfeec247
XL
1//! Implementation of lint checking.
2//!
3//! The lint checking is mostly consolidated into one pass which runs
4//! after all other analyses. Throughout compilation, lint warnings
5//! can be added via the `add_lint` method on the Session structure. This
6//! requires a span and an ID of the node that the lint is being added to. The
7//! lint isn't actually emitted at that time because it is unknown what the
8//! actual lint level at that location is.
9//!
10//! To actually emit lint warnings/errors, a separate pass is used.
11//! A context keeps track of the current state of all lint levels.
12//! Upon entering a node of the ast which can modify the lint settings, the
13//! previous lint state is pushed onto a stack and the ast is then recursed
14//! upon. As the ast is traversed, this keeps track of the current lint level
15//! for all lint attributes.
16
17use crate::context::{EarlyContext, LintContext, LintStore};
18use crate::passes::{EarlyLintPass, EarlyLintPassObject};
5099ac24
FG
19use rustc_ast::ptr::P;
20use rustc_ast::visit::{self as ast_visit, Visitor};
04454e1e 21use rustc_ast::{self as ast, walk_list, HasAttrs};
5099ac24 22use rustc_middle::ty::RegisteredTools;
ba9703b0 23use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass};
dfeec247 24use rustc_session::Session;
f9f354fc 25use rustc_span::symbol::Ident;
dfeec247 26use rustc_span::Span;
dfeec247 27
dfeec247
XL
28use std::slice;
29
30macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
31 $cx.pass.$f(&$cx.context, $($args),*);
32}) }
33
5099ac24 34pub struct EarlyContextAndPass<'a, T: EarlyLintPass> {
dfeec247
XL
35 context: EarlyContext<'a>,
36 pass: T,
37}
38
39impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
40 fn check_id(&mut self, id: ast::NodeId) {
41 for early_lint in self.context.buffered.take(id) {
ba9703b0 42 let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
74b04a01
XL
43 self.context.lookup_with_diagnostics(
44 lint_id.lint,
45 Some(span),
5e7ed085 46 |lint| {
f2b60f7d 47 lint.build(msg).emit();
5e7ed085 48 },
74b04a01 49 diagnostic,
dfeec247
XL
50 );
51 }
52 }
53
54 /// Merge the lints specified by any lint attributes into the
55 /// current lint context, call the provided function, then reset the
56 /// lints in effect to their previous state.
57 fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
58 where
59 F: FnOnce(&mut Self),
60 {
f035d41b 61 let is_crate_node = id == ast::CRATE_NODE_ID;
5e7ed085
FG
62 let push = self.context.builder.push(attrs, is_crate_node, None);
63
dfeec247 64 self.check_id(id);
dfeec247
XL
65 debug!("early context: enter_attrs({:?})", attrs);
66 run_early_pass!(self, enter_lint_attrs, attrs);
923072b8 67 f(self);
dfeec247
XL
68 debug!("early context: exit_attrs({:?})", attrs);
69 run_early_pass!(self, exit_lint_attrs, attrs);
923072b8 70 self.context.builder.pop(push);
dfeec247
XL
71 }
72}
73
74impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
75 fn visit_param(&mut self, param: &'a ast::Param) {
76 self.with_lint_attrs(param.id, &param.attrs, |cx| {
77 run_early_pass!(cx, check_param, param);
78 ast_visit::walk_param(cx, param);
79 });
80 }
81
82 fn visit_item(&mut self, it: &'a ast::Item) {
83 self.with_lint_attrs(it.id, &it.attrs, |cx| {
84 run_early_pass!(cx, check_item, it);
85 ast_visit::walk_item(cx, it);
86 run_early_pass!(cx, check_item_post, it);
87 })
88 }
89
90 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
91 self.with_lint_attrs(it.id, &it.attrs, |cx| {
dfeec247 92 ast_visit::walk_foreign_item(cx, it);
dfeec247
XL
93 })
94 }
95
96 fn visit_pat(&mut self, p: &'a ast::Pat) {
97 run_early_pass!(self, check_pat, p);
98 self.check_id(p.id);
99 ast_visit::walk_pat(self, p);
100 run_early_pass!(self, check_pat_post, p);
101 }
102
f2b60f7d
FG
103 fn visit_pat_field(&mut self, field: &'a ast::PatField) {
104 self.with_lint_attrs(field.id, &field.attrs, |cx| {
105 ast_visit::walk_pat_field(cx, field);
106 });
107 }
108
ba9703b0 109 fn visit_anon_const(&mut self, c: &'a ast::AnonConst) {
cdc7bbd5 110 self.check_id(c.id);
ba9703b0
XL
111 ast_visit::walk_anon_const(self, c);
112 }
113
dfeec247
XL
114 fn visit_expr(&mut self, e: &'a ast::Expr) {
115 self.with_lint_attrs(e.id, &e.attrs, |cx| {
116 run_early_pass!(cx, check_expr, e);
117 ast_visit::walk_expr(cx, e);
118 })
119 }
120
136023e0
XL
121 fn visit_expr_field(&mut self, f: &'a ast::ExprField) {
122 self.with_lint_attrs(f.id, &f.attrs, |cx| {
123 ast_visit::walk_expr_field(cx, f);
124 })
125 }
126
dfeec247 127 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
29967ef6
XL
128 // Add the statement's lint attributes to our
129 // current state when checking the statement itself.
130 // This allows us to handle attributes like
131 // `#[allow(unused_doc_comments)]`, which apply to
132 // sibling attributes on the same target
133 //
134 // Note that statements get their attributes from
135 // the AST struct that they wrap (e.g. an item)
136 self.with_lint_attrs(s.id, s.attrs(), |cx| {
137 run_early_pass!(cx, check_stmt, s);
138 cx.check_id(s.id);
139 });
140 // The visitor for the AST struct wrapped
141 // by the statement (e.g. `Item`) will call
142 // `with_lint_attrs`, so do this walk
143 // outside of the above `with_lint_attrs` call
dfeec247
XL
144 ast_visit::walk_stmt(self, s);
145 }
146
74b04a01
XL
147 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId) {
148 run_early_pass!(self, check_fn, fk, span, id);
dfeec247 149 self.check_id(id);
f2b60f7d 150 ast_visit::walk_fn(self, fk);
5869c6ff
XL
151
152 // Explicitly check for lints associated with 'closure_id', since
153 // it does not have a corresponding AST node
04454e1e 154 if let ast_visit::FnKind::Fn(_, _, sig, _, _, _) = fk {
5869c6ff
XL
155 if let ast::Async::Yes { closure_id, .. } = sig.header.asyncness {
156 self.check_id(closure_id);
157 }
158 }
dfeec247
XL
159 }
160
161 fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
dfeec247
XL
162 if let Some(ctor_hir_id) = s.ctor_id() {
163 self.check_id(ctor_hir_id);
164 }
165 ast_visit::walk_struct_def(self, s);
dfeec247
XL
166 }
167
6a06907d 168 fn visit_field_def(&mut self, s: &'a ast::FieldDef) {
dfeec247 169 self.with_lint_attrs(s.id, &s.attrs, |cx| {
6a06907d 170 ast_visit::walk_field_def(cx, s);
dfeec247
XL
171 })
172 }
173
174 fn visit_variant(&mut self, v: &'a ast::Variant) {
175 self.with_lint_attrs(v.id, &v.attrs, |cx| {
176 run_early_pass!(cx, check_variant, v);
177 ast_visit::walk_variant(cx, v);
dfeec247
XL
178 })
179 }
180
181 fn visit_ty(&mut self, t: &'a ast::Ty) {
182 run_early_pass!(self, check_ty, t);
183 self.check_id(t.id);
184 ast_visit::walk_ty(self, t);
185 }
186
f9f354fc 187 fn visit_ident(&mut self, ident: Ident) {
dfeec247
XL
188 run_early_pass!(self, check_ident, ident);
189 }
190
dfeec247
XL
191 fn visit_local(&mut self, l: &'a ast::Local) {
192 self.with_lint_attrs(l.id, &l.attrs, |cx| {
193 run_early_pass!(cx, check_local, l);
194 ast_visit::walk_local(cx, l);
195 })
196 }
197
198 fn visit_block(&mut self, b: &'a ast::Block) {
199 run_early_pass!(self, check_block, b);
200 self.check_id(b.id);
201 ast_visit::walk_block(self, b);
dfeec247
XL
202 }
203
204 fn visit_arm(&mut self, a: &'a ast::Arm) {
136023e0
XL
205 self.with_lint_attrs(a.id, &a.attrs, |cx| {
206 run_early_pass!(cx, check_arm, a);
207 ast_visit::walk_arm(cx, a);
208 })
dfeec247
XL
209 }
210
211 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
5869c6ff
XL
212 // Explicitly check for lints associated with 'closure_id', since
213 // it does not have a corresponding AST node
214 match e.kind {
064997fb 215 ast::ExprKind::Closure(_, _, ast::Async::Yes { closure_id, .. }, ..)
5869c6ff
XL
216 | ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id),
217 _ => {}
218 }
dfeec247
XL
219 }
220
29967ef6
XL
221 fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) {
222 run_early_pass!(self, check_generic_arg, arg);
223 ast_visit::walk_generic_arg(self, arg);
224 }
225
dfeec247 226 fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
f2b60f7d
FG
227 self.with_lint_attrs(param.id, &param.attrs, |cx| {
228 run_early_pass!(cx, check_generic_param, param);
229 ast_visit::walk_generic_param(cx, param);
230 });
dfeec247
XL
231 }
232
233 fn visit_generics(&mut self, g: &'a ast::Generics) {
234 run_early_pass!(self, check_generics, g);
235 ast_visit::walk_generics(self, g);
236 }
237
238 fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
dfeec247
XL
239 ast_visit::walk_where_predicate(self, p);
240 }
241
f2b60f7d
FG
242 fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
243 run_early_pass!(self, check_poly_trait_ref, t);
244 ast_visit::walk_poly_trait_ref(self, t);
dfeec247
XL
245 }
246
74b04a01
XL
247 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
248 self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt {
249 ast_visit::AssocCtxt::Trait => {
250 run_early_pass!(cx, check_trait_item, item);
251 ast_visit::walk_assoc_item(cx, item, ctxt);
74b04a01
XL
252 }
253 ast_visit::AssocCtxt::Impl => {
254 run_early_pass!(cx, check_impl_item, item);
255 ast_visit::walk_assoc_item(cx, item, ctxt);
74b04a01 256 }
dfeec247
XL
257 });
258 }
259
923072b8 260 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime, _: ast_visit::LifetimeCtxt) {
dfeec247
XL
261 self.check_id(lt.id);
262 }
263
264 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
dfeec247
XL
265 self.check_id(id);
266 ast_visit::walk_path(self, p);
267 }
268
f2b60f7d 269 fn visit_path_segment(&mut self, s: &'a ast::PathSegment) {
04454e1e 270 self.check_id(s.id);
f2b60f7d 271 ast_visit::walk_path_segment(self, s);
04454e1e
FG
272 }
273
dfeec247
XL
274 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
275 run_early_pass!(self, check_attribute, attr);
276 }
277
278 fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
f2b60f7d 279 run_early_pass!(self, check_mac_def, mac);
dfeec247
XL
280 self.check_id(id);
281 }
282
29967ef6 283 fn visit_mac_call(&mut self, mac: &'a ast::MacCall) {
dfeec247 284 run_early_pass!(self, check_mac, mac);
29967ef6 285 ast_visit::walk_mac(self, mac);
dfeec247
XL
286 }
287}
288
289struct EarlyLintPassObjects<'a> {
290 lints: &'a mut [EarlyLintPassObject],
291}
292
293#[allow(rustc::lint_pass_impl_without_macro)]
294impl LintPass for EarlyLintPassObjects<'_> {
295 fn name(&self) -> &'static str {
296 panic!()
297 }
298}
299
300macro_rules! expand_early_lint_pass_impl_methods {
301 ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
302 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
303 for obj in self.lints.iter_mut() {
304 obj.$name(context, $($param),*);
305 }
306 })*
307 )
308}
309
310macro_rules! early_lint_pass_impl {
311 ([], [$($methods:tt)*]) => (
312 impl EarlyLintPass for EarlyLintPassObjects<'_> {
313 expand_early_lint_pass_impl_methods!([$($methods)*]);
314 }
315 )
316}
317
318crate::early_lint_methods!(early_lint_pass_impl, []);
319
5099ac24
FG
320/// Early lints work on different nodes - either on the crate root, or on freshly loaded modules.
321/// This trait generalizes over those nodes.
322pub trait EarlyCheckNode<'a>: Copy {
323 fn id(self) -> ast::NodeId;
324 fn attrs<'b>(self) -> &'b [ast::Attribute]
325 where
326 'a: 'b;
327 fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
328 where
329 'a: 'b;
330}
331
332impl<'a> EarlyCheckNode<'a> for &'a ast::Crate {
333 fn id(self) -> ast::NodeId {
334 ast::CRATE_NODE_ID
335 }
336 fn attrs<'b>(self) -> &'b [ast::Attribute]
337 where
338 'a: 'b,
339 {
340 &self.attrs
341 }
342 fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
343 where
344 'a: 'b,
345 {
346 run_early_pass!(cx, check_crate, self);
347 ast_visit::walk_crate(cx, self);
348 run_early_pass!(cx, check_crate_post, self);
349 }
350}
351
352impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P<ast::Item>]) {
353 fn id(self) -> ast::NodeId {
354 self.0
355 }
356 fn attrs<'b>(self) -> &'b [ast::Attribute]
357 where
358 'a: 'b,
359 {
360 self.1
361 }
362 fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
363 where
364 'a: 'b,
365 {
366 walk_list!(cx, visit_attribute, self.1);
367 walk_list!(cx, visit_item, self.2);
368 }
369}
370
371fn early_lint_node<'a>(
dfeec247 372 sess: &Session,
5099ac24 373 warn_about_weird_lints: bool,
dfeec247 374 lint_store: &LintStore,
5099ac24 375 registered_tools: &RegisteredTools,
dfeec247 376 buffered: LintBuffer,
5099ac24
FG
377 pass: impl EarlyLintPass,
378 check_node: impl EarlyCheckNode<'a>,
dfeec247
XL
379) -> LintBuffer {
380 let mut cx = EarlyContextAndPass {
c295e0f8
XL
381 context: EarlyContext::new(
382 sess,
5099ac24 383 warn_about_weird_lints,
c295e0f8 384 lint_store,
5099ac24 385 registered_tools,
c295e0f8 386 buffered,
c295e0f8 387 ),
dfeec247
XL
388 pass,
389 };
390
5099ac24 391 cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx));
dfeec247
XL
392 cx.context.buffered
393}
394
5099ac24 395pub fn check_ast_node<'a>(
dfeec247 396 sess: &Session,
dfeec247 397 pre_expansion: bool,
5099ac24
FG
398 lint_store: &LintStore,
399 registered_tools: &RegisteredTools,
dfeec247 400 lint_buffer: Option<LintBuffer>,
5099ac24
FG
401 builtin_lints: impl EarlyLintPass,
402 check_node: impl EarlyCheckNode<'a>,
dfeec247 403) {
ba9703b0
XL
404 let passes =
405 if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
406 let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect();
dfeec247
XL
407 let mut buffered = lint_buffer.unwrap_or_default();
408
064997fb 409 if sess.opts.unstable_opts.no_interleave_lints {
923072b8
FG
410 for (i, pass) in passes.iter_mut().enumerate() {
411 buffered =
412 sess.prof.extra_verbose_generic_activity("run_lint", pass.name()).run(|| {
413 early_lint_node(
414 sess,
415 !pre_expansion && i == 0,
416 lint_store,
417 registered_tools,
418 buffered,
419 EarlyLintPassObjects { lints: slice::from_mut(pass) },
420 check_node,
421 )
422 });
423 }
424 } else {
5099ac24 425 buffered = early_lint_node(
c295e0f8 426 sess,
923072b8 427 !pre_expansion,
c295e0f8 428 lint_store,
5099ac24 429 registered_tools,
c295e0f8 430 buffered,
5099ac24
FG
431 builtin_lints,
432 check_node,
c295e0f8 433 );
dfeec247
XL
434
435 if !passes.is_empty() {
5099ac24 436 buffered = early_lint_node(
dfeec247 437 sess,
5099ac24 438 false,
dfeec247 439 lint_store,
5099ac24 440 registered_tools,
dfeec247 441 buffered,
5099ac24
FG
442 EarlyLintPassObjects { lints: &mut passes[..] },
443 check_node,
dfeec247
XL
444 );
445 }
dfeec247
XL
446 }
447
448 // All of the buffered lints should have been emitted at this point.
449 // If not, that means that we somehow buffered a lint for a node id
450 // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
136023e0 451 for (id, lints) in buffered.map {
5869c6ff 452 for early_lint in lints {
136023e0
XL
453 sess.delay_span_bug(
454 early_lint.span,
455 &format!(
456 "failed to process buffered lint here (dummy = {})",
457 id == ast::DUMMY_NODE_ID
458 ),
459 );
dfeec247
XL
460 }
461 }
462}