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