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