]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/context.rs
Rollup merge of #41910 - mersinvald:master, r=Mark-Simulacrum
[rust.git] / src / librustc / lint / context.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Implementation of lint checking.
12 //!
13 //! The lint checking is mostly consolidated into one pass which runs just
14 //! before translation to LLVM bytecode. Throughout compilation, lint warnings
15 //! can be added via the `add_lint` method on the Session structure. This
16 //! requires a span and an id of the node that the lint is being added to. The
17 //! lint isn't actually emitted at that time because it is unknown what the
18 //! actual lint level at that location is.
19 //!
20 //! To actually emit lint warnings/errors, a separate pass is used just before
21 //! translation. A context keeps track of the current state of all lint levels.
22 //! Upon entering a node of the ast which can modify the lint settings, the
23 //! previous lint state is pushed onto a stack and the ast is then recursed
24 //! upon.  As the ast is traversed, this keeps track of the current lint level
25 //! for all lint attributes.
26 use self::TargetLint::*;
27
28 use dep_graph::DepNode;
29 use middle::privacy::AccessLevels;
30 use ty::{self, TyCtxt};
31 use session::{config, early_error, Session};
32 use lint::{Level, LevelSource, Lint, LintId, LintPass, LintSource};
33 use lint::{EarlyLintPassObject, LateLintPassObject};
34 use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
35 use lint::builtin;
36 use rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
37 use util::nodemap::FxHashMap;
38
39 use std::cmp;
40 use std::default::Default as StdDefault;
41 use std::mem;
42 use std::fmt;
43 use syntax::attr;
44 use syntax::ast;
45 use syntax::symbol::Symbol;
46 use syntax_pos::{MultiSpan, Span};
47 use errors::{self, Diagnostic, DiagnosticBuilder};
48 use hir;
49 use hir::def_id::LOCAL_CRATE;
50 use hir::intravisit as hir_visit;
51 use syntax::visit as ast_visit;
52 use syntax::tokenstream::ThinTokenStream;
53
54 /// Information about the registered lints.
55 ///
56 /// This is basically the subset of `Context` that we can
57 /// build early in the compile pipeline.
58 pub struct LintStore {
59     /// Registered lints. The bool is true if the lint was
60     /// added by a plugin.
61     lints: Vec<(&'static Lint, bool)>,
62
63     /// Trait objects for each lint pass.
64     /// This is only `None` while iterating over the objects. See the definition
65     /// of run_lints.
66     early_passes: Option<Vec<EarlyLintPassObject>>,
67     late_passes: Option<Vec<LateLintPassObject>>,
68
69     /// Lints indexed by name.
70     by_name: FxHashMap<String, TargetLint>,
71
72     /// Current levels of each lint, and where they were set.
73     levels: FxHashMap<LintId, LevelSource>,
74
75     /// Map of registered lint groups to what lints they expand to. The bool
76     /// is true if the lint group was added by a plugin.
77     lint_groups: FxHashMap<&'static str, (Vec<LintId>, bool)>,
78
79     /// Extra info for future incompatibility lints, descibing the
80     /// issue or RFC that caused the incompatibility.
81     future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
82
83     /// Maximum level a lint can be
84     lint_cap: Option<Level>,
85 }
86
87 /// When you call `add_lint` on the session, you wind up storing one
88 /// of these, which records a "potential lint" at a particular point.
89 #[derive(PartialEq, RustcEncodable, RustcDecodable)]
90 pub struct EarlyLint {
91     /// what lint is this? (e.g., `dead_code`)
92     pub id: LintId,
93
94     /// the main message
95     pub diagnostic: Diagnostic,
96 }
97
98 impl fmt::Debug for EarlyLint {
99     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100         f.debug_struct("EarlyLint")
101             .field("id", &self.id)
102             .field("span", &self.diagnostic.span)
103             .field("diagnostic", &self.diagnostic)
104             .finish()
105     }
106 }
107
108 pub trait IntoEarlyLint {
109     fn into_early_lint(self, id: LintId) -> EarlyLint;
110 }
111
112 impl<'a, S: Into<MultiSpan>> IntoEarlyLint for (S, &'a str) {
113     fn into_early_lint(self, id: LintId) -> EarlyLint {
114         let (span, msg) = self;
115         let mut diagnostic = Diagnostic::new(errors::Level::Warning, msg);
116         diagnostic.set_span(span);
117         EarlyLint {
118             id: id,
119             diagnostic: diagnostic,
120         }
121     }
122 }
123
124 impl IntoEarlyLint for Diagnostic {
125     fn into_early_lint(self, id: LintId) -> EarlyLint {
126         EarlyLint {
127             id: id,
128             diagnostic: self,
129         }
130     }
131 }
132
133 /// Extra information for a future incompatibility lint. See the call
134 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
135 /// guidelines.
136 pub struct FutureIncompatibleInfo {
137     pub id: LintId,
138     pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
139 }
140
141 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
142 enum TargetLint {
143     /// A direct lint target
144     Id(LintId),
145
146     /// Temporary renaming, used for easing migration pain; see #16545
147     Renamed(String, LintId),
148
149     /// Lint with this name existed previously, but has been removed/deprecated.
150     /// The string argument is the reason for removal.
151     Removed(String),
152 }
153
154 enum FindLintError {
155     NotFound,
156     Removed,
157 }
158
159 impl LintStore {
160     fn get_level_source(&self, lint: LintId) -> LevelSource {
161         match self.levels.get(&lint) {
162             Some(&s) => s,
163             None => (Allow, Default),
164         }
165     }
166
167     fn set_level(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
168         if let Some(cap) = self.lint_cap {
169             lvlsrc.0 = cmp::min(lvlsrc.0, cap);
170         }
171         if lvlsrc.0 == Allow {
172             self.levels.remove(&lint);
173         } else {
174             self.levels.insert(lint, lvlsrc);
175         }
176     }
177
178     pub fn new() -> LintStore {
179         LintStore {
180             lints: vec![],
181             early_passes: Some(vec![]),
182             late_passes: Some(vec![]),
183             by_name: FxHashMap(),
184             levels: FxHashMap(),
185             future_incompatible: FxHashMap(),
186             lint_groups: FxHashMap(),
187             lint_cap: None,
188         }
189     }
190
191     pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
192         &self.lints
193     }
194
195     pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
196         self.lint_groups.iter().map(|(k, v)| (*k,
197                                               v.0.clone(),
198                                               v.1)).collect()
199     }
200
201     pub fn register_early_pass(&mut self,
202                                sess: Option<&Session>,
203                                from_plugin: bool,
204                                pass: EarlyLintPassObject) {
205         self.push_pass(sess, from_plugin, &pass);
206         self.early_passes.as_mut().unwrap().push(pass);
207     }
208
209     pub fn register_late_pass(&mut self,
210                               sess: Option<&Session>,
211                               from_plugin: bool,
212                               pass: LateLintPassObject) {
213         self.push_pass(sess, from_plugin, &pass);
214         self.late_passes.as_mut().unwrap().push(pass);
215     }
216
217     // Helper method for register_early/late_pass
218     fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
219                                         sess: Option<&Session>,
220                                         from_plugin: bool,
221                                         pass: &Box<P>) {
222         for &lint in pass.get_lints() {
223             self.lints.push((*lint, from_plugin));
224
225             let id = LintId::of(*lint);
226             if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
227                 let msg = format!("duplicate specification of lint {}", lint.name_lower());
228                 match (sess, from_plugin) {
229                     // We load builtin lints first, so a duplicate is a compiler bug.
230                     // Use early_error when handling -W help with no crate.
231                     (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
232                     (Some(_), false) => bug!("{}", msg),
233
234                     // A duplicate name from a plugin is a user error.
235                     (Some(sess), true)  => sess.err(&msg[..]),
236                 }
237             }
238
239             if lint.default_level != Allow {
240                 self.levels.insert(id, (lint.default_level, Default));
241             }
242         }
243     }
244
245     pub fn register_future_incompatible(&mut self,
246                                         sess: Option<&Session>,
247                                         lints: Vec<FutureIncompatibleInfo>) {
248         let ids = lints.iter().map(|f| f.id).collect();
249         self.register_group(sess, false, "future_incompatible", ids);
250         for info in lints {
251             self.future_incompatible.insert(info.id, info);
252         }
253     }
254
255     pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
256         self.future_incompatible.get(&id)
257     }
258
259     pub fn register_group(&mut self, sess: Option<&Session>,
260                           from_plugin: bool, name: &'static str,
261                           to: Vec<LintId>) {
262         let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
263
264         if !new {
265             let msg = format!("duplicate specification of lint group {}", name);
266             match (sess, from_plugin) {
267                 // We load builtin lints first, so a duplicate is a compiler bug.
268                 // Use early_error when handling -W help with no crate.
269                 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
270                 (Some(_), false) => bug!("{}", msg),
271
272                 // A duplicate name from a plugin is a user error.
273                 (Some(sess), true)  => sess.err(&msg[..]),
274             }
275         }
276     }
277
278     pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
279         let target = match self.by_name.get(new_name) {
280             Some(&Id(lint_id)) => lint_id.clone(),
281             _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
282         };
283         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
284     }
285
286     pub fn register_removed(&mut self, name: &str, reason: &str) {
287         self.by_name.insert(name.into(), Removed(reason.into()));
288     }
289
290     #[allow(unused_variables)]
291     fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
292                  -> Result<LintId, FindLintError>
293     {
294         match self.by_name.get(lint_name) {
295             Some(&Id(lint_id)) => Ok(lint_id),
296             Some(&Renamed(_, lint_id)) => {
297                 Ok(lint_id)
298             },
299             Some(&Removed(ref reason)) => {
300                 Err(FindLintError::Removed)
301             },
302             None => Err(FindLintError::NotFound)
303         }
304     }
305
306     pub fn process_command_line(&mut self, sess: &Session) {
307         for &(ref lint_name, level) in &sess.opts.lint_opts {
308             check_lint_name_cmdline(sess, self,
309                                     &lint_name[..], level);
310
311             let lint_flag_val = Symbol::intern(&lint_name);
312             match self.find_lint(&lint_name[..], sess, None) {
313                 Ok(lint_id) => self.set_level(lint_id, (level, CommandLine(lint_flag_val))),
314                 Err(FindLintError::Removed) => { }
315                 Err(_) => {
316                     match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
317                                                  .collect::<FxHashMap<&'static str,
318                                                                       Vec<LintId>>>()
319                                                  .get(&lint_name[..]) {
320                         Some(v) => {
321                             v.iter()
322                              .map(|lint_id: &LintId|
323                                      self.set_level(*lint_id, (level, CommandLine(lint_flag_val))))
324                              .collect::<Vec<()>>();
325                         }
326                         None => {
327                             // The lint or lint group doesn't exist.
328                             // This is an error, but it was handled
329                             // by check_lint_name_cmdline.
330                         }
331                     }
332                 }
333             }
334         }
335
336         self.lint_cap = sess.opts.lint_cap;
337         if let Some(cap) = self.lint_cap {
338             for level in self.levels.iter_mut().map(|p| &mut (p.1).0) {
339                 *level = cmp::min(*level, cap);
340             }
341         }
342     }
343 }
344
345 /// Context for lint checking after type checking.
346 pub struct LateContext<'a, 'tcx: 'a> {
347     /// Type context we're checking in.
348     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
349
350     /// Side-tables for the body we are in.
351     pub tables: &'a ty::TypeckTables<'tcx>,
352
353     /// The crate being checked.
354     pub krate: &'a hir::Crate,
355
356     /// Items accessible from the crate being checked.
357     pub access_levels: &'a AccessLevels,
358
359     /// The store of registered lints.
360     lints: LintStore,
361
362     /// When recursing into an attributed node of the ast which modifies lint
363     /// levels, this stack keeps track of the previous lint levels of whatever
364     /// was modified.
365     level_stack: Vec<(LintId, LevelSource)>,
366 }
367
368 /// Context for lint checking of the AST, after expansion, before lowering to
369 /// HIR.
370 pub struct EarlyContext<'a> {
371     /// Type context we're checking in.
372     pub sess: &'a Session,
373
374     /// The crate being checked.
375     pub krate: &'a ast::Crate,
376
377     /// The store of registered lints.
378     lints: LintStore,
379
380     /// When recursing into an attributed node of the ast which modifies lint
381     /// levels, this stack keeps track of the previous lint levels of whatever
382     /// was modified.
383     level_stack: Vec<(LintId, LevelSource)>,
384 }
385
386 /// Convenience macro for calling a `LintPass` method on every pass in the context.
387 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
388     // Move the vector of passes out of `$cx` so that we can
389     // iterate over it mutably while passing `$cx` to the methods.
390     let mut passes = $cx.mut_lints().$ps.take().unwrap();
391     for obj in &mut passes {
392         obj.$f($cx, $($args),*);
393     }
394     $cx.mut_lints().$ps = Some(passes);
395 }) }
396
397 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
398 /// attributes. Writing this as an iterator is an enormous mess.
399 // See also the hir version just below.
400 pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec<Result<(ast::Name, Level, Span), Span>> {
401     let mut out = vec![];
402     for attr in attrs {
403         let r = gather_attr(attr);
404         out.extend(r.into_iter());
405     }
406     out
407 }
408
409 pub fn gather_attr(attr: &ast::Attribute) -> Vec<Result<(ast::Name, Level, Span), Span>> {
410     let mut out = vec![];
411
412     let level = match attr.name().and_then(|name| Level::from_str(&name.as_str())) {
413         None => return out,
414         Some(lvl) => lvl,
415     };
416
417     let meta = unwrap_or!(attr.meta(), return out);
418     attr::mark_used(attr);
419
420     let metas = if let Some(metas) = meta.meta_item_list() {
421         metas
422     } else {
423         out.push(Err(meta.span));
424         return out;
425     };
426
427     for li in metas {
428         out.push(li.word().map_or(Err(li.span), |word| Ok((word.name(), level, word.span))));
429     }
430
431     out
432 }
433
434 /// Emit a lint as a warning or an error (or not at all)
435 /// according to `level`.
436 ///
437 /// This lives outside of `Context` so it can be used by checks
438 /// in trans that run after the main lint pass is finished. Most
439 /// lints elsewhere in the compiler should call
440 /// `Session::add_lint()` instead.
441 pub fn raw_emit_lint<S: Into<MultiSpan>>(sess: &Session,
442                                          lints: &LintStore,
443                                          lint: &'static Lint,
444                                          lvlsrc: LevelSource,
445                                          span: Option<S>,
446                                          msg: &str) {
447     raw_struct_lint(sess, lints, lint, lvlsrc, span, msg).emit();
448 }
449
450 pub fn raw_struct_lint<'a, S>(sess: &'a Session,
451                               lints: &LintStore,
452                               lint: &'static Lint,
453                               lvlsrc: LevelSource,
454                               span: Option<S>,
455                               msg: &str)
456                               -> DiagnosticBuilder<'a>
457     where S: Into<MultiSpan>
458 {
459     let (level, source) = lvlsrc;
460     if level == Allow {
461         return sess.diagnostic().struct_dummy();
462     }
463
464     let name = lint.name_lower();
465     let mut def = None;
466
467     // Except for possible note details, forbid behaves like deny.
468     let effective_level = if level == Forbid { Deny } else { level };
469
470     let mut err = match (effective_level, span) {
471         (Warn, Some(sp)) => sess.struct_span_warn(sp, &msg[..]),
472         (Warn, None)     => sess.struct_warn(&msg[..]),
473         (Deny, Some(sp)) => sess.struct_span_err(sp, &msg[..]),
474         (Deny, None)     => sess.struct_err(&msg[..]),
475         _ => bug!("impossible level in raw_emit_lint"),
476     };
477
478     match source {
479         Default => {
480             err.note(&format!("#[{}({})] on by default", level.as_str(), name));
481         },
482         CommandLine(lint_flag_val) => {
483             let flag = match level {
484                 Warn => "-W", Deny => "-D", Forbid => "-F",
485                 Allow => bug!("earlier conditional return should handle Allow case")
486             };
487             let hyphen_case_lint_name = name.replace("_", "-");
488             if lint_flag_val.as_str() == name {
489                 err.note(&format!("requested on the command line with `{} {}`",
490                                   flag, hyphen_case_lint_name));
491             } else {
492                 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
493                 err.note(&format!("`{} {}` implied by `{} {}`",
494                                   flag, hyphen_case_lint_name, flag, hyphen_case_flag_val));
495             }
496         },
497         Node(lint_attr_name, src) => {
498             def = Some(src);
499             if lint_attr_name.as_str() != name {
500                 let level_str = level.as_str();
501                 err.note(&format!("#[{}({})] implied by #[{}({})]",
502                                   level_str, name, level_str, lint_attr_name));
503             }
504         }
505     }
506
507     // Check for future incompatibility lints and issue a stronger warning.
508     if let Some(future_incompatible) = lints.future_incompatible(LintId::of(lint)) {
509         let explanation = format!("this was previously accepted by the compiler \
510                                    but is being phased out; \
511                                    it will become a hard error in a future release!");
512         let citation = format!("for more information, see {}",
513                                future_incompatible.reference);
514         err.warn(&explanation);
515         err.note(&citation);
516     }
517
518     if let Some(span) = def {
519         sess.diag_span_note_once(&mut err, lint, span, "lint level defined here");
520     }
521
522     err
523 }
524
525 pub trait LintContext<'tcx>: Sized {
526     fn sess(&self) -> &Session;
527     fn lints(&self) -> &LintStore;
528     fn mut_lints(&mut self) -> &mut LintStore;
529     fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>;
530     fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
531     fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
532
533     /// Get the level of `lint` at the current position of the lint
534     /// traversal.
535     fn current_level(&self, lint: &'static Lint) -> Level {
536         self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
537     }
538
539     fn level_src(&self, lint: &'static Lint) -> Option<LevelSource> {
540         self.lints().levels.get(&LintId::of(lint)).map(|ls| match ls {
541             &(Warn, _) => {
542                 let lint_id = LintId::of(builtin::WARNINGS);
543                 let warn_src = self.lints().get_level_source(lint_id);
544                 if warn_src.0 != Warn {
545                     warn_src
546                 } else {
547                     *ls
548                 }
549             }
550             _ => *ls
551         })
552     }
553
554     fn lookup_and_emit<S: Into<MultiSpan>>(&self,
555                                            lint: &'static Lint,
556                                            span: Option<S>,
557                                            msg: &str) {
558         let (level, src) = match self.level_src(lint) {
559             None => return,
560             Some(pair) => pair,
561         };
562
563         raw_emit_lint(&self.sess(), self.lints(), lint, (level, src), span, msg);
564     }
565
566     fn lookup<S: Into<MultiSpan>>(&self,
567                                   lint: &'static Lint,
568                                   span: Option<S>,
569                                   msg: &str)
570                                   -> DiagnosticBuilder {
571         let (level, src) = match self.level_src(lint) {
572             None => return self.sess().diagnostic().struct_dummy(),
573             Some(pair) => pair,
574         };
575
576         raw_struct_lint(&self.sess(), self.lints(), lint, (level, src), span, msg)
577     }
578
579     /// Emit a lint at the appropriate level, for a particular span.
580     fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
581         self.lookup_and_emit(lint, Some(span), msg);
582     }
583
584     fn early_lint(&self, early_lint: &EarlyLint) {
585         let span = early_lint.diagnostic.span.primary_span().expect("early lint w/o primary span");
586         let mut err = self.struct_span_lint(early_lint.id.lint,
587                                             span,
588                                             &early_lint.diagnostic.message());
589         err.copy_details_not_message(&early_lint.diagnostic);
590         err.emit();
591     }
592
593     fn struct_span_lint<S: Into<MultiSpan>>(&self,
594                                             lint: &'static Lint,
595                                             span: S,
596                                             msg: &str)
597                                             -> DiagnosticBuilder {
598         self.lookup(lint, Some(span), msg)
599     }
600
601     /// Emit a lint and note at the appropriate level, for a particular span.
602     fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
603                       note_span: Span, note: &str) {
604         let mut err = self.lookup(lint, Some(span), msg);
605         if self.current_level(lint) != Level::Allow {
606             if note_span == span {
607                 err.note(note);
608             } else {
609                 err.span_note(note_span, note);
610             }
611         }
612         err.emit();
613     }
614
615     /// Emit a lint and help at the appropriate level, for a particular span.
616     fn span_lint_help(&self, lint: &'static Lint, span: Span,
617                       msg: &str, help: &str) {
618         let mut err = self.lookup(lint, Some(span), msg);
619         self.span_lint(lint, span, msg);
620         if self.current_level(lint) != Level::Allow {
621             err.span_help(span, help);
622         }
623         err.emit();
624     }
625
626     /// Emit a lint at the appropriate level, with no associated span.
627     fn lint(&self, lint: &'static Lint, msg: &str) {
628         self.lookup_and_emit(lint, None as Option<Span>, msg);
629     }
630
631     /// Merge the lints specified by any lint attributes into the
632     /// current lint context, call the provided function, then reset the
633     /// lints in effect to their previous state.
634     fn with_lint_attrs<F>(&mut self,
635                           attrs: &'tcx [ast::Attribute],
636                           f: F)
637         where F: FnOnce(&mut Self),
638     {
639         // Parse all of the lint attributes, and then add them all to the
640         // current dictionary of lint information. Along the way, keep a history
641         // of what we changed so we can roll everything back after invoking the
642         // specified closure
643         let mut pushed = 0;
644
645         for result in gather_attrs(attrs) {
646             let v = match result {
647                 Err(span) => {
648                     span_err!(self.sess(), span, E0452,
649                               "malformed lint attribute");
650                     continue;
651                 }
652                 Ok((lint_name, level, span)) => {
653                     match self.lints().find_lint(&lint_name.as_str(), &self.sess(), Some(span)) {
654                         Ok(lint_id) => vec![(lint_id, level, span)],
655                         Err(FindLintError::NotFound) => {
656                             match self.lints().lint_groups.get(&*lint_name.as_str()) {
657                                 Some(&(ref v, _)) => v.iter()
658                                                       .map(|lint_id: &LintId|
659                                                            (*lint_id, level, span))
660                                                       .collect(),
661                                 None => {
662                                     // The lint or lint group doesn't exist.
663                                     // This is an error, but it was handled
664                                     // by check_lint_name_attribute.
665                                     continue;
666                                 }
667                             }
668                         },
669                         Err(FindLintError::Removed) => { continue; }
670                     }
671                 }
672             };
673
674             let lint_attr_name = result.expect("lint attribute should be well-formed").0;
675
676             for (lint_id, level, span) in v {
677                 let (now, now_source) = self.lints().get_level_source(lint_id);
678                 if now == Forbid && level != Forbid {
679                     let lint_name = lint_id.to_string();
680                     let mut diag_builder = struct_span_err!(self.sess(), span, E0453,
681                                                             "{}({}) overruled by outer forbid({})",
682                                                             level.as_str(), lint_name,
683                                                             lint_name);
684                     diag_builder.span_label(span, "overruled by previous forbid");
685                     match now_source {
686                         LintSource::Default => &mut diag_builder,
687                         LintSource::Node(_, forbid_source_span) => {
688                             diag_builder.span_label(forbid_source_span,
689                                                     "`forbid` level set here")
690                         },
691                         LintSource::CommandLine(_) => {
692                             diag_builder.note("`forbid` lint level was set on command line")
693                         }
694                     }.emit()
695                 } else if now != level {
696                     let src = self.lints().get_level_source(lint_id).1;
697                     self.level_stack().push((lint_id, (now, src)));
698                     pushed += 1;
699                     self.mut_lints().set_level(lint_id, (level, Node(lint_attr_name, span)));
700                 }
701             }
702         }
703
704         self.enter_attrs(attrs);
705         f(self);
706         self.exit_attrs(attrs);
707
708         // rollback
709         for _ in 0..pushed {
710             let (lint, lvlsrc) = self.level_stack().pop().unwrap();
711             self.mut_lints().set_level(lint, lvlsrc);
712         }
713     }
714 }
715
716
717 impl<'a> EarlyContext<'a> {
718     fn new(sess: &'a Session,
719            krate: &'a ast::Crate) -> EarlyContext<'a> {
720         // We want to own the lint store, so move it out of the session. Remember
721         // to put it back later...
722         let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
723                                       LintStore::new());
724         EarlyContext {
725             sess: sess,
726             krate: krate,
727             lints: lint_store,
728             level_stack: vec![],
729         }
730     }
731 }
732
733 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
734     /// Get the overall compiler `Session` object.
735     fn sess(&self) -> &Session {
736         &self.tcx.sess
737     }
738
739     fn lints(&self) -> &LintStore {
740         &self.lints
741     }
742
743     fn mut_lints(&mut self) -> &mut LintStore {
744         &mut self.lints
745     }
746
747     fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
748         &mut self.level_stack
749     }
750
751     fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
752         debug!("late context: enter_attrs({:?})", attrs);
753         run_lints!(self, enter_lint_attrs, late_passes, attrs);
754     }
755
756     fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
757         debug!("late context: exit_attrs({:?})", attrs);
758         run_lints!(self, exit_lint_attrs, late_passes, attrs);
759     }
760 }
761
762 impl<'a> LintContext<'a> for EarlyContext<'a> {
763     /// Get the overall compiler `Session` object.
764     fn sess(&self) -> &Session {
765         &self.sess
766     }
767
768     fn lints(&self) -> &LintStore {
769         &self.lints
770     }
771
772     fn mut_lints(&mut self) -> &mut LintStore {
773         &mut self.lints
774     }
775
776     fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
777         &mut self.level_stack
778     }
779
780     fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
781         debug!("early context: enter_attrs({:?})", attrs);
782         run_lints!(self, enter_lint_attrs, early_passes, attrs);
783     }
784
785     fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
786         debug!("early context: exit_attrs({:?})", attrs);
787         run_lints!(self, exit_lint_attrs, early_passes, attrs);
788     }
789 }
790
791 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
792     /// Because lints are scoped lexically, we want to walk nested
793     /// items in the context of the outer item, so enable
794     /// deep-walking.
795     fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
796         hir_visit::NestedVisitorMap::All(&self.tcx.hir)
797     }
798
799     // Output any lints that were previously added to the session.
800     fn visit_id(&mut self, id: ast::NodeId) {
801         let lints = self.sess().lints.borrow_mut().take(id);
802         for early_lint in lints.iter().chain(self.tables.lints.get(id)) {
803             debug!("LateContext::visit_id: id={:?} early_lint={:?}", id, early_lint);
804             self.early_lint(early_lint);
805         }
806     }
807
808     fn visit_nested_body(&mut self, body: hir::BodyId) {
809         let old_tables = self.tables;
810         self.tables = self.tcx.body_tables(body);
811         let body = self.tcx.hir.body(body);
812         self.visit_body(body);
813         self.tables = old_tables;
814     }
815
816     fn visit_body(&mut self, body: &'tcx hir::Body) {
817         run_lints!(self, check_body, late_passes, body);
818         hir_visit::walk_body(self, body);
819         run_lints!(self, check_body_post, late_passes, body);
820     }
821
822     fn visit_item(&mut self, it: &'tcx hir::Item) {
823         self.with_lint_attrs(&it.attrs, |cx| {
824             run_lints!(cx, check_item, late_passes, it);
825             hir_visit::walk_item(cx, it);
826             run_lints!(cx, check_item_post, late_passes, it);
827         })
828     }
829
830     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
831         self.with_lint_attrs(&it.attrs, |cx| {
832             run_lints!(cx, check_foreign_item, late_passes, it);
833             hir_visit::walk_foreign_item(cx, it);
834             run_lints!(cx, check_foreign_item_post, late_passes, it);
835         })
836     }
837
838     fn visit_pat(&mut self, p: &'tcx hir::Pat) {
839         run_lints!(self, check_pat, late_passes, p);
840         hir_visit::walk_pat(self, p);
841     }
842
843     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
844         self.with_lint_attrs(&e.attrs, |cx| {
845             run_lints!(cx, check_expr, late_passes, e);
846             hir_visit::walk_expr(cx, e);
847             run_lints!(cx, check_expr_post, late_passes, e);
848         })
849     }
850
851     fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
852         // statement attributes are actually just attributes on one of
853         // - item
854         // - local
855         // - expression
856         // so we keep track of lint levels there
857         run_lints!(self, check_stmt, late_passes, s);
858         hir_visit::walk_stmt(self, s);
859     }
860
861     fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
862                 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
863         // Wrap in tables here, not just in visit_nested_body,
864         // in order for `check_fn` to be able to use them.
865         let old_tables = self.tables;
866         self.tables = self.tcx.body_tables(body_id);
867         let body = self.tcx.hir.body(body_id);
868         run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
869         hir_visit::walk_fn(self, fk, decl, body_id, span, id);
870         run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
871         self.tables = old_tables;
872     }
873
874     fn visit_variant_data(&mut self,
875                         s: &'tcx hir::VariantData,
876                         name: ast::Name,
877                         g: &'tcx hir::Generics,
878                         item_id: ast::NodeId,
879                         _: Span) {
880         run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
881         hir_visit::walk_struct_def(self, s);
882         run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
883     }
884
885     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
886         self.with_lint_attrs(&s.attrs, |cx| {
887             run_lints!(cx, check_struct_field, late_passes, s);
888             hir_visit::walk_struct_field(cx, s);
889         })
890     }
891
892     fn visit_variant(&mut self,
893                      v: &'tcx hir::Variant,
894                      g: &'tcx hir::Generics,
895                      item_id: ast::NodeId) {
896         self.with_lint_attrs(&v.node.attrs, |cx| {
897             run_lints!(cx, check_variant, late_passes, v, g);
898             hir_visit::walk_variant(cx, v, g, item_id);
899             run_lints!(cx, check_variant_post, late_passes, v, g);
900         })
901     }
902
903     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
904         run_lints!(self, check_ty, late_passes, t);
905         hir_visit::walk_ty(self, t);
906     }
907
908     fn visit_name(&mut self, sp: Span, name: ast::Name) {
909         run_lints!(self, check_name, late_passes, sp, name);
910     }
911
912     fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
913         run_lints!(self, check_mod, late_passes, m, s, n);
914         hir_visit::walk_mod(self, m, n);
915         run_lints!(self, check_mod_post, late_passes, m, s, n);
916     }
917
918     fn visit_local(&mut self, l: &'tcx hir::Local) {
919         self.with_lint_attrs(&l.attrs, |cx| {
920             run_lints!(cx, check_local, late_passes, l);
921             hir_visit::walk_local(cx, l);
922         })
923     }
924
925     fn visit_block(&mut self, b: &'tcx hir::Block) {
926         run_lints!(self, check_block, late_passes, b);
927         hir_visit::walk_block(self, b);
928         run_lints!(self, check_block_post, late_passes, b);
929     }
930
931     fn visit_arm(&mut self, a: &'tcx hir::Arm) {
932         run_lints!(self, check_arm, late_passes, a);
933         hir_visit::walk_arm(self, a);
934     }
935
936     fn visit_decl(&mut self, d: &'tcx hir::Decl) {
937         run_lints!(self, check_decl, late_passes, d);
938         hir_visit::walk_decl(self, d);
939     }
940
941     fn visit_generics(&mut self, g: &'tcx hir::Generics) {
942         run_lints!(self, check_generics, late_passes, g);
943         hir_visit::walk_generics(self, g);
944     }
945
946     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
947         self.with_lint_attrs(&trait_item.attrs, |cx| {
948             run_lints!(cx, check_trait_item, late_passes, trait_item);
949             hir_visit::walk_trait_item(cx, trait_item);
950             run_lints!(cx, check_trait_item_post, late_passes, trait_item);
951         });
952     }
953
954     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
955         self.with_lint_attrs(&impl_item.attrs, |cx| {
956             run_lints!(cx, check_impl_item, late_passes, impl_item);
957             hir_visit::walk_impl_item(cx, impl_item);
958             run_lints!(cx, check_impl_item_post, late_passes, impl_item);
959         });
960     }
961
962     fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
963         run_lints!(self, check_lifetime, late_passes, lt);
964         hir_visit::walk_lifetime(self, lt);
965     }
966
967     fn visit_lifetime_def(&mut self, lt: &'tcx hir::LifetimeDef) {
968         run_lints!(self, check_lifetime_def, late_passes, lt);
969         hir_visit::walk_lifetime_def(self, lt);
970     }
971
972     fn visit_path(&mut self, p: &'tcx hir::Path, id: ast::NodeId) {
973         run_lints!(self, check_path, late_passes, p, id);
974         hir_visit::walk_path(self, p);
975     }
976
977     fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
978         check_lint_name_attribute(self, attr);
979         run_lints!(self, check_attribute, late_passes, attr);
980     }
981 }
982
983 impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> {
984     fn visit_item(&mut self, it: &'a ast::Item) {
985         self.with_lint_attrs(&it.attrs, |cx| {
986             run_lints!(cx, check_item, early_passes, it);
987             ast_visit::walk_item(cx, it);
988             run_lints!(cx, check_item_post, early_passes, it);
989         })
990     }
991
992     fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
993         self.with_lint_attrs(&it.attrs, |cx| {
994             run_lints!(cx, check_foreign_item, early_passes, it);
995             ast_visit::walk_foreign_item(cx, it);
996             run_lints!(cx, check_foreign_item_post, early_passes, it);
997         })
998     }
999
1000     fn visit_pat(&mut self, p: &'a ast::Pat) {
1001         run_lints!(self, check_pat, early_passes, p);
1002         ast_visit::walk_pat(self, p);
1003     }
1004
1005     fn visit_expr(&mut self, e: &'a ast::Expr) {
1006         self.with_lint_attrs(&e.attrs, |cx| {
1007             run_lints!(cx, check_expr, early_passes, e);
1008             ast_visit::walk_expr(cx, e);
1009         })
1010     }
1011
1012     fn visit_stmt(&mut self, s: &'a ast::Stmt) {
1013         run_lints!(self, check_stmt, early_passes, s);
1014         ast_visit::walk_stmt(self, s);
1015     }
1016
1017     fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
1018                 span: Span, id: ast::NodeId) {
1019         run_lints!(self, check_fn, early_passes, fk, decl, span, id);
1020         ast_visit::walk_fn(self, fk, decl, span);
1021         run_lints!(self, check_fn_post, early_passes, fk, decl, span, id);
1022     }
1023
1024     fn visit_variant_data(&mut self,
1025                         s: &'a ast::VariantData,
1026                         ident: ast::Ident,
1027                         g: &'a ast::Generics,
1028                         item_id: ast::NodeId,
1029                         _: Span) {
1030         run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
1031         ast_visit::walk_struct_def(self, s);
1032         run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
1033     }
1034
1035     fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1036         self.with_lint_attrs(&s.attrs, |cx| {
1037             run_lints!(cx, check_struct_field, early_passes, s);
1038             ast_visit::walk_struct_field(cx, s);
1039         })
1040     }
1041
1042     fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1043         self.with_lint_attrs(&v.node.attrs, |cx| {
1044             run_lints!(cx, check_variant, early_passes, v, g);
1045             ast_visit::walk_variant(cx, v, g, item_id);
1046             run_lints!(cx, check_variant_post, early_passes, v, g);
1047         })
1048     }
1049
1050     fn visit_ty(&mut self, t: &'a ast::Ty) {
1051         run_lints!(self, check_ty, early_passes, t);
1052         ast_visit::walk_ty(self, t);
1053     }
1054
1055     fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
1056         run_lints!(self, check_ident, early_passes, sp, id);
1057     }
1058
1059     fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
1060         run_lints!(self, check_mod, early_passes, m, s, n);
1061         ast_visit::walk_mod(self, m);
1062         run_lints!(self, check_mod_post, early_passes, m, s, n);
1063     }
1064
1065     fn visit_local(&mut self, l: &'a ast::Local) {
1066         self.with_lint_attrs(&l.attrs, |cx| {
1067             run_lints!(cx, check_local, early_passes, l);
1068             ast_visit::walk_local(cx, l);
1069         })
1070     }
1071
1072     fn visit_block(&mut self, b: &'a ast::Block) {
1073         run_lints!(self, check_block, early_passes, b);
1074         ast_visit::walk_block(self, b);
1075         run_lints!(self, check_block_post, early_passes, b);
1076     }
1077
1078     fn visit_arm(&mut self, a: &'a ast::Arm) {
1079         run_lints!(self, check_arm, early_passes, a);
1080         ast_visit::walk_arm(self, a);
1081     }
1082
1083     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1084         run_lints!(self, check_expr_post, early_passes, e);
1085     }
1086
1087     fn visit_generics(&mut self, g: &'a ast::Generics) {
1088         run_lints!(self, check_generics, early_passes, g);
1089         ast_visit::walk_generics(self, g);
1090     }
1091
1092     fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1093         self.with_lint_attrs(&trait_item.attrs, |cx| {
1094             run_lints!(cx, check_trait_item, early_passes, trait_item);
1095             ast_visit::walk_trait_item(cx, trait_item);
1096             run_lints!(cx, check_trait_item_post, early_passes, trait_item);
1097         });
1098     }
1099
1100     fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1101         self.with_lint_attrs(&impl_item.attrs, |cx| {
1102             run_lints!(cx, check_impl_item, early_passes, impl_item);
1103             ast_visit::walk_impl_item(cx, impl_item);
1104             run_lints!(cx, check_impl_item_post, early_passes, impl_item);
1105         });
1106     }
1107
1108     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1109         run_lints!(self, check_lifetime, early_passes, lt);
1110     }
1111
1112     fn visit_lifetime_def(&mut self, lt: &'a ast::LifetimeDef) {
1113         run_lints!(self, check_lifetime_def, early_passes, lt);
1114     }
1115
1116     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1117         run_lints!(self, check_path, early_passes, p, id);
1118         ast_visit::walk_path(self, p);
1119     }
1120
1121     fn visit_path_list_item(&mut self, prefix: &'a ast::Path, item: &'a ast::PathListItem) {
1122         run_lints!(self, check_path_list_item, early_passes, item);
1123         ast_visit::walk_path_list_item(self, prefix, item);
1124     }
1125
1126     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1127         run_lints!(self, check_attribute, early_passes, attr);
1128     }
1129
1130     fn visit_mac_def(&mut self, _mac: &'a ThinTokenStream, id: ast::NodeId) {
1131         let lints = self.sess.lints.borrow_mut().take(id);
1132         for early_lint in lints {
1133             self.early_lint(&early_lint);
1134         }
1135     }
1136 }
1137
1138 enum CheckLintNameResult {
1139     Ok,
1140     // Lint doesn't exist
1141     NoLint,
1142     // The lint is either renamed or removed. This is the warning
1143     // message.
1144     Warning(String),
1145 }
1146
1147 /// Checks the name of a lint for its existence, and whether it was
1148 /// renamed or removed. Generates a DiagnosticBuilder containing a
1149 /// warning for renamed and removed lints. This is over both lint
1150 /// names from attributes and those passed on the command line. Since
1151 /// it emits non-fatal warnings and there are *two* lint passes that
1152 /// inspect attributes, this is only run from the late pass to avoid
1153 /// printing duplicate warnings.
1154 fn check_lint_name(lint_cx: &LintStore,
1155                    lint_name: &str) -> CheckLintNameResult {
1156     match lint_cx.by_name.get(lint_name) {
1157         Some(&Renamed(ref new_name, _)) => {
1158             CheckLintNameResult::Warning(
1159                 format!("lint {} has been renamed to {}", lint_name, new_name)
1160             )
1161         },
1162         Some(&Removed(ref reason)) => {
1163             CheckLintNameResult::Warning(
1164                 format!("lint {} has been removed: {}", lint_name, reason)
1165             )
1166         },
1167         None => {
1168             match lint_cx.lint_groups.get(lint_name) {
1169                 None => {
1170                     CheckLintNameResult::NoLint
1171                 }
1172                 Some(_) => {
1173                     /* lint group exists */
1174                     CheckLintNameResult::Ok
1175                 }
1176             }
1177         }
1178         Some(_) => {
1179             /* lint exists */
1180             CheckLintNameResult::Ok
1181         }
1182     }
1183 }
1184
1185 // Checks the validity of lint names derived from attributes
1186 fn check_lint_name_attribute(cx: &LateContext, attr: &ast::Attribute) {
1187     for result in gather_attr(attr) {
1188         match result {
1189             Err(_) => {
1190                 // Malformed lint attr. Reported by with_lint_attrs
1191                 continue;
1192             }
1193             Ok((lint_name, _, span)) => {
1194                 match check_lint_name(&cx.lints, &lint_name.as_str()) {
1195                     CheckLintNameResult::Ok => (),
1196                     CheckLintNameResult::Warning(ref msg) => {
1197                         cx.span_lint(builtin::RENAMED_AND_REMOVED_LINTS,
1198                                      span, msg);
1199                     }
1200                     CheckLintNameResult::NoLint => {
1201                         cx.span_lint(builtin::UNKNOWN_LINTS, span,
1202                                      &format!("unknown lint: `{}`",
1203                                               lint_name));
1204                     }
1205                 }
1206             }
1207         }
1208     }
1209 }
1210
1211 // Checks the validity of lint names derived from the command line
1212 fn check_lint_name_cmdline(sess: &Session, lint_cx: &LintStore,
1213                            lint_name: &str, level: Level) {
1214     let db = match check_lint_name(lint_cx, lint_name) {
1215         CheckLintNameResult::Ok => None,
1216         CheckLintNameResult::Warning(ref msg) => {
1217             Some(sess.struct_warn(msg))
1218         },
1219         CheckLintNameResult::NoLint => {
1220             Some(sess.struct_err(&format!("unknown lint: `{}`", lint_name)))
1221         }
1222     };
1223
1224     if let Some(mut db) = db {
1225         let msg = format!("requested on the command line with `{} {}`",
1226                           match level {
1227                               Level::Allow => "-A",
1228                               Level::Warn => "-W",
1229                               Level::Deny => "-D",
1230                               Level::Forbid => "-F",
1231                           },
1232                           lint_name);
1233         db.note(&msg);
1234         db.emit();
1235     }
1236 }
1237
1238
1239 /// Perform lint checking on a crate.
1240 ///
1241 /// Consumes the `lint_store` field of the `Session`.
1242 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1243     let _task = tcx.dep_graph.in_task(DepNode::LateLintCheck);
1244
1245     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1246
1247     let krate = tcx.hir.krate();
1248
1249     // We want to own the lint store, so move it out of the session.
1250     let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), LintStore::new());
1251     let mut cx = LateContext {
1252         tcx: tcx,
1253         tables: &ty::TypeckTables::empty(),
1254         krate: krate,
1255         access_levels: access_levels,
1256         lints: lint_store,
1257         level_stack: vec![],
1258     };
1259
1260     // Visit the whole crate.
1261     cx.with_lint_attrs(&krate.attrs, |cx| {
1262         // since the root module isn't visited as an item (because it isn't an
1263         // item), warn for it here.
1264         run_lints!(cx, check_crate, late_passes, krate);
1265
1266         hir_visit::walk_crate(cx, krate);
1267
1268         run_lints!(cx, check_crate_post, late_passes, krate);
1269     });
1270
1271     // If we missed any lints added to the session, then there's a bug somewhere
1272     // in the iteration code.
1273     if let Some((id, v)) = tcx.sess.lints.borrow().get_any() {
1274         for early_lint in v {
1275             span_bug!(early_lint.diagnostic.span.clone(),
1276                       "unprocessed lint {:?} at {}",
1277                       early_lint, tcx.hir.node_to_string(*id));
1278         }
1279     }
1280
1281     // Put the lint store back in the session.
1282     mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), cx.lints);
1283 }
1284
1285 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1286     let mut cx = EarlyContext::new(sess, krate);
1287
1288     // Visit the whole crate.
1289     cx.with_lint_attrs(&krate.attrs, |cx| {
1290         // Lints may be assigned to the whole crate.
1291         let lints = cx.sess.lints.borrow_mut().take(ast::CRATE_NODE_ID);
1292         for early_lint in lints {
1293             cx.early_lint(&early_lint);
1294         }
1295
1296         // since the root module isn't visited as an item (because it isn't an
1297         // item), warn for it here.
1298         run_lints!(cx, check_crate, early_passes, krate);
1299
1300         ast_visit::walk_crate(cx, krate);
1301
1302         run_lints!(cx, check_crate_post, early_passes, krate);
1303     });
1304
1305     // Put the lint store back in the session.
1306     mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1307
1308     // If we missed any lints added to the session, then there's a bug somewhere
1309     // in the iteration code.
1310     for (_, v) in sess.lints.borrow().get_any() {
1311         for early_lint in v {
1312             span_bug!(early_lint.diagnostic.span.clone(), "unprocessed lint {:?}", early_lint);
1313         }
1314     }
1315 }
1316
1317 impl Encodable for LintId {
1318     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1319         s.emit_str(&self.lint.name.to_lowercase())
1320     }
1321 }
1322
1323 impl Decodable for LintId {
1324     #[inline]
1325     fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1326         let s = d.read_str()?;
1327         ty::tls::with(|tcx| {
1328             match tcx.sess.lint_store.borrow().find_lint(&s, tcx.sess, None) {
1329                 Ok(id) => Ok(id),
1330                 Err(_) => panic!("invalid lint-id `{}`", s),
1331             }
1332         })
1333     }
1334 }