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