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