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