]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/early.rs
Box `ExprKind::{Closure,MethodCall}`, and `QSelf` in expressions, types, and patterns.
[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::{self as ast, walk_list, HasAttrs};
22 use rustc_middle::ty::RegisteredTools;
23 use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass};
24 use rustc_session::Session;
25 use rustc_span::symbol::Ident;
26 use rustc_span::Span;
27
28 use std::slice;
29
30 macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
31     $cx.pass.$f(&$cx.context, $($args),*);
32 }) }
33
34 pub struct EarlyContextAndPass<'a, T: EarlyLintPass> {
35     context: EarlyContext<'a>,
36     pass: T,
37 }
38
39 impl<'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) {
42             let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
43             self.context.lookup_with_diagnostics(
44                 lint_id.lint,
45                 Some(span),
46                 msg,
47                 |lint| lint,
48                 diagnostic,
49             );
50         }
51     }
52
53     /// Merge the lints specified by any lint attributes into the
54     /// current lint context, call the provided function, then reset the
55     /// lints in effect to their previous state.
56     fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
57     where
58         F: FnOnce(&mut Self),
59     {
60         let is_crate_node = id == ast::CRATE_NODE_ID;
61         debug!(?id);
62         let push = self.context.builder.push(attrs, is_crate_node, None);
63
64         self.check_id(id);
65         debug!("early context: enter_attrs({:?})", attrs);
66         run_early_pass!(self, enter_lint_attrs, attrs);
67         f(self);
68         debug!("early context: exit_attrs({:?})", attrs);
69         run_early_pass!(self, exit_lint_attrs, attrs);
70         self.context.builder.pop(push);
71     }
72 }
73
74 impl<'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| {
92             ast_visit::walk_foreign_item(cx, it);
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
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
109     fn visit_anon_const(&mut self, c: &'a ast::AnonConst) {
110         self.check_id(c.id);
111         ast_visit::walk_anon_const(self, c);
112     }
113
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
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
127     fn visit_stmt(&mut self, s: &'a ast::Stmt) {
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
144         ast_visit::walk_stmt(self, s);
145     }
146
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);
149         self.check_id(id);
150         ast_visit::walk_fn(self, fk);
151
152         // Explicitly check for lints associated with 'closure_id', since
153         // it does not have a corresponding AST node
154         if let ast_visit::FnKind::Fn(_, _, sig, _, _, _) = fk {
155             if let ast::Async::Yes { closure_id, .. } = sig.header.asyncness {
156                 self.check_id(closure_id);
157             }
158         }
159     }
160
161     fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
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);
166     }
167
168     fn visit_field_def(&mut self, s: &'a ast::FieldDef) {
169         self.with_lint_attrs(s.id, &s.attrs, |cx| {
170             ast_visit::walk_field_def(cx, s);
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);
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
187     fn visit_ident(&mut self, ident: Ident) {
188         run_early_pass!(self, check_ident, ident);
189     }
190
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);
202     }
203
204     fn visit_arm(&mut self, a: &'a ast::Arm) {
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         })
209     }
210
211     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
212         // Explicitly check for lints associated with 'closure_id', since
213         // it does not have a corresponding AST node
214         match e.kind {
215             ast::ExprKind::Closure(box ast::Closure {
216                 asyncness: ast::Async::Yes { closure_id, .. },
217                 ..
218             })
219             | ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id),
220             _ => {}
221         }
222     }
223
224     fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) {
225         run_early_pass!(self, check_generic_arg, arg);
226         ast_visit::walk_generic_arg(self, arg);
227     }
228
229     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
230         self.with_lint_attrs(param.id, &param.attrs, |cx| {
231             run_early_pass!(cx, check_generic_param, param);
232             ast_visit::walk_generic_param(cx, param);
233         });
234     }
235
236     fn visit_generics(&mut self, g: &'a ast::Generics) {
237         run_early_pass!(self, check_generics, g);
238         ast_visit::walk_generics(self, g);
239     }
240
241     fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
242         ast_visit::walk_where_predicate(self, p);
243     }
244
245     fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
246         run_early_pass!(self, check_poly_trait_ref, t);
247         ast_visit::walk_poly_trait_ref(self, t);
248     }
249
250     fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
251         self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt {
252             ast_visit::AssocCtxt::Trait => {
253                 run_early_pass!(cx, check_trait_item, item);
254                 ast_visit::walk_assoc_item(cx, item, ctxt);
255             }
256             ast_visit::AssocCtxt::Impl => {
257                 run_early_pass!(cx, check_impl_item, item);
258                 ast_visit::walk_assoc_item(cx, item, ctxt);
259             }
260         });
261     }
262
263     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime, _: ast_visit::LifetimeCtxt) {
264         self.check_id(lt.id);
265     }
266
267     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
268         self.check_id(id);
269         ast_visit::walk_path(self, p);
270     }
271
272     fn visit_path_segment(&mut self, s: &'a ast::PathSegment) {
273         self.check_id(s.id);
274         ast_visit::walk_path_segment(self, s);
275     }
276
277     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
278         run_early_pass!(self, check_attribute, attr);
279     }
280
281     fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
282         run_early_pass!(self, check_mac_def, mac);
283         self.check_id(id);
284     }
285
286     fn visit_mac_call(&mut self, mac: &'a ast::MacCall) {
287         run_early_pass!(self, check_mac, mac);
288         ast_visit::walk_mac(self, mac);
289     }
290 }
291
292 struct EarlyLintPassObjects<'a> {
293     lints: &'a mut [EarlyLintPassObject],
294 }
295
296 #[allow(rustc::lint_pass_impl_without_macro)]
297 impl LintPass for EarlyLintPassObjects<'_> {
298     fn name(&self) -> &'static str {
299         panic!()
300     }
301 }
302
303 macro_rules! expand_early_lint_pass_impl_methods {
304     ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
305         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
306             for obj in self.lints.iter_mut() {
307                 obj.$name(context, $($param),*);
308             }
309         })*
310     )
311 }
312
313 macro_rules! early_lint_pass_impl {
314     ([], [$($methods:tt)*]) => (
315         impl EarlyLintPass for EarlyLintPassObjects<'_> {
316             expand_early_lint_pass_impl_methods!([$($methods)*]);
317         }
318     )
319 }
320
321 crate::early_lint_methods!(early_lint_pass_impl, []);
322
323 /// Early lints work on different nodes - either on the crate root, or on freshly loaded modules.
324 /// This trait generalizes over those nodes.
325 pub trait EarlyCheckNode<'a>: Copy {
326     fn id(self) -> ast::NodeId;
327     fn attrs<'b>(self) -> &'b [ast::Attribute]
328     where
329         'a: 'b;
330     fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
331     where
332         'a: 'b;
333 }
334
335 impl<'a> EarlyCheckNode<'a> for &'a ast::Crate {
336     fn id(self) -> ast::NodeId {
337         ast::CRATE_NODE_ID
338     }
339     fn attrs<'b>(self) -> &'b [ast::Attribute]
340     where
341         'a: 'b,
342     {
343         &self.attrs
344     }
345     fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
346     where
347         'a: 'b,
348     {
349         run_early_pass!(cx, check_crate, self);
350         ast_visit::walk_crate(cx, self);
351         run_early_pass!(cx, check_crate_post, self);
352     }
353 }
354
355 impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P<ast::Item>]) {
356     fn id(self) -> ast::NodeId {
357         self.0
358     }
359     fn attrs<'b>(self) -> &'b [ast::Attribute]
360     where
361         'a: 'b,
362     {
363         self.1
364     }
365     fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
366     where
367         'a: 'b,
368     {
369         walk_list!(cx, visit_attribute, self.1);
370         walk_list!(cx, visit_item, self.2);
371     }
372 }
373
374 fn early_lint_node<'a>(
375     sess: &Session,
376     warn_about_weird_lints: bool,
377     lint_store: &LintStore,
378     registered_tools: &RegisteredTools,
379     buffered: LintBuffer,
380     pass: impl EarlyLintPass,
381     check_node: impl EarlyCheckNode<'a>,
382 ) -> LintBuffer {
383     let mut cx = EarlyContextAndPass {
384         context: EarlyContext::new(
385             sess,
386             warn_about_weird_lints,
387             lint_store,
388             registered_tools,
389             buffered,
390         ),
391         pass,
392     };
393
394     cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx));
395     cx.context.buffered
396 }
397
398 pub fn check_ast_node<'a>(
399     sess: &Session,
400     pre_expansion: bool,
401     lint_store: &LintStore,
402     registered_tools: &RegisteredTools,
403     lint_buffer: Option<LintBuffer>,
404     builtin_lints: impl EarlyLintPass,
405     check_node: impl EarlyCheckNode<'a>,
406 ) {
407     let passes =
408         if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
409     let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect();
410     let mut buffered = lint_buffer.unwrap_or_default();
411
412     if sess.opts.unstable_opts.no_interleave_lints {
413         for (i, pass) in passes.iter_mut().enumerate() {
414             buffered =
415                 sess.prof.verbose_generic_activity_with_arg("run_lint", pass.name()).run(|| {
416                     early_lint_node(
417                         sess,
418                         !pre_expansion && i == 0,
419                         lint_store,
420                         registered_tools,
421                         buffered,
422                         EarlyLintPassObjects { lints: slice::from_mut(pass) },
423                         check_node,
424                     )
425                 });
426         }
427     } else {
428         buffered = early_lint_node(
429             sess,
430             !pre_expansion,
431             lint_store,
432             registered_tools,
433             buffered,
434             builtin_lints,
435             check_node,
436         );
437
438         if !passes.is_empty() {
439             buffered = early_lint_node(
440                 sess,
441                 false,
442                 lint_store,
443                 registered_tools,
444                 buffered,
445                 EarlyLintPassObjects { lints: &mut passes[..] },
446                 check_node,
447             );
448         }
449     }
450
451     // All of the buffered lints should have been emitted at this point.
452     // If not, that means that we somehow buffered a lint for a node id
453     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
454     for (id, lints) in buffered.map {
455         for early_lint in lints {
456             sess.delay_span_bug(
457                 early_lint.span,
458                 &format!(
459                     "failed to process buffered lint here (dummy = {})",
460                     id == ast::DUMMY_NODE_ID
461                 ),
462             );
463         }
464     }
465 }