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