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