]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/context.rs
Rollup merge of #67507 - Mark-Simulacrum:purge-uninit, r=Centril
[rust.git] / src / librustc / lint / context.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 self::TargetLint::*;
18
19 use crate::hir;
20 use crate::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
21 use crate::hir::intravisit as hir_visit;
22 use crate::hir::intravisit::Visitor;
23 use crate::hir::map::{definitions::DisambiguatedDefPathData, DefPathData};
24 use crate::lint::builtin::BuiltinLintDiagnostics;
25 use crate::lint::levels::{LintLevelSets, LintLevelsBuilder};
26 use crate::lint::{EarlyLintPass, EarlyLintPassObject, LateLintPass, LateLintPassObject};
27 use crate::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId, LintPass};
28 use crate::middle::privacy::AccessLevels;
29 use crate::session::Session;
30 use crate::ty::layout::{LayoutError, LayoutOf, TyLayout};
31 use crate::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt};
32 use crate::util::common::time;
33 use crate::util::nodemap::FxHashMap;
34
35 use errors::DiagnosticBuilder;
36 use rustc_data_structures::sync::{self, join, par_iter, ParallelIterator};
37 use std::slice;
38 use syntax::ast;
39 use syntax::util::lev_distance::find_best_match_for_name;
40 use syntax::visit as ast_visit;
41 use syntax_pos::{symbol::Symbol, MultiSpan, Span};
42
43 use rustc_error_codes::*;
44
45 /// Information about the registered lints.
46 ///
47 /// This is basically the subset of `Context` that we can
48 /// build early in the compile pipeline.
49 pub struct LintStore {
50     /// Registered lints.
51     lints: Vec<&'static Lint>,
52
53     /// Constructor functions for each variety of lint pass.
54     ///
55     /// These should only be called once, but since we want to avoid locks or
56     /// interior mutability, we don't enforce this (and lints should, in theory,
57     /// be compatible with being constructed more than once, though not
58     /// necessarily in a sane manner. This is safe though.)
59     pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
60     early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
61     late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
62     /// This is unique in that we construct them per-module, so not once.
63     late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
64
65     /// Lints indexed by name.
66     by_name: FxHashMap<String, TargetLint>,
67
68     /// Map of registered lint groups to what lints they expand to.
69     lint_groups: FxHashMap<&'static str, LintGroup>,
70 }
71
72 /// Lints that are buffered up early on in the `Session` before the
73 /// `LintLevels` is calculated
74 #[derive(PartialEq, Debug)]
75 pub struct BufferedEarlyLint {
76     pub lint_id: LintId,
77     pub ast_id: ast::NodeId,
78     pub span: MultiSpan,
79     pub msg: String,
80     pub diagnostic: BuiltinLintDiagnostics,
81 }
82
83 /// The target of the `by_name` map, which accounts for renaming/deprecation.
84 enum TargetLint {
85     /// A direct lint target
86     Id(LintId),
87
88     /// Temporary renaming, used for easing migration pain; see #16545
89     Renamed(String, LintId),
90
91     /// Lint with this name existed previously, but has been removed/deprecated.
92     /// The string argument is the reason for removal.
93     Removed(String),
94 }
95
96 pub enum FindLintError {
97     NotFound,
98     Removed,
99 }
100
101 struct LintAlias {
102     name: &'static str,
103     /// Whether deprecation warnings should be suppressed for this alias.
104     silent: bool,
105 }
106
107 struct LintGroup {
108     lint_ids: Vec<LintId>,
109     from_plugin: bool,
110     depr: Option<LintAlias>,
111 }
112
113 pub enum CheckLintNameResult<'a> {
114     Ok(&'a [LintId]),
115     /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
116     NoLint(Option<Symbol>),
117     /// The lint is either renamed or removed. This is the warning
118     /// message, and an optional new name (`None` if removed).
119     Warning(String, Option<String>),
120     /// The lint is from a tool. If the Option is None, then either
121     /// the lint does not exist in the tool or the code was not
122     /// compiled with the tool and therefore the lint was never
123     /// added to the `LintStore`. Otherwise the `LintId` will be
124     /// returned as if it where a rustc lint.
125     Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
126 }
127
128 impl LintStore {
129     pub fn new() -> LintStore {
130         LintStore {
131             lints: vec![],
132             pre_expansion_passes: vec![],
133             early_passes: vec![],
134             late_passes: vec![],
135             late_module_passes: vec![],
136             by_name: Default::default(),
137             lint_groups: Default::default(),
138         }
139     }
140
141     pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
142         &self.lints
143     }
144
145     pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
146         self.lint_groups
147             .iter()
148             .filter(|(_, LintGroup { depr, .. })| {
149                 // Don't display deprecated lint groups.
150                 depr.is_none()
151             })
152             .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
153                 (*k, lint_ids.clone(), *from_plugin)
154             })
155             .collect()
156     }
157
158     pub fn register_early_pass(
159         &mut self,
160         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
161     ) {
162         self.early_passes.push(Box::new(pass));
163     }
164
165     pub fn register_pre_expansion_pass(
166         &mut self,
167         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
168     ) {
169         self.pre_expansion_passes.push(Box::new(pass));
170     }
171
172     pub fn register_late_pass(
173         &mut self,
174         pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
175     ) {
176         self.late_passes.push(Box::new(pass));
177     }
178
179     pub fn register_late_mod_pass(
180         &mut self,
181         pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
182     ) {
183         self.late_module_passes.push(Box::new(pass));
184     }
185
186     // Helper method for register_early/late_pass
187     pub fn register_lints(&mut self, lints: &[&'static Lint]) {
188         for lint in lints {
189             self.lints.push(lint);
190
191             let id = LintId::of(lint);
192             if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
193                 bug!("duplicate specification of lint {}", lint.name_lower())
194             }
195
196             if let Some(FutureIncompatibleInfo { edition, .. }) = lint.future_incompatible {
197                 if let Some(edition) = edition {
198                     self.lint_groups
199                         .entry(edition.lint_name())
200                         .or_insert(LintGroup {
201                             lint_ids: vec![],
202                             from_plugin: lint.is_plugin,
203                             depr: None,
204                         })
205                         .lint_ids
206                         .push(id);
207                 }
208
209                 self.lint_groups
210                     .entry("future_incompatible")
211                     .or_insert(LintGroup {
212                         lint_ids: vec![],
213                         from_plugin: lint.is_plugin,
214                         depr: None,
215                     })
216                     .lint_ids
217                     .push(id);
218             }
219         }
220     }
221
222     pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
223         self.lint_groups.insert(
224             alias,
225             LintGroup {
226                 lint_ids: vec![],
227                 from_plugin: false,
228                 depr: Some(LintAlias { name: lint_name, silent: true }),
229             },
230         );
231     }
232
233     pub fn register_group(
234         &mut self,
235         from_plugin: bool,
236         name: &'static str,
237         deprecated_name: Option<&'static str>,
238         to: Vec<LintId>,
239     ) {
240         let new = self
241             .lint_groups
242             .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
243             .is_none();
244         if let Some(deprecated) = deprecated_name {
245             self.lint_groups.insert(
246                 deprecated,
247                 LintGroup {
248                     lint_ids: vec![],
249                     from_plugin,
250                     depr: Some(LintAlias { name, silent: false }),
251                 },
252             );
253         }
254
255         if !new {
256             bug!("duplicate specification of lint group {}", name);
257         }
258     }
259
260     pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
261         let target = match self.by_name.get(new_name) {
262             Some(&Id(lint_id)) => lint_id.clone(),
263             _ => bug!("invalid lint renaming of {} to {}", old_name, new_name),
264         };
265         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
266     }
267
268     pub fn register_removed(&mut self, name: &str, reason: &str) {
269         self.by_name.insert(name.into(), Removed(reason.into()));
270     }
271
272     pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
273         match self.by_name.get(lint_name) {
274             Some(&Id(lint_id)) => Ok(vec![lint_id]),
275             Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
276             Some(&Removed(_)) => Err(FindLintError::Removed),
277             None => loop {
278                 return match self.lint_groups.get(lint_name) {
279                     Some(LintGroup { lint_ids, depr, .. }) => {
280                         if let Some(LintAlias { name, .. }) = depr {
281                             lint_name = name;
282                             continue;
283                         }
284                         Ok(lint_ids.clone())
285                     }
286                     None => Err(FindLintError::Removed),
287                 };
288             },
289         }
290     }
291
292     /// Checks the validity of lint names derived from the command line
293     pub fn check_lint_name_cmdline(&self, sess: &Session, lint_name: &str, level: Level) {
294         let db = match self.check_lint_name(lint_name, None) {
295             CheckLintNameResult::Ok(_) => None,
296             CheckLintNameResult::Warning(ref msg, _) => Some(sess.struct_warn(msg)),
297             CheckLintNameResult::NoLint(suggestion) => {
298                 let mut err = struct_err!(sess, E0602, "unknown lint: `{}`", lint_name);
299
300                 if let Some(suggestion) = suggestion {
301                     err.help(&format!("did you mean: `{}`", suggestion));
302                 }
303
304                 Some(err)
305             }
306             CheckLintNameResult::Tool(result) => match result {
307                 Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
308                     "lint name `{}` is deprecated \
309                      and does not have an effect anymore. \
310                      Use: {}",
311                     lint_name, new_name
312                 ))),
313                 _ => None,
314             },
315         };
316
317         if let Some(mut db) = db {
318             let msg = format!(
319                 "requested on the command line with `{} {}`",
320                 match level {
321                     Level::Allow => "-A",
322                     Level::Warn => "-W",
323                     Level::Deny => "-D",
324                     Level::Forbid => "-F",
325                 },
326                 lint_name
327             );
328             db.note(&msg);
329             db.emit();
330         }
331     }
332
333     /// Checks the name of a lint for its existence, and whether it was
334     /// renamed or removed. Generates a DiagnosticBuilder containing a
335     /// warning for renamed and removed lints. This is over both lint
336     /// names from attributes and those passed on the command line. Since
337     /// it emits non-fatal warnings and there are *two* lint passes that
338     /// inspect attributes, this is only run from the late pass to avoid
339     /// printing duplicate warnings.
340     pub fn check_lint_name(
341         &self,
342         lint_name: &str,
343         tool_name: Option<Symbol>,
344     ) -> CheckLintNameResult<'_> {
345         let complete_name = if let Some(tool_name) = tool_name {
346             format!("{}::{}", tool_name, lint_name)
347         } else {
348             lint_name.to_string()
349         };
350         // If the lint was scoped with `tool::` check if the tool lint exists
351         if let Some(_) = tool_name {
352             match self.by_name.get(&complete_name) {
353                 None => match self.lint_groups.get(&*complete_name) {
354                     None => return CheckLintNameResult::Tool(Err((None, String::new()))),
355                     Some(LintGroup { lint_ids, .. }) => {
356                         return CheckLintNameResult::Tool(Ok(&lint_ids));
357                     }
358                 },
359                 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
360                 // If the lint was registered as removed or renamed by the lint tool, we don't need
361                 // to treat tool_lints and rustc lints different and can use the code below.
362                 _ => {}
363             }
364         }
365         match self.by_name.get(&complete_name) {
366             Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
367                 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
368                 Some(new_name.to_owned()),
369             ),
370             Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
371                 format!("lint `{}` has been removed: `{}`", complete_name, reason),
372                 None,
373             ),
374             None => match self.lint_groups.get(&*complete_name) {
375                 // If neither the lint, nor the lint group exists check if there is a `clippy::`
376                 // variant of this lint
377                 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
378                 Some(LintGroup { lint_ids, depr, .. }) => {
379                     // Check if the lint group name is deprecated
380                     if let Some(LintAlias { name, silent }) = depr {
381                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
382                         return if *silent {
383                             CheckLintNameResult::Ok(&lint_ids)
384                         } else {
385                             CheckLintNameResult::Tool(Err((Some(&lint_ids), name.to_string())))
386                         };
387                     }
388                     CheckLintNameResult::Ok(&lint_ids)
389                 }
390             },
391             Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
392         }
393     }
394
395     fn check_tool_name_for_backwards_compat(
396         &self,
397         lint_name: &str,
398         tool_name: &str,
399     ) -> CheckLintNameResult<'_> {
400         let complete_name = format!("{}::{}", tool_name, lint_name);
401         match self.by_name.get(&complete_name) {
402             None => match self.lint_groups.get(&*complete_name) {
403                 // Now we are sure, that this lint exists nowhere
404                 None => {
405                     let symbols =
406                         self.by_name.keys().map(|name| Symbol::intern(&name)).collect::<Vec<_>>();
407
408                     let suggestion =
409                         find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
410
411                     CheckLintNameResult::NoLint(suggestion)
412                 }
413                 Some(LintGroup { lint_ids, depr, .. }) => {
414                     // Reaching this would be weird, but let's cover this case anyway
415                     if let Some(LintAlias { name, silent }) = depr {
416                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
417                         return if *silent {
418                             CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
419                         } else {
420                             CheckLintNameResult::Tool(Err((Some(&lint_ids), name.to_string())))
421                         };
422                     }
423                     CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
424                 }
425             },
426             Some(&Id(ref id)) => {
427                 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
428             }
429             _ => CheckLintNameResult::NoLint(None),
430         }
431     }
432 }
433
434 /// Context for lint checking after type checking.
435 pub struct LateContext<'a, 'tcx> {
436     /// Type context we're checking in.
437     pub tcx: TyCtxt<'tcx>,
438
439     /// Side-tables for the body we are in.
440     // FIXME: Make this lazy to avoid running the TypeckTables query?
441     pub tables: &'a ty::TypeckTables<'tcx>,
442
443     /// Parameter environment for the item we are in.
444     pub param_env: ty::ParamEnv<'tcx>,
445
446     /// Items accessible from the crate being checked.
447     pub access_levels: &'a AccessLevels,
448
449     /// The store of registered lints and the lint levels.
450     lint_store: &'tcx LintStore,
451
452     last_node_with_lint_attrs: hir::HirId,
453
454     /// Generic type parameters in scope for the item we are in.
455     pub generics: Option<&'tcx hir::Generics>,
456
457     /// We are only looking at one module
458     only_module: bool,
459 }
460
461 pub struct LateContextAndPass<'a, 'tcx, T: LateLintPass<'a, 'tcx>> {
462     context: LateContext<'a, 'tcx>,
463     pass: T,
464 }
465
466 /// Context for lint checking of the AST, after expansion, before lowering to
467 /// HIR.
468 pub struct EarlyContext<'a> {
469     /// Type context we're checking in.
470     pub sess: &'a Session,
471
472     /// The crate being checked.
473     pub krate: &'a ast::Crate,
474
475     builder: LintLevelsBuilder<'a>,
476
477     /// The store of registered lints and the lint levels.
478     lint_store: &'a LintStore,
479
480     buffered: LintBuffer,
481 }
482
483 pub struct EarlyContextAndPass<'a, T: EarlyLintPass> {
484     context: EarlyContext<'a>,
485     pass: T,
486 }
487
488 pub trait LintPassObject: Sized {}
489
490 impl LintPassObject for EarlyLintPassObject {}
491
492 impl LintPassObject for LateLintPassObject {}
493
494 pub trait LintContext: Sized {
495     type PassObject: LintPassObject;
496
497     fn sess(&self) -> &Session;
498     fn lints(&self) -> &LintStore;
499
500     fn lookup_and_emit<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: Option<S>, msg: &str) {
501         self.lookup(lint, span, msg).emit();
502     }
503
504     fn lookup_and_emit_with_diagnostics<S: Into<MultiSpan>>(
505         &self,
506         lint: &'static Lint,
507         span: Option<S>,
508         msg: &str,
509         diagnostic: BuiltinLintDiagnostics,
510     ) {
511         let mut db = self.lookup(lint, span, msg);
512         diagnostic.run(self.sess(), &mut db);
513         db.emit();
514     }
515
516     fn lookup<S: Into<MultiSpan>>(
517         &self,
518         lint: &'static Lint,
519         span: Option<S>,
520         msg: &str,
521     ) -> DiagnosticBuilder<'_>;
522
523     /// Emit a lint at the appropriate level, for a particular span.
524     fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
525         self.lookup_and_emit(lint, Some(span), msg);
526     }
527
528     fn struct_span_lint<S: Into<MultiSpan>>(
529         &self,
530         lint: &'static Lint,
531         span: S,
532         msg: &str,
533     ) -> DiagnosticBuilder<'_> {
534         self.lookup(lint, Some(span), msg)
535     }
536
537     /// Emit a lint and note at the appropriate level, for a particular span.
538     fn span_lint_note(
539         &self,
540         lint: &'static Lint,
541         span: Span,
542         msg: &str,
543         note_span: Span,
544         note: &str,
545     ) {
546         let mut err = self.lookup(lint, Some(span), msg);
547         if note_span == span {
548             err.note(note);
549         } else {
550             err.span_note(note_span, note);
551         }
552         err.emit();
553     }
554
555     /// Emit a lint and help at the appropriate level, for a particular span.
556     fn span_lint_help(&self, lint: &'static Lint, span: Span, msg: &str, help: &str) {
557         let mut err = self.lookup(lint, Some(span), msg);
558         self.span_lint(lint, span, msg);
559         err.span_help(span, help);
560         err.emit();
561     }
562
563     /// Emit a lint at the appropriate level, with no associated span.
564     fn lint(&self, lint: &'static Lint, msg: &str) {
565         self.lookup_and_emit(lint, None as Option<Span>, msg);
566     }
567 }
568
569 impl<'a> EarlyContext<'a> {
570     fn new(
571         sess: &'a Session,
572         lint_store: &'a LintStore,
573         krate: &'a ast::Crate,
574         buffered: LintBuffer,
575         warn_about_weird_lints: bool,
576     ) -> EarlyContext<'a> {
577         EarlyContext {
578             sess,
579             krate,
580             lint_store,
581             builder: LintLevelSets::builder(sess, warn_about_weird_lints, lint_store),
582             buffered,
583         }
584     }
585 }
586
587 macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
588     $cx.pass.$f(&$cx.context, $($args),*);
589 }) }
590
591 macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
592     $cx.pass.$f(&$cx.context, $($args),*);
593 }) }
594
595 impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
596     fn check_id(&mut self, id: ast::NodeId) {
597         for early_lint in self.context.buffered.take(id) {
598             self.context.lookup_and_emit_with_diagnostics(
599                 early_lint.lint_id.lint,
600                 Some(early_lint.span.clone()),
601                 &early_lint.msg,
602                 early_lint.diagnostic,
603             );
604         }
605     }
606
607     /// Merge the lints specified by any lint attributes into the
608     /// current lint context, call the provided function, then reset the
609     /// lints in effect to their previous state.
610     fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
611     where
612         F: FnOnce(&mut Self),
613     {
614         let push = self.context.builder.push(attrs, &self.context.lint_store);
615         self.check_id(id);
616         self.enter_attrs(attrs);
617         f(self);
618         self.exit_attrs(attrs);
619         self.context.builder.pop(push);
620     }
621
622     fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
623         debug!("early context: enter_attrs({:?})", attrs);
624         run_early_pass!(self, enter_lint_attrs, attrs);
625     }
626
627     fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
628         debug!("early context: exit_attrs({:?})", attrs);
629         run_early_pass!(self, exit_lint_attrs, attrs);
630     }
631 }
632
633 impl LintContext for LateContext<'_, '_> {
634     type PassObject = LateLintPassObject;
635
636     /// Gets the overall compiler `Session` object.
637     fn sess(&self) -> &Session {
638         &self.tcx.sess
639     }
640
641     fn lints(&self) -> &LintStore {
642         &*self.lint_store
643     }
644
645     fn lookup<S: Into<MultiSpan>>(
646         &self,
647         lint: &'static Lint,
648         span: Option<S>,
649         msg: &str,
650     ) -> DiagnosticBuilder<'_> {
651         let hir_id = self.last_node_with_lint_attrs;
652
653         match span {
654             Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, msg),
655             None => self.tcx.struct_lint_node(lint, hir_id, msg),
656         }
657     }
658 }
659
660 impl LintContext for EarlyContext<'_> {
661     type PassObject = EarlyLintPassObject;
662
663     /// Gets the overall compiler `Session` object.
664     fn sess(&self) -> &Session {
665         &self.sess
666     }
667
668     fn lints(&self) -> &LintStore {
669         &*self.lint_store
670     }
671
672     fn lookup<S: Into<MultiSpan>>(
673         &self,
674         lint: &'static Lint,
675         span: Option<S>,
676         msg: &str,
677     ) -> DiagnosticBuilder<'_> {
678         self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
679     }
680 }
681
682 impl<'a, 'tcx> LateContext<'a, 'tcx> {
683     pub fn current_lint_root(&self) -> hir::HirId {
684         self.last_node_with_lint_attrs
685     }
686
687     /// Check if a `DefId`'s path matches the given absolute type path usage.
688     ///
689     /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
690     /// inherent `impl` blocks are matched with the name of the type.
691     ///
692     /// # Examples
693     ///
694     /// ```rust,ignore (no context or def id available)
695     /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
696     ///     // The given `def_id` is that of an `Option` type
697     /// }
698     /// ```
699     pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
700         let names = self.get_def_path(def_id);
701
702         names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
703     }
704
705     /// Gets the absolute path of `def_id` as a vector of `Symbol`.
706     ///
707     /// # Examples
708     ///
709     /// ```rust,ignore (no context or def id available)
710     /// let def_path = cx.get_def_path(def_id);
711     /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
712     ///     // The given `def_id` is that of an `Option` type
713     /// }
714     /// ```
715     pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
716         pub struct AbsolutePathPrinter<'tcx> {
717             pub tcx: TyCtxt<'tcx>,
718         }
719
720         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
721             type Error = !;
722
723             type Path = Vec<Symbol>;
724             type Region = ();
725             type Type = ();
726             type DynExistential = ();
727             type Const = ();
728
729             fn tcx(&self) -> TyCtxt<'tcx> {
730                 self.tcx
731             }
732
733             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
734                 Ok(())
735             }
736
737             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
738                 Ok(())
739             }
740
741             fn print_dyn_existential(
742                 self,
743                 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
744             ) -> Result<Self::DynExistential, Self::Error> {
745                 Ok(())
746             }
747
748             fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
749                 Ok(())
750             }
751
752             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
753                 Ok(vec![self.tcx.original_crate_name(cnum)])
754             }
755
756             fn path_qualified(
757                 self,
758                 self_ty: Ty<'tcx>,
759                 trait_ref: Option<ty::TraitRef<'tcx>>,
760             ) -> Result<Self::Path, Self::Error> {
761                 if trait_ref.is_none() {
762                     if let ty::Adt(def, substs) = self_ty.kind {
763                         return self.print_def_path(def.did, substs);
764                     }
765                 }
766
767                 // This shouldn't ever be needed, but just in case:
768                 Ok(vec![match trait_ref {
769                     Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
770                     None => Symbol::intern(&format!("<{}>", self_ty)),
771                 }])
772             }
773
774             fn path_append_impl(
775                 self,
776                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
777                 _disambiguated_data: &DisambiguatedDefPathData,
778                 self_ty: Ty<'tcx>,
779                 trait_ref: Option<ty::TraitRef<'tcx>>,
780             ) -> Result<Self::Path, Self::Error> {
781                 let mut path = print_prefix(self)?;
782
783                 // This shouldn't ever be needed, but just in case:
784                 path.push(match trait_ref {
785                     Some(trait_ref) => Symbol::intern(&format!(
786                         "<impl {} for {}>",
787                         trait_ref.print_only_trait_path(),
788                         self_ty
789                     )),
790                     None => Symbol::intern(&format!("<impl {}>", self_ty)),
791                 });
792
793                 Ok(path)
794             }
795
796             fn path_append(
797                 self,
798                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
799                 disambiguated_data: &DisambiguatedDefPathData,
800             ) -> Result<Self::Path, Self::Error> {
801                 let mut path = print_prefix(self)?;
802
803                 // Skip `::{{constructor}}` on tuple/unit structs.
804                 match disambiguated_data.data {
805                     DefPathData::Ctor => return Ok(path),
806                     _ => {}
807                 }
808
809                 path.push(disambiguated_data.data.as_symbol());
810                 Ok(path)
811             }
812
813             fn path_generic_args(
814                 self,
815                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
816                 _args: &[GenericArg<'tcx>],
817             ) -> Result<Self::Path, Self::Error> {
818                 print_prefix(self)
819             }
820         }
821
822         AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
823     }
824 }
825
826 impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
827     type Ty = Ty<'tcx>;
828     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
829
830     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
831         self.tcx.layout_of(self.param_env.and(ty))
832     }
833 }
834
835 impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> LateContextAndPass<'a, 'tcx, T> {
836     /// Merge the lints specified by any lint attributes into the
837     /// current lint context, call the provided function, then reset the
838     /// lints in effect to their previous state.
839     fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &'tcx [ast::Attribute], f: F)
840     where
841         F: FnOnce(&mut Self),
842     {
843         let prev = self.context.last_node_with_lint_attrs;
844         self.context.last_node_with_lint_attrs = id;
845         self.enter_attrs(attrs);
846         f(self);
847         self.exit_attrs(attrs);
848         self.context.last_node_with_lint_attrs = prev;
849     }
850
851     fn with_param_env<F>(&mut self, id: hir::HirId, f: F)
852     where
853         F: FnOnce(&mut Self),
854     {
855         let old_param_env = self.context.param_env;
856         self.context.param_env =
857             self.context.tcx.param_env(self.context.tcx.hir().local_def_id(id));
858         f(self);
859         self.context.param_env = old_param_env;
860     }
861
862     fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) {
863         lint_callback!(self, check_mod, m, s, n);
864         hir_visit::walk_mod(self, m, n);
865         lint_callback!(self, check_mod_post, m, s, n);
866     }
867
868     fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
869         debug!("late context: enter_attrs({:?})", attrs);
870         lint_callback!(self, enter_lint_attrs, attrs);
871     }
872
873     fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
874         debug!("late context: exit_attrs({:?})", attrs);
875         lint_callback!(self, exit_lint_attrs, attrs);
876     }
877 }
878
879 impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx>
880     for LateContextAndPass<'a, 'tcx, T>
881 {
882     /// Because lints are scoped lexically, we want to walk nested
883     /// items in the context of the outer item, so enable
884     /// deep-walking.
885     fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
886         hir_visit::NestedVisitorMap::All(&self.context.tcx.hir())
887     }
888
889     fn visit_nested_body(&mut self, body: hir::BodyId) {
890         let old_tables = self.context.tables;
891         self.context.tables = self.context.tcx.body_tables(body);
892         let body = self.context.tcx.hir().body(body);
893         self.visit_body(body);
894         self.context.tables = old_tables;
895     }
896
897     fn visit_param(&mut self, param: &'tcx hir::Param) {
898         self.with_lint_attrs(param.hir_id, &param.attrs, |cx| {
899             lint_callback!(cx, check_param, param);
900             hir_visit::walk_param(cx, param);
901         });
902     }
903
904     fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
905         lint_callback!(self, check_body, body);
906         hir_visit::walk_body(self, body);
907         lint_callback!(self, check_body_post, body);
908     }
909
910     fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
911         let generics = self.context.generics.take();
912         self.context.generics = it.kind.generics();
913         self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
914             cx.with_param_env(it.hir_id, |cx| {
915                 lint_callback!(cx, check_item, it);
916                 hir_visit::walk_item(cx, it);
917                 lint_callback!(cx, check_item_post, it);
918             });
919         });
920         self.context.generics = generics;
921     }
922
923     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
924         self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
925             cx.with_param_env(it.hir_id, |cx| {
926                 lint_callback!(cx, check_foreign_item, it);
927                 hir_visit::walk_foreign_item(cx, it);
928                 lint_callback!(cx, check_foreign_item_post, it);
929             });
930         })
931     }
932
933     fn visit_pat(&mut self, p: &'tcx hir::Pat) {
934         lint_callback!(self, check_pat, p);
935         hir_visit::walk_pat(self, p);
936     }
937
938     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
939         self.with_lint_attrs(e.hir_id, &e.attrs, |cx| {
940             lint_callback!(cx, check_expr, e);
941             hir_visit::walk_expr(cx, e);
942             lint_callback!(cx, check_expr_post, e);
943         })
944     }
945
946     fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
947         // statement attributes are actually just attributes on one of
948         // - item
949         // - local
950         // - expression
951         // so we keep track of lint levels there
952         lint_callback!(self, check_stmt, s);
953         hir_visit::walk_stmt(self, s);
954     }
955
956     fn visit_fn(
957         &mut self,
958         fk: hir_visit::FnKind<'tcx>,
959         decl: &'tcx hir::FnDecl,
960         body_id: hir::BodyId,
961         span: Span,
962         id: hir::HirId,
963     ) {
964         // Wrap in tables here, not just in visit_nested_body,
965         // in order for `check_fn` to be able to use them.
966         let old_tables = self.context.tables;
967         self.context.tables = self.context.tcx.body_tables(body_id);
968         let body = self.context.tcx.hir().body(body_id);
969         lint_callback!(self, check_fn, fk, decl, body, span, id);
970         hir_visit::walk_fn(self, fk, decl, body_id, span, id);
971         lint_callback!(self, check_fn_post, fk, decl, body, span, id);
972         self.context.tables = old_tables;
973     }
974
975     fn visit_variant_data(
976         &mut self,
977         s: &'tcx hir::VariantData<'tcx>,
978         _: ast::Name,
979         _: &'tcx hir::Generics,
980         _: hir::HirId,
981         _: Span,
982     ) {
983         lint_callback!(self, check_struct_def, s);
984         hir_visit::walk_struct_def(self, s);
985         lint_callback!(self, check_struct_def_post, s);
986     }
987
988     fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
989         self.with_lint_attrs(s.hir_id, &s.attrs, |cx| {
990             lint_callback!(cx, check_struct_field, s);
991             hir_visit::walk_struct_field(cx, s);
992         })
993     }
994
995     fn visit_variant(
996         &mut self,
997         v: &'tcx hir::Variant<'tcx>,
998         g: &'tcx hir::Generics,
999         item_id: hir::HirId,
1000     ) {
1001         self.with_lint_attrs(v.id, &v.attrs, |cx| {
1002             lint_callback!(cx, check_variant, v);
1003             hir_visit::walk_variant(cx, v, g, item_id);
1004             lint_callback!(cx, check_variant_post, v);
1005         })
1006     }
1007
1008     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1009         lint_callback!(self, check_ty, t);
1010         hir_visit::walk_ty(self, t);
1011     }
1012
1013     fn visit_name(&mut self, sp: Span, name: ast::Name) {
1014         lint_callback!(self, check_name, sp, name);
1015     }
1016
1017     fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) {
1018         if !self.context.only_module {
1019             self.process_mod(m, s, n);
1020         }
1021     }
1022
1023     fn visit_local(&mut self, l: &'tcx hir::Local) {
1024         self.with_lint_attrs(l.hir_id, &l.attrs, |cx| {
1025             lint_callback!(cx, check_local, l);
1026             hir_visit::walk_local(cx, l);
1027         })
1028     }
1029
1030     fn visit_block(&mut self, b: &'tcx hir::Block) {
1031         lint_callback!(self, check_block, b);
1032         hir_visit::walk_block(self, b);
1033         lint_callback!(self, check_block_post, b);
1034     }
1035
1036     fn visit_arm(&mut self, a: &'tcx hir::Arm) {
1037         lint_callback!(self, check_arm, a);
1038         hir_visit::walk_arm(self, a);
1039     }
1040
1041     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam) {
1042         lint_callback!(self, check_generic_param, p);
1043         hir_visit::walk_generic_param(self, p);
1044     }
1045
1046     fn visit_generics(&mut self, g: &'tcx hir::Generics) {
1047         lint_callback!(self, check_generics, g);
1048         hir_visit::walk_generics(self, g);
1049     }
1050
1051     fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate) {
1052         lint_callback!(self, check_where_predicate, p);
1053         hir_visit::walk_where_predicate(self, p);
1054     }
1055
1056     fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef, m: hir::TraitBoundModifier) {
1057         lint_callback!(self, check_poly_trait_ref, t, m);
1058         hir_visit::walk_poly_trait_ref(self, t, m);
1059     }
1060
1061     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1062         let generics = self.context.generics.take();
1063         self.context.generics = Some(&trait_item.generics);
1064         self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |cx| {
1065             cx.with_param_env(trait_item.hir_id, |cx| {
1066                 lint_callback!(cx, check_trait_item, trait_item);
1067                 hir_visit::walk_trait_item(cx, trait_item);
1068                 lint_callback!(cx, check_trait_item_post, trait_item);
1069             });
1070         });
1071         self.context.generics = generics;
1072     }
1073
1074     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1075         let generics = self.context.generics.take();
1076         self.context.generics = Some(&impl_item.generics);
1077         self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |cx| {
1078             cx.with_param_env(impl_item.hir_id, |cx| {
1079                 lint_callback!(cx, check_impl_item, impl_item);
1080                 hir_visit::walk_impl_item(cx, impl_item);
1081                 lint_callback!(cx, check_impl_item_post, impl_item);
1082             });
1083         });
1084         self.context.generics = generics;
1085     }
1086
1087     fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1088         lint_callback!(self, check_lifetime, lt);
1089         hir_visit::walk_lifetime(self, lt);
1090     }
1091
1092     fn visit_path(&mut self, p: &'tcx hir::Path, id: hir::HirId) {
1093         lint_callback!(self, check_path, p, id);
1094         hir_visit::walk_path(self, p);
1095     }
1096
1097     fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
1098         lint_callback!(self, check_attribute, attr);
1099     }
1100 }
1101
1102 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
1103     fn visit_param(&mut self, param: &'a ast::Param) {
1104         self.with_lint_attrs(param.id, &param.attrs, |cx| {
1105             run_early_pass!(cx, check_param, param);
1106             ast_visit::walk_param(cx, param);
1107         });
1108     }
1109
1110     fn visit_item(&mut self, it: &'a ast::Item) {
1111         self.with_lint_attrs(it.id, &it.attrs, |cx| {
1112             run_early_pass!(cx, check_item, it);
1113             ast_visit::walk_item(cx, it);
1114             run_early_pass!(cx, check_item_post, it);
1115         })
1116     }
1117
1118     fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
1119         self.with_lint_attrs(it.id, &it.attrs, |cx| {
1120             run_early_pass!(cx, check_foreign_item, it);
1121             ast_visit::walk_foreign_item(cx, it);
1122             run_early_pass!(cx, check_foreign_item_post, it);
1123         })
1124     }
1125
1126     fn visit_pat(&mut self, p: &'a ast::Pat) {
1127         run_early_pass!(self, check_pat, p);
1128         self.check_id(p.id);
1129         ast_visit::walk_pat(self, p);
1130         run_early_pass!(self, check_pat_post, p);
1131     }
1132
1133     fn visit_expr(&mut self, e: &'a ast::Expr) {
1134         self.with_lint_attrs(e.id, &e.attrs, |cx| {
1135             run_early_pass!(cx, check_expr, e);
1136             ast_visit::walk_expr(cx, e);
1137         })
1138     }
1139
1140     fn visit_stmt(&mut self, s: &'a ast::Stmt) {
1141         run_early_pass!(self, check_stmt, s);
1142         self.check_id(s.id);
1143         ast_visit::walk_stmt(self, s);
1144     }
1145
1146     fn visit_fn(
1147         &mut self,
1148         fk: ast_visit::FnKind<'a>,
1149         decl: &'a ast::FnDecl,
1150         span: Span,
1151         id: ast::NodeId,
1152     ) {
1153         run_early_pass!(self, check_fn, fk, decl, span, id);
1154         self.check_id(id);
1155         ast_visit::walk_fn(self, fk, decl, span);
1156         run_early_pass!(self, check_fn_post, fk, decl, span, id);
1157     }
1158
1159     fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
1160         run_early_pass!(self, check_struct_def, s);
1161         if let Some(ctor_hir_id) = s.ctor_id() {
1162             self.check_id(ctor_hir_id);
1163         }
1164         ast_visit::walk_struct_def(self, s);
1165         run_early_pass!(self, check_struct_def_post, s);
1166     }
1167
1168     fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1169         self.with_lint_attrs(s.id, &s.attrs, |cx| {
1170             run_early_pass!(cx, check_struct_field, s);
1171             ast_visit::walk_struct_field(cx, s);
1172         })
1173     }
1174
1175     fn visit_variant(&mut self, v: &'a ast::Variant) {
1176         self.with_lint_attrs(v.id, &v.attrs, |cx| {
1177             run_early_pass!(cx, check_variant, v);
1178             ast_visit::walk_variant(cx, v);
1179             run_early_pass!(cx, check_variant_post, v);
1180         })
1181     }
1182
1183     fn visit_ty(&mut self, t: &'a ast::Ty) {
1184         run_early_pass!(self, check_ty, t);
1185         self.check_id(t.id);
1186         ast_visit::walk_ty(self, t);
1187     }
1188
1189     fn visit_ident(&mut self, ident: ast::Ident) {
1190         run_early_pass!(self, check_ident, ident);
1191     }
1192
1193     fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
1194         run_early_pass!(self, check_mod, m, s, n);
1195         self.check_id(n);
1196         ast_visit::walk_mod(self, m);
1197         run_early_pass!(self, check_mod_post, m, s, n);
1198     }
1199
1200     fn visit_local(&mut self, l: &'a ast::Local) {
1201         self.with_lint_attrs(l.id, &l.attrs, |cx| {
1202             run_early_pass!(cx, check_local, l);
1203             ast_visit::walk_local(cx, l);
1204         })
1205     }
1206
1207     fn visit_block(&mut self, b: &'a ast::Block) {
1208         run_early_pass!(self, check_block, b);
1209         self.check_id(b.id);
1210         ast_visit::walk_block(self, b);
1211         run_early_pass!(self, check_block_post, b);
1212     }
1213
1214     fn visit_arm(&mut self, a: &'a ast::Arm) {
1215         run_early_pass!(self, check_arm, a);
1216         ast_visit::walk_arm(self, a);
1217     }
1218
1219     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1220         run_early_pass!(self, check_expr_post, e);
1221     }
1222
1223     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
1224         run_early_pass!(self, check_generic_param, param);
1225         ast_visit::walk_generic_param(self, param);
1226     }
1227
1228     fn visit_generics(&mut self, g: &'a ast::Generics) {
1229         run_early_pass!(self, check_generics, g);
1230         ast_visit::walk_generics(self, g);
1231     }
1232
1233     fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
1234         run_early_pass!(self, check_where_predicate, p);
1235         ast_visit::walk_where_predicate(self, p);
1236     }
1237
1238     fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
1239         run_early_pass!(self, check_poly_trait_ref, t, m);
1240         ast_visit::walk_poly_trait_ref(self, t, m);
1241     }
1242
1243     fn visit_trait_item(&mut self, trait_item: &'a ast::AssocItem) {
1244         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
1245             run_early_pass!(cx, check_trait_item, trait_item);
1246             ast_visit::walk_trait_item(cx, trait_item);
1247             run_early_pass!(cx, check_trait_item_post, trait_item);
1248         });
1249     }
1250
1251     fn visit_impl_item(&mut self, impl_item: &'a ast::AssocItem) {
1252         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
1253             run_early_pass!(cx, check_impl_item, impl_item);
1254             ast_visit::walk_impl_item(cx, impl_item);
1255             run_early_pass!(cx, check_impl_item_post, impl_item);
1256         });
1257     }
1258
1259     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1260         run_early_pass!(self, check_lifetime, lt);
1261         self.check_id(lt.id);
1262     }
1263
1264     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1265         run_early_pass!(self, check_path, p, id);
1266         self.check_id(id);
1267         ast_visit::walk_path(self, p);
1268     }
1269
1270     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1271         run_early_pass!(self, check_attribute, attr);
1272     }
1273
1274     fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
1275         run_early_pass!(self, check_mac_def, mac, id);
1276         self.check_id(id);
1277     }
1278
1279     fn visit_mac(&mut self, mac: &'a ast::Mac) {
1280         // FIXME(#54110): So, this setup isn't really right. I think
1281         // that (a) the libsyntax visitor ought to be doing this as
1282         // part of `walk_mac`, and (b) we should be calling
1283         // `visit_path`, *but* that would require a `NodeId`, and I
1284         // want to get #53686 fixed quickly. -nmatsakis
1285         ast_visit::walk_path(self, &mac.path);
1286
1287         run_early_pass!(self, check_mac, mac);
1288     }
1289 }
1290
1291 struct LateLintPassObjects<'a> {
1292     lints: &'a mut [LateLintPassObject],
1293 }
1294
1295 #[allow(rustc::lint_pass_impl_without_macro)]
1296 impl LintPass for LateLintPassObjects<'_> {
1297     fn name(&self) -> &'static str {
1298         panic!()
1299     }
1300 }
1301
1302 macro_rules! expand_late_lint_pass_impl_methods {
1303     ([$a:tt, $hir:tt], [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
1304         $(fn $name(&mut self, context: &LateContext<$a, $hir>, $($param: $arg),*) {
1305             for obj in self.lints.iter_mut() {
1306                 obj.$name(context, $($param),*);
1307             }
1308         })*
1309     )
1310 }
1311
1312 macro_rules! late_lint_pass_impl {
1313     ([], [$hir:tt], $methods:tt) => (
1314         impl LateLintPass<'a, $hir> for LateLintPassObjects<'_> {
1315             expand_late_lint_pass_impl_methods!(['a, $hir], $methods);
1316         }
1317     )
1318 }
1319
1320 late_lint_methods!(late_lint_pass_impl, [], ['tcx]);
1321
1322 fn late_lint_mod_pass<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
1323     tcx: TyCtxt<'tcx>,
1324     module_def_id: DefId,
1325     pass: T,
1326 ) {
1327     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1328
1329     let context = LateContext {
1330         tcx,
1331         tables: &ty::TypeckTables::empty(None),
1332         param_env: ty::ParamEnv::empty(),
1333         access_levels,
1334         lint_store: &tcx.lint_store,
1335         last_node_with_lint_attrs: tcx.hir().as_local_hir_id(module_def_id).unwrap(),
1336         generics: None,
1337         only_module: true,
1338     };
1339
1340     let mut cx = LateContextAndPass { context, pass };
1341
1342     let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
1343     cx.process_mod(module, span, hir_id);
1344
1345     // Visit the crate attributes
1346     if hir_id == hir::CRATE_HIR_ID {
1347         walk_list!(cx, visit_attribute, tcx.hir().attrs(hir::CRATE_HIR_ID));
1348     }
1349 }
1350
1351 pub fn late_lint_mod<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
1352     tcx: TyCtxt<'tcx>,
1353     module_def_id: DefId,
1354     builtin_lints: T,
1355 ) {
1356     if tcx.sess.opts.debugging_opts.no_interleave_lints {
1357         // These passes runs in late_lint_crate with -Z no_interleave_lints
1358         return;
1359     }
1360
1361     late_lint_mod_pass(tcx, module_def_id, builtin_lints);
1362
1363     let mut passes: Vec<_> =
1364         tcx.lint_store.late_module_passes.iter().map(|pass| (pass)()).collect();
1365
1366     if !passes.is_empty() {
1367         late_lint_mod_pass(tcx, module_def_id, LateLintPassObjects { lints: &mut passes[..] });
1368     }
1369 }
1370
1371 fn late_lint_pass_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(tcx: TyCtxt<'tcx>, pass: T) {
1372     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1373
1374     let krate = tcx.hir().krate();
1375
1376     let context = LateContext {
1377         tcx,
1378         tables: &ty::TypeckTables::empty(None),
1379         param_env: ty::ParamEnv::empty(),
1380         access_levels,
1381         lint_store: &tcx.lint_store,
1382         last_node_with_lint_attrs: hir::CRATE_HIR_ID,
1383         generics: None,
1384         only_module: false,
1385     };
1386
1387     let mut cx = LateContextAndPass { context, pass };
1388
1389     // Visit the whole crate.
1390     cx.with_lint_attrs(hir::CRATE_HIR_ID, &krate.attrs, |cx| {
1391         // since the root module isn't visited as an item (because it isn't an
1392         // item), warn for it here.
1393         lint_callback!(cx, check_crate, krate);
1394
1395         hir_visit::walk_crate(cx, krate);
1396
1397         lint_callback!(cx, check_crate_post, krate);
1398     })
1399 }
1400
1401 fn late_lint_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(tcx: TyCtxt<'tcx>, builtin_lints: T) {
1402     let mut passes = tcx.lint_store.late_passes.iter().map(|p| (p)()).collect::<Vec<_>>();
1403
1404     if !tcx.sess.opts.debugging_opts.no_interleave_lints {
1405         if !passes.is_empty() {
1406             late_lint_pass_crate(tcx, LateLintPassObjects { lints: &mut passes[..] });
1407         }
1408
1409         late_lint_pass_crate(tcx, builtin_lints);
1410     } else {
1411         for pass in &mut passes {
1412             time(tcx.sess, &format!("running late lint: {}", pass.name()), || {
1413                 late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) });
1414             });
1415         }
1416
1417         let mut passes: Vec<_> =
1418             tcx.lint_store.late_module_passes.iter().map(|pass| (pass)()).collect();
1419
1420         for pass in &mut passes {
1421             time(tcx.sess, &format!("running late module lint: {}", pass.name()), || {
1422                 late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) });
1423             });
1424         }
1425     }
1426 }
1427
1428 /// Performs lint checking on a crate.
1429 pub fn check_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
1430     tcx: TyCtxt<'tcx>,
1431     builtin_lints: impl FnOnce() -> T + Send,
1432 ) {
1433     join(
1434         || {
1435             time(tcx.sess, "crate lints", || {
1436                 // Run whole crate non-incremental lints
1437                 late_lint_crate(tcx, builtin_lints());
1438             });
1439         },
1440         || {
1441             time(tcx.sess, "module lints", || {
1442                 // Run per-module lints
1443                 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
1444                     tcx.ensure().lint_mod(tcx.hir().local_def_id(module));
1445                 });
1446             });
1447         },
1448     );
1449 }
1450
1451 struct EarlyLintPassObjects<'a> {
1452     lints: &'a mut [EarlyLintPassObject],
1453 }
1454
1455 #[allow(rustc::lint_pass_impl_without_macro)]
1456 impl LintPass for EarlyLintPassObjects<'_> {
1457     fn name(&self) -> &'static str {
1458         panic!()
1459     }
1460 }
1461
1462 macro_rules! expand_early_lint_pass_impl_methods {
1463     ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
1464         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
1465             for obj in self.lints.iter_mut() {
1466                 obj.$name(context, $($param),*);
1467             }
1468         })*
1469     )
1470 }
1471
1472 macro_rules! early_lint_pass_impl {
1473     ([], [$($methods:tt)*]) => (
1474         impl EarlyLintPass for EarlyLintPassObjects<'_> {
1475             expand_early_lint_pass_impl_methods!([$($methods)*]);
1476         }
1477     )
1478 }
1479
1480 early_lint_methods!(early_lint_pass_impl, []);
1481
1482 fn early_lint_crate<T: EarlyLintPass>(
1483     sess: &Session,
1484     lint_store: &LintStore,
1485     krate: &ast::Crate,
1486     pass: T,
1487     buffered: LintBuffer,
1488     warn_about_weird_lints: bool,
1489 ) -> LintBuffer {
1490     let mut cx = EarlyContextAndPass {
1491         context: EarlyContext::new(sess, lint_store, krate, buffered, warn_about_weird_lints),
1492         pass,
1493     };
1494
1495     // Visit the whole crate.
1496     cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1497         // since the root module isn't visited as an item (because it isn't an
1498         // item), warn for it here.
1499         run_early_pass!(cx, check_crate, krate);
1500
1501         ast_visit::walk_crate(cx, krate);
1502
1503         run_early_pass!(cx, check_crate_post, krate);
1504     });
1505     cx.context.buffered
1506 }
1507
1508 pub fn check_ast_crate<T: EarlyLintPass>(
1509     sess: &Session,
1510     lint_store: &LintStore,
1511     krate: &ast::Crate,
1512     pre_expansion: bool,
1513     lint_buffer: Option<LintBuffer>,
1514     builtin_lints: T,
1515 ) {
1516     let mut passes: Vec<_> = if pre_expansion {
1517         lint_store.pre_expansion_passes.iter().map(|p| (p)()).collect()
1518     } else {
1519         lint_store.early_passes.iter().map(|p| (p)()).collect()
1520     };
1521     let mut buffered = lint_buffer.unwrap_or_default();
1522
1523     if !sess.opts.debugging_opts.no_interleave_lints {
1524         buffered =
1525             early_lint_crate(sess, lint_store, krate, builtin_lints, buffered, pre_expansion);
1526
1527         if !passes.is_empty() {
1528             buffered = early_lint_crate(
1529                 sess,
1530                 lint_store,
1531                 krate,
1532                 EarlyLintPassObjects { lints: &mut passes[..] },
1533                 buffered,
1534                 pre_expansion,
1535             );
1536         }
1537     } else {
1538         for pass in &mut passes {
1539             buffered = time(sess, &format!("running lint: {}", pass.name()), || {
1540                 early_lint_crate(
1541                     sess,
1542                     lint_store,
1543                     krate,
1544                     EarlyLintPassObjects { lints: slice::from_mut(pass) },
1545                     buffered,
1546                     pre_expansion,
1547                 )
1548             });
1549         }
1550     }
1551
1552     // All of the buffered lints should have been emitted at this point.
1553     // If not, that means that we somehow buffered a lint for a node id
1554     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
1555     //
1556     // Rustdoc runs everybody-loops before the early lints and removes
1557     // function bodies, so it's totally possible for linted
1558     // node ids to not exist (e.g., macros defined within functions for the
1559     // unused_macro lint) anymore. So we only run this check
1560     // when we're not in rustdoc mode. (see issue #47639)
1561     if !sess.opts.actually_rustdoc {
1562         for (_id, lints) in buffered.map {
1563             for early_lint in lints {
1564                 sess.delay_span_bug(early_lint.span, "failed to process buffered lint here");
1565             }
1566         }
1567     }
1568 }