]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/early.rs
Rollup merge of #66564 - foeb:66219-document-unsafe-sync-cell-str, r=Amanieu
[rust.git] / src / librustc_lint / 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_session::lint::{LintBuffer, LintPass};
20 use rustc_session::Session;
21 use rustc_span::Span;
22 use syntax::ast;
23 use syntax::visit as ast_visit;
24
25 use log::debug;
26 use std::slice;
27
28 macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
29     $cx.pass.$f(&$cx.context, $($args),*);
30 }) }
31
32 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             self.context.lookup_and_emit_with_diagnostics(
41                 early_lint.lint_id.lint,
42                 Some(early_lint.span.clone()),
43                 &early_lint.msg,
44                 early_lint.diagnostic,
45             );
46         }
47     }
48
49     /// Merge the lints specified by any lint attributes into the
50     /// current lint context, call the provided function, then reset the
51     /// lints in effect to their previous state.
52     fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
53     where
54         F: FnOnce(&mut Self),
55     {
56         let push = self.context.builder.push(attrs, &self.context.lint_store);
57         self.check_id(id);
58         self.enter_attrs(attrs);
59         f(self);
60         self.exit_attrs(attrs);
61         self.context.builder.pop(push);
62     }
63
64     fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
65         debug!("early context: enter_attrs({:?})", attrs);
66         run_early_pass!(self, enter_lint_attrs, attrs);
67     }
68
69     fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
70         debug!("early context: exit_attrs({:?})", attrs);
71         run_early_pass!(self, exit_lint_attrs, attrs);
72     }
73 }
74
75 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
76     fn visit_param(&mut self, param: &'a ast::Param) {
77         self.with_lint_attrs(param.id, &param.attrs, |cx| {
78             run_early_pass!(cx, check_param, param);
79             ast_visit::walk_param(cx, param);
80         });
81     }
82
83     fn visit_item(&mut self, it: &'a ast::Item) {
84         self.with_lint_attrs(it.id, &it.attrs, |cx| {
85             run_early_pass!(cx, check_item, it);
86             ast_visit::walk_item(cx, it);
87             run_early_pass!(cx, check_item_post, it);
88         })
89     }
90
91     fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
92         self.with_lint_attrs(it.id, &it.attrs, |cx| {
93             run_early_pass!(cx, check_foreign_item, it);
94             ast_visit::walk_foreign_item(cx, it);
95             run_early_pass!(cx, check_foreign_item_post, it);
96         })
97     }
98
99     fn visit_pat(&mut self, p: &'a ast::Pat) {
100         run_early_pass!(self, check_pat, p);
101         self.check_id(p.id);
102         ast_visit::walk_pat(self, p);
103         run_early_pass!(self, check_pat_post, p);
104     }
105
106     fn visit_expr(&mut self, e: &'a ast::Expr) {
107         self.with_lint_attrs(e.id, &e.attrs, |cx| {
108             run_early_pass!(cx, check_expr, e);
109             ast_visit::walk_expr(cx, e);
110         })
111     }
112
113     fn visit_stmt(&mut self, s: &'a ast::Stmt) {
114         run_early_pass!(self, check_stmt, s);
115         self.check_id(s.id);
116         ast_visit::walk_stmt(self, s);
117     }
118
119     fn visit_fn(
120         &mut self,
121         fk: ast_visit::FnKind<'a>,
122         decl: &'a ast::FnDecl,
123         span: Span,
124         id: ast::NodeId,
125     ) {
126         run_early_pass!(self, check_fn, fk, decl, span, id);
127         self.check_id(id);
128         ast_visit::walk_fn(self, fk, decl, span);
129         run_early_pass!(self, check_fn_post, fk, decl, span, id);
130     }
131
132     fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
133         run_early_pass!(self, check_struct_def, s);
134         if let Some(ctor_hir_id) = s.ctor_id() {
135             self.check_id(ctor_hir_id);
136         }
137         ast_visit::walk_struct_def(self, s);
138         run_early_pass!(self, check_struct_def_post, s);
139     }
140
141     fn visit_struct_field(&mut self, s: &'a ast::StructField) {
142         self.with_lint_attrs(s.id, &s.attrs, |cx| {
143             run_early_pass!(cx, check_struct_field, s);
144             ast_visit::walk_struct_field(cx, s);
145         })
146     }
147
148     fn visit_variant(&mut self, v: &'a ast::Variant) {
149         self.with_lint_attrs(v.id, &v.attrs, |cx| {
150             run_early_pass!(cx, check_variant, v);
151             ast_visit::walk_variant(cx, v);
152             run_early_pass!(cx, check_variant_post, v);
153         })
154     }
155
156     fn visit_ty(&mut self, t: &'a ast::Ty) {
157         run_early_pass!(self, check_ty, t);
158         self.check_id(t.id);
159         ast_visit::walk_ty(self, t);
160     }
161
162     fn visit_ident(&mut self, ident: ast::Ident) {
163         run_early_pass!(self, check_ident, ident);
164     }
165
166     fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
167         run_early_pass!(self, check_mod, m, s, n);
168         self.check_id(n);
169         ast_visit::walk_mod(self, m);
170         run_early_pass!(self, check_mod_post, m, s, n);
171     }
172
173     fn visit_local(&mut self, l: &'a ast::Local) {
174         self.with_lint_attrs(l.id, &l.attrs, |cx| {
175             run_early_pass!(cx, check_local, l);
176             ast_visit::walk_local(cx, l);
177         })
178     }
179
180     fn visit_block(&mut self, b: &'a ast::Block) {
181         run_early_pass!(self, check_block, b);
182         self.check_id(b.id);
183         ast_visit::walk_block(self, b);
184         run_early_pass!(self, check_block_post, b);
185     }
186
187     fn visit_arm(&mut self, a: &'a ast::Arm) {
188         run_early_pass!(self, check_arm, a);
189         ast_visit::walk_arm(self, a);
190     }
191
192     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
193         run_early_pass!(self, check_expr_post, e);
194     }
195
196     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
197         run_early_pass!(self, check_generic_param, param);
198         ast_visit::walk_generic_param(self, param);
199     }
200
201     fn visit_generics(&mut self, g: &'a ast::Generics) {
202         run_early_pass!(self, check_generics, g);
203         ast_visit::walk_generics(self, g);
204     }
205
206     fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
207         run_early_pass!(self, check_where_predicate, p);
208         ast_visit::walk_where_predicate(self, p);
209     }
210
211     fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
212         run_early_pass!(self, check_poly_trait_ref, t, m);
213         ast_visit::walk_poly_trait_ref(self, t, m);
214     }
215
216     fn visit_trait_item(&mut self, trait_item: &'a ast::AssocItem) {
217         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
218             run_early_pass!(cx, check_trait_item, trait_item);
219             ast_visit::walk_trait_item(cx, trait_item);
220             run_early_pass!(cx, check_trait_item_post, trait_item);
221         });
222     }
223
224     fn visit_impl_item(&mut self, impl_item: &'a ast::AssocItem) {
225         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
226             run_early_pass!(cx, check_impl_item, impl_item);
227             ast_visit::walk_impl_item(cx, impl_item);
228             run_early_pass!(cx, check_impl_item_post, impl_item);
229         });
230     }
231
232     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
233         run_early_pass!(self, check_lifetime, lt);
234         self.check_id(lt.id);
235     }
236
237     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
238         run_early_pass!(self, check_path, p, id);
239         self.check_id(id);
240         ast_visit::walk_path(self, p);
241     }
242
243     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
244         run_early_pass!(self, check_attribute, attr);
245     }
246
247     fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
248         run_early_pass!(self, check_mac_def, mac, id);
249         self.check_id(id);
250     }
251
252     fn visit_mac(&mut self, mac: &'a ast::Mac) {
253         // FIXME(#54110): So, this setup isn't really right. I think
254         // that (a) the libsyntax visitor ought to be doing this as
255         // part of `walk_mac`, and (b) we should be calling
256         // `visit_path`, *but* that would require a `NodeId`, and I
257         // want to get #53686 fixed quickly. -nmatsakis
258         ast_visit::walk_path(self, &mac.path);
259
260         run_early_pass!(self, check_mac, mac);
261     }
262 }
263
264 struct EarlyLintPassObjects<'a> {
265     lints: &'a mut [EarlyLintPassObject],
266 }
267
268 #[allow(rustc::lint_pass_impl_without_macro)]
269 impl LintPass for EarlyLintPassObjects<'_> {
270     fn name(&self) -> &'static str {
271         panic!()
272     }
273 }
274
275 macro_rules! expand_early_lint_pass_impl_methods {
276     ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
277         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
278             for obj in self.lints.iter_mut() {
279                 obj.$name(context, $($param),*);
280             }
281         })*
282     )
283 }
284
285 macro_rules! early_lint_pass_impl {
286     ([], [$($methods:tt)*]) => (
287         impl EarlyLintPass for EarlyLintPassObjects<'_> {
288             expand_early_lint_pass_impl_methods!([$($methods)*]);
289         }
290     )
291 }
292
293 crate::early_lint_methods!(early_lint_pass_impl, []);
294
295 fn early_lint_crate<T: EarlyLintPass>(
296     sess: &Session,
297     lint_store: &LintStore,
298     krate: &ast::Crate,
299     pass: T,
300     buffered: LintBuffer,
301     warn_about_weird_lints: bool,
302 ) -> LintBuffer {
303     let mut cx = EarlyContextAndPass {
304         context: EarlyContext::new(sess, lint_store, krate, buffered, warn_about_weird_lints),
305         pass,
306     };
307
308     // Visit the whole crate.
309     cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
310         // since the root module isn't visited as an item (because it isn't an
311         // item), warn for it here.
312         run_early_pass!(cx, check_crate, krate);
313
314         ast_visit::walk_crate(cx, krate);
315
316         run_early_pass!(cx, check_crate_post, krate);
317     });
318     cx.context.buffered
319 }
320
321 pub fn check_ast_crate<T: EarlyLintPass>(
322     sess: &Session,
323     lint_store: &LintStore,
324     krate: &ast::Crate,
325     pre_expansion: bool,
326     lint_buffer: Option<LintBuffer>,
327     builtin_lints: T,
328 ) {
329     let mut passes: Vec<_> = if pre_expansion {
330         lint_store.pre_expansion_passes.iter().map(|p| (p)()).collect()
331     } else {
332         lint_store.early_passes.iter().map(|p| (p)()).collect()
333     };
334     let mut buffered = lint_buffer.unwrap_or_default();
335
336     if !sess.opts.debugging_opts.no_interleave_lints {
337         buffered =
338             early_lint_crate(sess, lint_store, krate, builtin_lints, buffered, pre_expansion);
339
340         if !passes.is_empty() {
341             buffered = early_lint_crate(
342                 sess,
343                 lint_store,
344                 krate,
345                 EarlyLintPassObjects { lints: &mut passes[..] },
346                 buffered,
347                 pre_expansion,
348             );
349         }
350     } else {
351         for pass in &mut passes {
352             buffered = sess
353                 .prof
354                 .extra_verbose_generic_activity(&format!("running lint: {}", pass.name()))
355                 .run(|| {
356                     early_lint_crate(
357                         sess,
358                         lint_store,
359                         krate,
360                         EarlyLintPassObjects { lints: slice::from_mut(pass) },
361                         buffered,
362                         pre_expansion,
363                     )
364                 });
365         }
366     }
367
368     // All of the buffered lints should have been emitted at this point.
369     // If not, that means that we somehow buffered a lint for a node id
370     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
371     //
372     // Rustdoc runs everybody-loops before the early lints and removes
373     // function bodies, so it's totally possible for linted
374     // node ids to not exist (e.g., macros defined within functions for the
375     // unused_macro lint) anymore. So we only run this check
376     // when we're not in rustdoc mode. (see issue #47639)
377     if !sess.opts.actually_rustdoc {
378         for (_id, lints) in buffered.map {
379             for early_lint in lints {
380                 sess.delay_span_bug(early_lint.span, "failed to process buffered lint here");
381             }
382         }
383     }
384 }