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