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