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