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