]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/context.rs
Rollup merge of #58273 - taiki-e:rename-dependency, r=matthewjasper
[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_ast_node_with_lint_attrs: ast::NodeId,
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
568 pub trait LintContext<'tcx>: Sized {
569     type PassObject: LintPassObject;
570
571     fn sess(&self) -> &Session;
572     fn lints(&self) -> &LintStore;
573     fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject>;
574     fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject>;
575
576     fn lookup_and_emit<S: Into<MultiSpan>>(&self,
577                                            lint: &'static Lint,
578                                            span: Option<S>,
579                                            msg: &str) {
580         self.lookup(lint, span, msg).emit();
581     }
582
583     fn lookup_and_emit_with_diagnostics<S: Into<MultiSpan>>(&self,
584                                                             lint: &'static Lint,
585                                                             span: Option<S>,
586                                                             msg: &str,
587                                                             diagnostic: BuiltinLintDiagnostics) {
588         let mut db = self.lookup(lint, span, msg);
589         diagnostic.run(self.sess(), &mut db);
590         db.emit();
591     }
592
593     fn lookup<S: Into<MultiSpan>>(&self,
594                                   lint: &'static Lint,
595                                   span: Option<S>,
596                                   msg: &str)
597                                   -> DiagnosticBuilder<'_>;
598
599     /// Emit a lint at the appropriate level, for a particular span.
600     fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
601         self.lookup_and_emit(lint, Some(span), msg);
602     }
603
604     fn struct_span_lint<S: Into<MultiSpan>>(&self,
605                                             lint: &'static Lint,
606                                             span: S,
607                                             msg: &str)
608                                             -> DiagnosticBuilder<'_> {
609         self.lookup(lint, Some(span), msg)
610     }
611
612     /// Emit a lint and note at the appropriate level, for a particular span.
613     fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
614                       note_span: Span, note: &str) {
615         let mut err = self.lookup(lint, Some(span), msg);
616         if note_span == span {
617             err.note(note);
618         } else {
619             err.span_note(note_span, note);
620         }
621         err.emit();
622     }
623
624     /// Emit a lint and help at the appropriate level, for a particular span.
625     fn span_lint_help(&self, lint: &'static Lint, span: Span,
626                       msg: &str, help: &str) {
627         let mut err = self.lookup(lint, Some(span), msg);
628         self.span_lint(lint, span, msg);
629         err.span_help(span, help);
630         err.emit();
631     }
632
633     /// Emit a lint at the appropriate level, with no associated span.
634     fn lint(&self, lint: &'static Lint, msg: &str) {
635         self.lookup_and_emit(lint, None as Option<Span>, msg);
636     }
637 }
638
639
640 impl<'a> EarlyContext<'a> {
641     fn new(
642         sess: &'a Session,
643         krate: &'a ast::Crate,
644         buffered: LintBuffer,
645     ) -> EarlyContext<'a> {
646         EarlyContext {
647             sess,
648             krate,
649             lint_sess: LintSession {
650                 lints: sess.lint_store.borrow(),
651                 passes: None,
652             },
653             builder: LintLevelSets::builder(sess),
654             buffered,
655         }
656     }
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_sess.lints
713     }
714
715     fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject> {
716         &self.lint_sess
717     }
718
719     fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject> {
720         &mut self.lint_sess
721     }
722
723     fn lookup<S: Into<MultiSpan>>(&self,
724                                   lint: &'static Lint,
725                                   span: Option<S>,
726                                   msg: &str)
727                                   -> DiagnosticBuilder<'_> {
728         let id = self.last_ast_node_with_lint_attrs;
729         match span {
730             Some(s) => self.tcx.struct_span_lint_node(lint, id, s, msg),
731             None => self.tcx.struct_lint_node(lint, id, msg),
732         }
733     }
734 }
735
736 impl<'a> LintContext<'a> for EarlyContext<'a> {
737     type PassObject = EarlyLintPassObject;
738
739     /// Gets the overall compiler `Session` object.
740     fn sess(&self) -> &Session {
741         &self.sess
742     }
743
744     fn lints(&self) -> &LintStore {
745         &*self.lint_sess.lints
746     }
747
748     fn lint_sess(&self) -> &LintSession<'a, Self::PassObject> {
749         &self.lint_sess
750     }
751
752     fn lint_sess_mut(&mut self) -> &mut LintSession<'a, Self::PassObject> {
753         &mut self.lint_sess
754     }
755
756     fn lookup<S: Into<MultiSpan>>(&self,
757                                   lint: &'static Lint,
758                                   span: Option<S>,
759                                   msg: &str)
760                                   -> DiagnosticBuilder<'_> {
761         self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
762     }
763 }
764
765 impl<'a, 'tcx> LateContext<'a, 'tcx> {
766     /// Merge the lints specified by any lint attributes into the
767     /// current lint context, call the provided function, then reset the
768     /// lints in effect to their previous state.
769     fn with_lint_attrs<F>(&mut self,
770                           id: ast::NodeId,
771                           attrs: &'tcx [ast::Attribute],
772                           f: F)
773         where F: FnOnce(&mut Self)
774     {
775         let prev = self.last_ast_node_with_lint_attrs;
776         self.last_ast_node_with_lint_attrs = id;
777         self.enter_attrs(attrs);
778         f(self);
779         self.exit_attrs(attrs);
780         self.last_ast_node_with_lint_attrs = prev;
781     }
782
783     fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
784         debug!("late context: enter_attrs({:?})", attrs);
785         run_lints!(self, enter_lint_attrs, attrs);
786     }
787
788     fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
789         debug!("late context: exit_attrs({:?})", attrs);
790         run_lints!(self, exit_lint_attrs, attrs);
791     }
792
793     fn with_param_env<F>(&mut self, id: ast::NodeId, f: F)
794         where F: FnOnce(&mut Self),
795     {
796         let old_param_env = self.param_env;
797         self.param_env = self.tcx.param_env(self.tcx.hir().local_def_id(id));
798         f(self);
799         self.param_env = old_param_env;
800     }
801     pub fn current_lint_root(&self) -> ast::NodeId {
802         self.last_ast_node_with_lint_attrs
803     }
804 }
805
806 impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
807     type Ty = Ty<'tcx>;
808     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
809
810     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
811         self.tcx.layout_of(self.param_env.and(ty))
812     }
813 }
814
815 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
816     /// Because lints are scoped lexically, we want to walk nested
817     /// items in the context of the outer item, so enable
818     /// deep-walking.
819     fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
820         hir_visit::NestedVisitorMap::All(&self.tcx.hir())
821     }
822
823     fn visit_nested_body(&mut self, body: hir::BodyId) {
824         let old_tables = self.tables;
825         self.tables = self.tcx.body_tables(body);
826         let body = self.tcx.hir().body(body);
827         self.visit_body(body);
828         self.tables = old_tables;
829     }
830
831     fn visit_body(&mut self, body: &'tcx hir::Body) {
832         run_lints!(self, check_body, body);
833         hir_visit::walk_body(self, body);
834         run_lints!(self, check_body_post, body);
835     }
836
837     fn visit_item(&mut self, it: &'tcx hir::Item) {
838         let generics = self.generics.take();
839         self.generics = it.node.generics();
840         self.with_lint_attrs(it.id, &it.attrs, |cx| {
841             cx.with_param_env(it.id, |cx| {
842                 run_lints!(cx, check_item, it);
843                 hir_visit::walk_item(cx, it);
844                 run_lints!(cx, check_item_post, it);
845             });
846         });
847         self.generics = generics;
848     }
849
850     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
851         self.with_lint_attrs(it.id, &it.attrs, |cx| {
852             cx.with_param_env(it.id, |cx| {
853                 run_lints!(cx, check_foreign_item, it);
854                 hir_visit::walk_foreign_item(cx, it);
855                 run_lints!(cx, check_foreign_item_post, it);
856             });
857         })
858     }
859
860     fn visit_pat(&mut self, p: &'tcx hir::Pat) {
861         run_lints!(self, check_pat, p);
862         hir_visit::walk_pat(self, p);
863     }
864
865     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
866         self.with_lint_attrs(e.id, &e.attrs, |cx| {
867             run_lints!(cx, check_expr, e);
868             hir_visit::walk_expr(cx, e);
869             run_lints!(cx, check_expr_post, e);
870         })
871     }
872
873     fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
874         // statement attributes are actually just attributes on one of
875         // - item
876         // - local
877         // - expression
878         // so we keep track of lint levels there
879         run_lints!(self, check_stmt, s);
880         hir_visit::walk_stmt(self, s);
881     }
882
883     fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
884                 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
885         // Wrap in tables here, not just in visit_nested_body,
886         // in order for `check_fn` to be able to use them.
887         let old_tables = self.tables;
888         self.tables = self.tcx.body_tables(body_id);
889         let body = self.tcx.hir().body(body_id);
890         run_lints!(self, check_fn, fk, decl, body, span, id);
891         hir_visit::walk_fn(self, fk, decl, body_id, span, id);
892         run_lints!(self, check_fn_post, fk, decl, body, span, id);
893         self.tables = old_tables;
894     }
895
896     fn visit_variant_data(&mut self,
897                         s: &'tcx hir::VariantData,
898                         name: ast::Name,
899                         g: &'tcx hir::Generics,
900                         item_id: ast::NodeId,
901                         _: Span) {
902         run_lints!(self, check_struct_def, s, name, g, item_id);
903         hir_visit::walk_struct_def(self, s);
904         run_lints!(self, check_struct_def_post, s, name, g, item_id);
905     }
906
907     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
908         self.with_lint_attrs(s.id, &s.attrs, |cx| {
909             run_lints!(cx, check_struct_field, s);
910             hir_visit::walk_struct_field(cx, s);
911         })
912     }
913
914     fn visit_variant(&mut self,
915                      v: &'tcx hir::Variant,
916                      g: &'tcx hir::Generics,
917                      item_id: ast::NodeId) {
918         self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |cx| {
919             run_lints!(cx, check_variant, v, g);
920             hir_visit::walk_variant(cx, v, g, item_id);
921             run_lints!(cx, check_variant_post, v, g);
922         })
923     }
924
925     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
926         run_lints!(self, check_ty, t);
927         hir_visit::walk_ty(self, t);
928     }
929
930     fn visit_name(&mut self, sp: Span, name: ast::Name) {
931         run_lints!(self, check_name, sp, name);
932     }
933
934     fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
935         run_lints!(self, check_mod, m, s, n);
936         hir_visit::walk_mod(self, m, n);
937         run_lints!(self, check_mod_post, m, s, n);
938     }
939
940     fn visit_local(&mut self, l: &'tcx hir::Local) {
941         self.with_lint_attrs(l.id, &l.attrs, |cx| {
942             run_lints!(cx, check_local, l);
943             hir_visit::walk_local(cx, l);
944         })
945     }
946
947     fn visit_block(&mut self, b: &'tcx hir::Block) {
948         run_lints!(self, check_block, b);
949         hir_visit::walk_block(self, b);
950         run_lints!(self, check_block_post, b);
951     }
952
953     fn visit_arm(&mut self, a: &'tcx hir::Arm) {
954         run_lints!(self, check_arm, a);
955         hir_visit::walk_arm(self, a);
956     }
957
958     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam) {
959         run_lints!(self, check_generic_param, p);
960         hir_visit::walk_generic_param(self, p);
961     }
962
963     fn visit_generics(&mut self, g: &'tcx hir::Generics) {
964         run_lints!(self, check_generics, g);
965         hir_visit::walk_generics(self, g);
966     }
967
968     fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate) {
969         run_lints!(self, check_where_predicate, p);
970         hir_visit::walk_where_predicate(self, p);
971     }
972
973     fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef,
974                             m: hir::TraitBoundModifier) {
975         run_lints!(self, check_poly_trait_ref, t, m);
976         hir_visit::walk_poly_trait_ref(self, t, m);
977     }
978
979     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
980         let generics = self.generics.take();
981         self.generics = Some(&trait_item.generics);
982         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
983             cx.with_param_env(trait_item.id, |cx| {
984                 run_lints!(cx, check_trait_item, trait_item);
985                 hir_visit::walk_trait_item(cx, trait_item);
986                 run_lints!(cx, check_trait_item_post, trait_item);
987             });
988         });
989         self.generics = generics;
990     }
991
992     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
993         let generics = self.generics.take();
994         self.generics = Some(&impl_item.generics);
995         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
996             cx.with_param_env(impl_item.id, |cx| {
997                 run_lints!(cx, check_impl_item, impl_item);
998                 hir_visit::walk_impl_item(cx, impl_item);
999                 run_lints!(cx, check_impl_item_post, impl_item);
1000             });
1001         });
1002         self.generics = generics;
1003     }
1004
1005     fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1006         run_lints!(self, check_lifetime, lt);
1007         hir_visit::walk_lifetime(self, lt);
1008     }
1009
1010     fn visit_path(&mut self, p: &'tcx hir::Path, id: hir::HirId) {
1011         run_lints!(self, check_path, p, id);
1012         hir_visit::walk_path(self, p);
1013     }
1014
1015     fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
1016         run_lints!(self, check_attribute, attr);
1017     }
1018 }
1019
1020 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
1021     fn visit_item(&mut self, it: &'a ast::Item) {
1022         self.with_lint_attrs(it.id, &it.attrs, |cx| {
1023             run_early_pass!(cx, check_item, it);
1024             ast_visit::walk_item(cx, it);
1025             run_early_pass!(cx, check_item_post, it);
1026         })
1027     }
1028
1029     fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
1030         self.with_lint_attrs(it.id, &it.attrs, |cx| {
1031             run_early_pass!(cx, check_foreign_item, it);
1032             ast_visit::walk_foreign_item(cx, it);
1033             run_early_pass!(cx, check_foreign_item_post, it);
1034         })
1035     }
1036
1037     fn visit_pat(&mut self, p: &'a ast::Pat) {
1038         let mut visit_subpats = true;
1039         run_early_pass!(self, check_pat, p, &mut visit_subpats);
1040         self.check_id(p.id);
1041         if visit_subpats {
1042             ast_visit::walk_pat(self, p);
1043         }
1044     }
1045
1046     fn visit_expr(&mut self, e: &'a ast::Expr) {
1047         self.with_lint_attrs(e.id, &e.attrs, |cx| {
1048             run_early_pass!(cx, check_expr, e);
1049             ast_visit::walk_expr(cx, e);
1050         })
1051     }
1052
1053     fn visit_stmt(&mut self, s: &'a ast::Stmt) {
1054         run_early_pass!(self, check_stmt, s);
1055         self.check_id(s.id);
1056         ast_visit::walk_stmt(self, s);
1057     }
1058
1059     fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
1060                 span: Span, id: ast::NodeId) {
1061         run_early_pass!(self, check_fn, fk, decl, span, id);
1062         self.check_id(id);
1063         ast_visit::walk_fn(self, fk, decl, span);
1064         run_early_pass!(self, check_fn_post, fk, decl, span, id);
1065     }
1066
1067     fn visit_variant_data(&mut self,
1068                         s: &'a ast::VariantData,
1069                         ident: ast::Ident,
1070                         g: &'a ast::Generics,
1071                         item_id: ast::NodeId,
1072                         _: Span) {
1073         run_early_pass!(self, check_struct_def, s, ident, g, item_id);
1074         self.check_id(s.id());
1075         ast_visit::walk_struct_def(self, s);
1076         run_early_pass!(self, check_struct_def_post, s, ident, g, item_id);
1077     }
1078
1079     fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1080         self.with_lint_attrs(s.id, &s.attrs, |cx| {
1081             run_early_pass!(cx, check_struct_field, s);
1082             ast_visit::walk_struct_field(cx, s);
1083         })
1084     }
1085
1086     fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1087         self.with_lint_attrs(item_id, &v.node.attrs, |cx| {
1088             run_early_pass!(cx, check_variant, v, g);
1089             ast_visit::walk_variant(cx, v, g, item_id);
1090             run_early_pass!(cx, check_variant_post, v, g);
1091         })
1092     }
1093
1094     fn visit_ty(&mut self, t: &'a ast::Ty) {
1095         run_early_pass!(self, check_ty, t);
1096         self.check_id(t.id);
1097         ast_visit::walk_ty(self, t);
1098     }
1099
1100     fn visit_ident(&mut self, ident: ast::Ident) {
1101         run_early_pass!(self, check_ident, ident);
1102     }
1103
1104     fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
1105         run_early_pass!(self, check_mod, m, s, n);
1106         self.check_id(n);
1107         ast_visit::walk_mod(self, m);
1108         run_early_pass!(self, check_mod_post, m, s, n);
1109     }
1110
1111     fn visit_local(&mut self, l: &'a ast::Local) {
1112         self.with_lint_attrs(l.id, &l.attrs, |cx| {
1113             run_early_pass!(cx, check_local, l);
1114             ast_visit::walk_local(cx, l);
1115         })
1116     }
1117
1118     fn visit_block(&mut self, b: &'a ast::Block) {
1119         run_early_pass!(self, check_block, b);
1120         self.check_id(b.id);
1121         ast_visit::walk_block(self, b);
1122         run_early_pass!(self, check_block_post, b);
1123     }
1124
1125     fn visit_arm(&mut self, a: &'a ast::Arm) {
1126         run_early_pass!(self, check_arm, a);
1127         ast_visit::walk_arm(self, a);
1128     }
1129
1130     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1131         run_early_pass!(self, check_expr_post, e);
1132     }
1133
1134     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
1135         run_early_pass!(self, check_generic_param, param);
1136         ast_visit::walk_generic_param(self, param);
1137     }
1138
1139     fn visit_generics(&mut self, g: &'a ast::Generics) {
1140         run_early_pass!(self, check_generics, g);
1141         ast_visit::walk_generics(self, g);
1142     }
1143
1144     fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
1145         run_early_pass!(self, check_where_predicate, p);
1146         ast_visit::walk_where_predicate(self, p);
1147     }
1148
1149     fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
1150         run_early_pass!(self, check_poly_trait_ref, t, m);
1151         ast_visit::walk_poly_trait_ref(self, t, m);
1152     }
1153
1154     fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1155         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
1156             run_early_pass!(cx, check_trait_item, trait_item);
1157             ast_visit::walk_trait_item(cx, trait_item);
1158             run_early_pass!(cx, check_trait_item_post, trait_item);
1159         });
1160     }
1161
1162     fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1163         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
1164             run_early_pass!(cx, check_impl_item, impl_item);
1165             ast_visit::walk_impl_item(cx, impl_item);
1166             run_early_pass!(cx, check_impl_item_post, impl_item);
1167         });
1168     }
1169
1170     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1171         run_early_pass!(self, check_lifetime, lt);
1172         self.check_id(lt.id);
1173     }
1174
1175     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1176         run_early_pass!(self, check_path, p, id);
1177         self.check_id(id);
1178         ast_visit::walk_path(self, p);
1179     }
1180
1181     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1182         run_early_pass!(self, check_attribute, attr);
1183     }
1184
1185     fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
1186         run_early_pass!(self, check_mac_def, mac, id);
1187         self.check_id(id);
1188     }
1189
1190     fn visit_mac(&mut self, mac: &'a ast::Mac) {
1191         // FIXME(#54110): So, this setup isn't really right. I think
1192         // that (a) the libsyntax visitor ought to be doing this as
1193         // part of `walk_mac`, and (b) we should be calling
1194         // `visit_path`, *but* that would require a `NodeId`, and I
1195         // want to get #53686 fixed quickly. -nmatsakis
1196         ast_visit::walk_path(self, &mac.node.path);
1197
1198         run_early_pass!(self, check_mac, mac);
1199     }
1200 }
1201
1202
1203 /// Performs lint checking on a crate.
1204 ///
1205 /// Consumes the `lint_store` field of the `Session`.
1206 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1207     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1208
1209     let krate = tcx.hir().krate();
1210     let passes = tcx.sess.lint_store.borrow_mut().late_passes.take();
1211
1212     let passes = {
1213         let mut cx = LateContext {
1214             tcx,
1215             tables: &ty::TypeckTables::empty(None),
1216             param_env: ty::ParamEnv::empty(),
1217             access_levels,
1218             lint_sess: LintSession {
1219                 passes,
1220                 lints: tcx.sess.lint_store.borrow(),
1221             },
1222             last_ast_node_with_lint_attrs: ast::CRATE_NODE_ID,
1223             generics: None,
1224         };
1225
1226         // Visit the whole crate.
1227         cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1228             // since the root module isn't visited as an item (because it isn't an
1229             // item), warn for it here.
1230             run_lints!(cx, check_crate, krate);
1231
1232             hir_visit::walk_crate(cx, krate);
1233
1234             run_lints!(cx, check_crate_post, krate);
1235         });
1236         cx.lint_sess.passes
1237     };
1238
1239     // Put the lint store levels and passes back in the session.
1240     tcx.sess.lint_store.borrow_mut().late_passes = passes;
1241 }
1242
1243 struct EarlyLintPassObjects<'a> {
1244     lints: &'a mut [EarlyLintPassObject],
1245 }
1246
1247 impl LintPass for EarlyLintPassObjects<'_> {
1248     fn name(&self) -> &'static str {
1249         panic!()
1250     }
1251
1252     fn get_lints(&self) -> LintArray {
1253         panic!()
1254     }
1255 }
1256
1257 macro_rules! expand_early_lint_pass_impl_methods {
1258     ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
1259         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
1260             for obj in self.lints.iter_mut() {
1261                 obj.$name(context, $($param),*);
1262             }
1263         })*
1264     )
1265 }
1266
1267 macro_rules! early_lint_pass_impl {
1268     ([], [$($methods:tt)*]) => (
1269         impl EarlyLintPass for EarlyLintPassObjects<'_> {
1270             expand_early_lint_pass_impl_methods!([$($methods)*]);
1271         }
1272     )
1273 }
1274
1275 early_lint_methods!(early_lint_pass_impl, []);
1276
1277
1278 fn early_lint_crate<T: EarlyLintPass>(
1279     sess: &Session,
1280     krate: &ast::Crate,
1281     pass: T,
1282     buffered: LintBuffer,
1283 ) -> LintBuffer {
1284     let mut cx = EarlyContextAndPass {
1285         context: EarlyContext::new(sess, krate, buffered),
1286         pass,
1287     };
1288
1289     // Visit the whole crate.
1290     cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1291         // since the root module isn't visited as an item (because it isn't an
1292         // item), warn for it here.
1293         run_early_pass!(cx, check_crate, krate);
1294
1295         ast_visit::walk_crate(cx, krate);
1296
1297         run_early_pass!(cx, check_crate_post, krate);
1298     });
1299     cx.context.buffered
1300 }
1301
1302 pub fn check_ast_crate<T: EarlyLintPass>(
1303     sess: &Session,
1304     krate: &ast::Crate,
1305     pre_expansion: bool,
1306     builtin_lints: T,
1307 ) {
1308     let (mut passes, mut buffered) = if pre_expansion {
1309         (
1310             sess.lint_store.borrow_mut().pre_expansion_passes.take().unwrap(),
1311             LintBuffer::default(),
1312         )
1313     } else {
1314         (
1315             sess.lint_store.borrow_mut().early_passes.take().unwrap(),
1316             sess.buffered_lints.borrow_mut().take().unwrap(),
1317         )
1318     };
1319
1320     if !sess.opts.debugging_opts.no_interleave_lints {
1321         buffered = early_lint_crate(sess, krate, builtin_lints, buffered);
1322
1323         if !passes.is_empty() {
1324             buffered = early_lint_crate(
1325                 sess,
1326                 krate,
1327                 EarlyLintPassObjects { lints: &mut passes[..] },
1328                 buffered,
1329             );
1330         }
1331     } else {
1332         for pass in &mut passes {
1333             buffered = time(sess, &format!("running lint: {}", pass.name()), || {
1334                 early_lint_crate(
1335                     sess,
1336                     krate,
1337                     EarlyLintPassObjects { lints: slice::from_mut(pass) },
1338                     buffered,
1339                 )
1340             });
1341         }
1342     }
1343
1344     // Put the lint store levels and passes back in the session.
1345     if pre_expansion {
1346         sess.lint_store.borrow_mut().pre_expansion_passes = Some(passes);
1347     } else {
1348         sess.lint_store.borrow_mut().early_passes = Some(passes);
1349     }
1350
1351     // All of the buffered lints should have been emitted at this point.
1352     // If not, that means that we somehow buffered a lint for a node id
1353     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
1354     //
1355     // Rustdoc runs everybody-loops before the early lints and removes
1356     // function bodies, so it's totally possible for linted
1357     // node ids to not exist (e.g., macros defined within functions for the
1358     // unused_macro lint) anymore. So we only run this check
1359     // when we're not in rustdoc mode. (see issue #47639)
1360     if !sess.opts.actually_rustdoc {
1361         for (_id, lints) in buffered.map {
1362             for early_lint in lints {
1363                 sess.delay_span_bug(early_lint.span, "failed to process buffered lint here");
1364             }
1365         }
1366     }
1367 }
1368
1369 impl Encodable for LintId {
1370     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1371         s.emit_str(&self.lint.name.to_lowercase())
1372     }
1373 }
1374
1375 impl Decodable for LintId {
1376     #[inline]
1377     fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1378         let s = d.read_str()?;
1379         ty::tls::with(|tcx| {
1380             match tcx.sess.lint_store.borrow().find_lints(&s) {
1381                 Ok(ids) => {
1382                     if ids.len() != 0 {
1383                         panic!("invalid lint-id `{}`", s);
1384                     }
1385                     Ok(ids[0])
1386                 }
1387                 Err(_) => panic!("invalid lint-id `{}`", s),
1388             }
1389         })
1390     }
1391 }