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