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