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