]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/context.rs
f47c709e03aa2f5ebb771d26a157ae919070fbac
[rust.git] / src / librustc / lint / context.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Implementation of lint checking.
12 //!
13 //! The lint checking is mostly consolidated into one pass which runs just
14 //! before translation to LLVM bytecode. Throughout compilation, lint warnings
15 //! can be added via the `add_lint` method on the Session structure. This
16 //! requires a span and an id of the node that the lint is being added to. The
17 //! lint isn't actually emitted at that time because it is unknown what the
18 //! actual lint level at that location is.
19 //!
20 //! To actually emit lint warnings/errors, a separate pass is used just before
21 //! translation. A context keeps track of the current state of all lint levels.
22 //! Upon entering a node of the ast which can modify the lint settings, the
23 //! previous lint state is pushed onto a stack and the ast is then recursed
24 //! upon.  As the ast is traversed, this keeps track of the current lint level
25 //! for all lint attributes.
26 use self::TargetLint::*;
27
28 use middle::privacy::ExportedItems;
29 use middle::ty::{self, Ty};
30 use session::{early_error, Session};
31 use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass};
32 use lint::{EarlyLintPass, EarlyLintPassObject, LateLintPass, LateLintPassObject};
33 use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
34 use lint::builtin;
35 use util::nodemap::FnvHashMap;
36
37 use std::cell::RefCell;
38 use std::cmp;
39 use std::mem;
40 use syntax::ast_util::{self, IdVisitingOperation};
41 use syntax::attr::{self, AttrMetaMethods};
42 use syntax::codemap::Span;
43 use syntax::parse::token::InternedString;
44 use syntax::ast;
45 use rustc_front::hir;
46 use rustc_front::util;
47 use rustc_front::visit as hir_visit;
48 use syntax::visit as ast_visit;
49 use syntax::diagnostic;
50
51 /// Information about the registered lints.
52 ///
53 /// This is basically the subset of `Context` that we can
54 /// build early in the compile pipeline.
55 pub struct LintStore {
56     /// Registered lints. The bool is true if the lint was
57     /// added by a plugin.
58     lints: Vec<(&'static Lint, bool)>,
59
60     /// Trait objects for each lint pass.
61     /// This is only `None` while iterating over the objects. See the definition
62     /// of run_lints.
63     early_passes: Option<Vec<EarlyLintPassObject>>,
64     late_passes: Option<Vec<LateLintPassObject>>,
65
66     /// Lints indexed by name.
67     by_name: FnvHashMap<String, TargetLint>,
68
69     /// Current levels of each lint, and where they were set.
70     levels: FnvHashMap<LintId, LevelSource>,
71
72     /// Map of registered lint groups to what lints they expand to. The bool
73     /// is true if the lint group was added by a plugin.
74     lint_groups: FnvHashMap<&'static str, (Vec<LintId>, bool)>,
75
76     /// Maximum level a lint can be
77     lint_cap: Option<Level>,
78 }
79
80 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
81 enum TargetLint {
82     /// A direct lint target
83     Id(LintId),
84
85     /// Temporary renaming, used for easing migration pain; see #16545
86     Renamed(String, LintId),
87
88     /// Lint with this name existed previously, but has been removed/deprecated.
89     /// The string argument is the reason for removal.
90     Removed(String),
91 }
92
93 enum FindLintError {
94     NotFound,
95     Removed
96 }
97
98 impl LintStore {
99     fn get_level_source(&self, lint: LintId) -> LevelSource {
100         match self.levels.get(&lint) {
101             Some(&s) => s,
102             None => (Allow, Default),
103         }
104     }
105
106     fn set_level(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
107         if let Some(cap) = self.lint_cap {
108             lvlsrc.0 = cmp::min(lvlsrc.0, cap);
109         }
110         if lvlsrc.0 == Allow {
111             self.levels.remove(&lint);
112         } else {
113             self.levels.insert(lint, lvlsrc);
114         }
115     }
116
117     pub fn new() -> LintStore {
118         LintStore {
119             lints: vec!(),
120             early_passes: Some(vec!()),
121             late_passes: Some(vec!()),
122             by_name: FnvHashMap(),
123             levels: FnvHashMap(),
124             lint_groups: FnvHashMap(),
125             lint_cap: None,
126         }
127     }
128
129     pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
130         &self.lints
131     }
132
133     pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
134         self.lint_groups.iter().map(|(k, v)| (*k,
135                                               v.0.clone(),
136                                               v.1)).collect()
137     }
138
139     pub fn register_early_pass(&mut self,
140                                sess: Option<&Session>,
141                                from_plugin: bool,
142                                pass: EarlyLintPassObject) {
143         self.push_pass(sess, from_plugin, &pass);
144         self.early_passes.as_mut().unwrap().push(pass);
145     }
146
147     pub fn register_late_pass(&mut self,
148                               sess: Option<&Session>,
149                               from_plugin: bool,
150                               pass: LateLintPassObject) {
151         self.push_pass(sess, from_plugin, &pass);
152         self.late_passes.as_mut().unwrap().push(pass);
153     }
154
155     // Helper method for register_early/late_pass
156     fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
157                                         sess: Option<&Session>,
158                                         from_plugin: bool,
159                                         pass: &Box<P>) {
160         for &lint in pass.get_lints() {
161             self.lints.push((*lint, from_plugin));
162
163             let id = LintId::of(*lint);
164             if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
165                 let msg = format!("duplicate specification of lint {}", lint.name_lower());
166                 match (sess, from_plugin) {
167                     // We load builtin lints first, so a duplicate is a compiler bug.
168                     // Use early_error when handling -W help with no crate.
169                     (None, _) => early_error(diagnostic::Auto, &msg[..]),
170                     (Some(sess), false) => sess.bug(&msg[..]),
171
172                     // A duplicate name from a plugin is a user error.
173                     (Some(sess), true)  => sess.err(&msg[..]),
174                 }
175             }
176
177             if lint.default_level != Allow {
178                 self.levels.insert(id, (lint.default_level, Default));
179             }
180         }
181     }
182
183     pub fn register_group(&mut self, sess: Option<&Session>,
184                           from_plugin: bool, name: &'static str,
185                           to: Vec<LintId>) {
186         let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
187
188         if !new {
189             let msg = format!("duplicate specification of lint group {}", name);
190             match (sess, from_plugin) {
191                 // We load builtin lints first, so a duplicate is a compiler bug.
192                 // Use early_error when handling -W help with no crate.
193                 (None, _) => early_error(diagnostic::Auto, &msg[..]),
194                 (Some(sess), false) => sess.bug(&msg[..]),
195
196                 // A duplicate name from a plugin is a user error.
197                 (Some(sess), true)  => sess.err(&msg[..]),
198             }
199         }
200     }
201
202     pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
203         let target = match self.by_name.get(new_name) {
204             Some(&Id(lint_id)) => lint_id.clone(),
205             _ => panic!("invalid lint renaming of {} to {}", old_name, new_name)
206         };
207         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
208     }
209
210     pub fn register_removed(&mut self, name: &str, reason: &str) {
211         self.by_name.insert(name.into(), Removed(reason.into()));
212     }
213
214     #[allow(unused_variables)]
215     fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
216                  -> Result<LintId, FindLintError>
217     {
218         match self.by_name.get(lint_name) {
219             Some(&Id(lint_id)) => Ok(lint_id),
220             Some(&Renamed(ref new_name, lint_id)) => {
221                 let warning = format!("lint {} has been renamed to {}",
222                                       lint_name, new_name);
223                 match span {
224                     Some(span) => sess.span_warn(span, &warning[..]),
225                     None => sess.warn(&warning[..]),
226                 };
227                 Ok(lint_id)
228             },
229             Some(&Removed(ref reason)) => {
230                 let warning = format!("lint {} has been removed: {}", lint_name, reason);
231                 match span {
232                     Some(span) => sess.span_warn(span, &warning[..]),
233                     None => sess.warn(&warning[..])
234                 }
235                 Err(FindLintError::Removed)
236             },
237             None => Err(FindLintError::NotFound)
238         }
239     }
240
241     pub fn process_command_line(&mut self, sess: &Session) {
242         for &(ref lint_name, level) in &sess.opts.lint_opts {
243             match self.find_lint(&lint_name[..], sess, None) {
244                 Ok(lint_id) => self.set_level(lint_id, (level, CommandLine)),
245                 Err(_) => {
246                     match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
247                                                  .collect::<FnvHashMap<&'static str,
248                                                                        Vec<LintId>>>()
249                                                  .get(&lint_name[..]) {
250                         Some(v) => {
251                             v.iter()
252                              .map(|lint_id: &LintId|
253                                      self.set_level(*lint_id, (level, CommandLine)))
254                              .collect::<Vec<()>>();
255                         }
256                         None => sess.err(&format!("unknown {} flag: {}",
257                                                  level.as_str(), lint_name)),
258                     }
259                 }
260             }
261         }
262
263         self.lint_cap = sess.opts.lint_cap;
264         if let Some(cap) = self.lint_cap {
265             for level in self.levels.iter_mut().map(|p| &mut (p.1).0) {
266                 *level = cmp::min(*level, cap);
267             }
268         }
269     }
270 }
271
272 /// Context for lint checking after type checking.
273 pub struct LateContext<'a, 'tcx: 'a> {
274     /// Type context we're checking in.
275     pub tcx: &'a ty::ctxt<'tcx>,
276
277     /// The crate being checked.
278     pub krate: &'a hir::Crate,
279
280     /// Items exported from the crate being checked.
281     pub exported_items: &'a ExportedItems,
282
283     /// The store of registered lints.
284     lints: LintStore,
285
286     /// When recursing into an attributed node of the ast which modifies lint
287     /// levels, this stack keeps track of the previous lint levels of whatever
288     /// was modified.
289     level_stack: Vec<(LintId, LevelSource)>,
290
291     /// Level of lints for certain NodeIds, stored here because the body of
292     /// the lint needs to run in trans.
293     node_levels: RefCell<FnvHashMap<(ast::NodeId, LintId), LevelSource>>,
294 }
295
296 /// Context for lint checking of the AST, after expansion, before lowering to
297 /// HIR.
298 pub struct EarlyContext<'a> {
299     /// Type context we're checking in.
300     pub sess: &'a Session,
301
302     /// The crate being checked.
303     pub krate: &'a ast::Crate,
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 /// Convenience macro for calling a `LintPass` method on every pass in the context.
315 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
316     // Move the vector of passes out of `$cx` so that we can
317     // iterate over it mutably while passing `$cx` to the methods.
318     let mut passes = $cx.mut_lints().$ps.take().unwrap();
319     for obj in &mut passes {
320         obj.$f($cx, $($args),*);
321     }
322     $cx.mut_lints().$ps = Some(passes);
323 }) }
324
325 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
326 /// attributes. Writing this as an iterator is an enormous mess.
327 // See also the hir version just below.
328 pub fn gather_attrs(attrs: &[ast::Attribute])
329                     -> Vec<Result<(InternedString, Level, Span), Span>> {
330     let mut out = vec!();
331     for attr in attrs {
332         let level = match Level::from_str(&attr.name()) {
333             None => continue,
334             Some(lvl) => lvl,
335         };
336
337         attr::mark_used(attr);
338
339         let meta = &attr.node.value;
340         let metas = match meta.node {
341             ast::MetaList(_, ref metas) => metas,
342             _ => {
343                 out.push(Err(meta.span));
344                 continue;
345             }
346         };
347
348         for meta in metas {
349             out.push(match meta.node {
350                 ast::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)),
351                 _ => Err(meta.span),
352             });
353         }
354     }
355     out
356 }
357
358 /// Emit a lint as a warning or an error (or not at all)
359 /// according to `level`.
360 ///
361 /// This lives outside of `Context` so it can be used by checks
362 /// in trans that run after the main lint pass is finished. Most
363 /// lints elsewhere in the compiler should call
364 /// `Session::add_lint()` instead.
365 pub fn raw_emit_lint(sess: &Session, lint: &'static Lint,
366                      lvlsrc: LevelSource, span: Option<Span>, msg: &str) {
367     let (mut level, source) = lvlsrc;
368     if level == Allow { return }
369
370     let name = lint.name_lower();
371     let mut def = None;
372     let msg = match source {
373         Default => {
374             format!("{}, #[{}({})] on by default", msg,
375                     level.as_str(), name)
376         },
377         CommandLine => {
378             format!("{} [-{} {}]", msg,
379                     match level {
380                         Warn => 'W', Deny => 'D', Forbid => 'F',
381                         Allow => panic!()
382                     }, name.replace("_", "-"))
383         },
384         Node(src) => {
385             def = Some(src);
386             msg.to_string()
387         }
388     };
389
390     // For purposes of printing, we can treat forbid as deny.
391     if level == Forbid { level = Deny; }
392
393     match (level, span) {
394         (Warn, Some(sp)) => sess.span_warn(sp, &msg[..]),
395         (Warn, None)     => sess.warn(&msg[..]),
396         (Deny, Some(sp)) => sess.span_err(sp, &msg[..]),
397         (Deny, None)     => sess.err(&msg[..]),
398         _ => sess.bug("impossible level in raw_emit_lint"),
399     }
400
401     if let Some(span) = def {
402         sess.span_note(span, "lint level defined here");
403     }
404 }
405
406 pub trait LintContext: Sized {
407     fn sess(&self) -> &Session;
408     fn lints(&self) -> &LintStore;
409     fn mut_lints(&mut self) -> &mut LintStore;
410     fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>;
411     fn enter_attrs(&mut self, attrs: &[ast::Attribute]);
412     fn exit_attrs(&mut self, attrs: &[ast::Attribute]);
413
414     /// Get the level of `lint` at the current position of the lint
415     /// traversal.
416     fn current_level(&self, lint: &'static Lint) -> Level {
417         self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
418     }
419
420     fn lookup_and_emit(&self, lint: &'static Lint, span: Option<Span>, msg: &str) {
421         let (level, src) = match self.lints().levels.get(&LintId::of(lint)) {
422             None => return,
423             Some(&(Warn, src)) => {
424                 let lint_id = LintId::of(builtin::WARNINGS);
425                 (self.lints().get_level_source(lint_id).0, src)
426             }
427             Some(&pair) => pair,
428         };
429
430         raw_emit_lint(&self.sess(), lint, (level, src), span, msg);
431     }
432
433     /// Emit a lint at the appropriate level, for a particular span.
434     fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) {
435         self.lookup_and_emit(lint, Some(span), msg);
436     }
437
438     /// Emit a lint at the appropriate level, with no associated span.
439     fn lint(&self, lint: &'static Lint, msg: &str) {
440         self.lookup_and_emit(lint, None, msg);
441     }
442
443     /// Merge the lints specified by any lint attributes into the
444     /// current lint context, call the provided function, then reset the
445     /// lints in effect to their previous state.
446     fn with_lint_attrs<F>(&mut self,
447                           attrs: &[ast::Attribute],
448                           f: F)
449         where F: FnOnce(&mut Self),
450     {
451         // Parse all of the lint attributes, and then add them all to the
452         // current dictionary of lint information. Along the way, keep a history
453         // of what we changed so we can roll everything back after invoking the
454         // specified closure
455         let mut pushed = 0;
456
457         for result in gather_attrs(attrs) {
458             let v = match result {
459                 Err(span) => {
460                     span_err!(self.sess(), span, E0452,
461                               "malformed lint attribute");
462                     continue;
463                 }
464                 Ok((lint_name, level, span)) => {
465                     match self.lints().find_lint(&lint_name, &self.sess(), Some(span)) {
466                         Ok(lint_id) => vec![(lint_id, level, span)],
467                         Err(FindLintError::NotFound) => {
468                             match self.lints().lint_groups.get(&lint_name[..]) {
469                                 Some(&(ref v, _)) => v.iter()
470                                                       .map(|lint_id: &LintId|
471                                                            (*lint_id, level, span))
472                                                       .collect(),
473                                 None => {
474                                     self.span_lint(builtin::UNKNOWN_LINTS, span,
475                                                    &format!("unknown `{}` attribute: `{}`",
476                                                             level.as_str(), lint_name));
477                                     continue;
478                                 }
479                             }
480                         },
481                         Err(FindLintError::Removed) => { continue; }
482                     }
483                 }
484             };
485
486             for (lint_id, level, span) in v {
487                 let now = self.lints().get_level_source(lint_id).0;
488                 if now == Forbid && level != Forbid {
489                     let lint_name = lint_id.as_str();
490                     span_err!(self.sess(), span, E0453,
491                               "{}({}) overruled by outer forbid({})",
492                               level.as_str(), lint_name,
493                               lint_name);
494                 } else if now != level {
495                     let src = self.lints().get_level_source(lint_id).1;
496                     self.level_stack().push((lint_id, (now, src)));
497                     pushed += 1;
498                     self.mut_lints().set_level(lint_id, (level, Node(span)));
499                 }
500             }
501         }
502
503         self.enter_attrs(attrs);
504         f(self);
505         self.exit_attrs(attrs);
506
507         // rollback
508         for _ in 0..pushed {
509             let (lint, lvlsrc) = self.level_stack().pop().unwrap();
510             self.mut_lints().set_level(lint, lvlsrc);
511         }
512     }
513 }
514
515
516 impl<'a> EarlyContext<'a> {
517     fn new(sess: &'a Session,
518            krate: &'a ast::Crate) -> EarlyContext<'a> {
519         // We want to own the lint store, so move it out of the session. Remember
520         // to put it back later...
521         let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
522                                       LintStore::new());
523         EarlyContext {
524             sess: sess,
525             krate: krate,
526             lints: lint_store,
527             level_stack: vec![],
528         }
529     }
530
531     fn visit_ids<F>(&mut self, f: F)
532         where F: FnOnce(&mut ast_util::IdVisitor<EarlyContext>)
533     {
534         let mut v = ast_util::IdVisitor {
535             operation: self,
536             pass_through_items: false,
537             visited_outermost: false,
538         };
539         f(&mut v);
540     }
541 }
542
543 impl<'a, 'tcx> LateContext<'a, 'tcx> {
544     fn new(tcx: &'a ty::ctxt<'tcx>,
545            krate: &'a hir::Crate,
546            exported_items: &'a ExportedItems) -> LateContext<'a, 'tcx> {
547         // We want to own the lint store, so move it out of the session.
548         let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
549                                       LintStore::new());
550
551         LateContext {
552             tcx: tcx,
553             krate: krate,
554             exported_items: exported_items,
555             lints: lint_store,
556             level_stack: vec![],
557             node_levels: RefCell::new(FnvHashMap()),
558         }
559     }
560
561     fn visit_ids<F>(&mut self, f: F)
562         where F: FnOnce(&mut util::IdVisitor<LateContext>)
563     {
564         let mut v = util::IdVisitor {
565             operation: self,
566             pass_through_items: false,
567             visited_outermost: false,
568         };
569         f(&mut v);
570     }
571 }
572
573 impl<'a, 'tcx> LintContext for LateContext<'a, 'tcx> {
574     /// Get the overall compiler `Session` object.
575     fn sess(&self) -> &Session {
576         &self.tcx.sess
577     }
578
579     fn lints(&self) -> &LintStore {
580         &self.lints
581     }
582
583     fn mut_lints(&mut self) -> &mut LintStore {
584         &mut self.lints
585     }
586
587     fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
588         &mut self.level_stack
589     }
590
591     fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
592         run_lints!(self, enter_lint_attrs, late_passes, attrs);
593     }
594
595     fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
596         run_lints!(self, exit_lint_attrs, late_passes, attrs);
597     }
598 }
599
600 impl<'a> LintContext for EarlyContext<'a> {
601     /// Get the overall compiler `Session` object.
602     fn sess(&self) -> &Session {
603         &self.sess
604     }
605
606     fn lints(&self) -> &LintStore {
607         &self.lints
608     }
609
610     fn mut_lints(&mut self) -> &mut LintStore {
611         &mut self.lints
612     }
613
614     fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
615         &mut self.level_stack
616     }
617
618     fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
619         run_lints!(self, enter_lint_attrs, early_passes, attrs);
620     }
621
622     fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
623         run_lints!(self, exit_lint_attrs, early_passes, attrs);
624     }
625 }
626
627 impl<'a, 'tcx, 'v> hir_visit::Visitor<'v> for LateContext<'a, 'tcx> {
628     fn visit_item(&mut self, it: &hir::Item) {
629         self.with_lint_attrs(&it.attrs, |cx| {
630             run_lints!(cx, check_item, late_passes, it);
631             cx.visit_ids(|v| v.visit_item(it));
632             hir_visit::walk_item(cx, it);
633         })
634     }
635
636     fn visit_foreign_item(&mut self, it: &hir::ForeignItem) {
637         self.with_lint_attrs(&it.attrs, |cx| {
638             run_lints!(cx, check_foreign_item, late_passes, it);
639             hir_visit::walk_foreign_item(cx, it);
640         })
641     }
642
643     fn visit_pat(&mut self, p: &hir::Pat) {
644         run_lints!(self, check_pat, late_passes, p);
645         hir_visit::walk_pat(self, p);
646     }
647
648     fn visit_expr(&mut self, e: &hir::Expr) {
649         run_lints!(self, check_expr, late_passes, e);
650         hir_visit::walk_expr(self, e);
651     }
652
653     fn visit_stmt(&mut self, s: &hir::Stmt) {
654         run_lints!(self, check_stmt, late_passes, s);
655         hir_visit::walk_stmt(self, s);
656     }
657
658     fn visit_fn(&mut self, fk: hir_visit::FnKind<'v>, decl: &'v hir::FnDecl,
659                 body: &'v hir::Block, span: Span, id: ast::NodeId) {
660         run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
661         hir_visit::walk_fn(self, fk, decl, body, span);
662     }
663
664     fn visit_struct_def(&mut self,
665                         s: &hir::StructDef,
666                         name: ast::Name,
667                         g: &hir::Generics,
668                         id: ast::NodeId) {
669         run_lints!(self, check_struct_def, late_passes, s, name, g, id);
670         hir_visit::walk_struct_def(self, s);
671         run_lints!(self, check_struct_def_post, late_passes, s, name, g, id);
672     }
673
674     fn visit_struct_field(&mut self, s: &hir::StructField) {
675         self.with_lint_attrs(&s.node.attrs, |cx| {
676             run_lints!(cx, check_struct_field, late_passes, s);
677             hir_visit::walk_struct_field(cx, s);
678         })
679     }
680
681     fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics) {
682         self.with_lint_attrs(&v.node.attrs, |cx| {
683             run_lints!(cx, check_variant, late_passes, v, g);
684             hir_visit::walk_variant(cx, v, g);
685             run_lints!(cx, check_variant_post, late_passes, v, g);
686         })
687     }
688
689     fn visit_ty(&mut self, t: &hir::Ty) {
690         run_lints!(self, check_ty, late_passes, t);
691         hir_visit::walk_ty(self, t);
692     }
693
694     fn visit_name(&mut self, sp: Span, name: ast::Name) {
695         run_lints!(self, check_name, late_passes, sp, name);
696     }
697
698     fn visit_mod(&mut self, m: &hir::Mod, s: Span, n: ast::NodeId) {
699         run_lints!(self, check_mod, late_passes, m, s, n);
700         hir_visit::walk_mod(self, m);
701     }
702
703     fn visit_local(&mut self, l: &hir::Local) {
704         run_lints!(self, check_local, late_passes, l);
705         hir_visit::walk_local(self, l);
706     }
707
708     fn visit_block(&mut self, b: &hir::Block) {
709         run_lints!(self, check_block, late_passes, b);
710         hir_visit::walk_block(self, b);
711     }
712
713     fn visit_arm(&mut self, a: &hir::Arm) {
714         run_lints!(self, check_arm, late_passes, a);
715         hir_visit::walk_arm(self, a);
716     }
717
718     fn visit_decl(&mut self, d: &hir::Decl) {
719         run_lints!(self, check_decl, late_passes, d);
720         hir_visit::walk_decl(self, d);
721     }
722
723     fn visit_expr_post(&mut self, e: &hir::Expr) {
724         run_lints!(self, check_expr_post, late_passes, e);
725     }
726
727     fn visit_generics(&mut self, g: &hir::Generics) {
728         run_lints!(self, check_generics, late_passes, g);
729         hir_visit::walk_generics(self, g);
730     }
731
732     fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
733         self.with_lint_attrs(&trait_item.attrs, |cx| {
734             run_lints!(cx, check_trait_item, late_passes, trait_item);
735             cx.visit_ids(|v| v.visit_trait_item(trait_item));
736             hir_visit::walk_trait_item(cx, trait_item);
737         });
738     }
739
740     fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
741         self.with_lint_attrs(&impl_item.attrs, |cx| {
742             run_lints!(cx, check_impl_item, late_passes, impl_item);
743             cx.visit_ids(|v| v.visit_impl_item(impl_item));
744             hir_visit::walk_impl_item(cx, impl_item);
745         });
746     }
747
748     fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<hir::Lifetime>) {
749         run_lints!(self, check_opt_lifetime_ref, late_passes, sp, lt);
750     }
751
752     fn visit_lifetime_ref(&mut self, lt: &hir::Lifetime) {
753         run_lints!(self, check_lifetime_ref, late_passes, lt);
754     }
755
756     fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) {
757         run_lints!(self, check_lifetime_def, late_passes, lt);
758     }
759
760     fn visit_explicit_self(&mut self, es: &hir::ExplicitSelf) {
761         run_lints!(self, check_explicit_self, late_passes, es);
762         hir_visit::walk_explicit_self(self, es);
763     }
764
765     fn visit_path(&mut self, p: &hir::Path, id: ast::NodeId) {
766         run_lints!(self, check_path, late_passes, p, id);
767         hir_visit::walk_path(self, p);
768     }
769
770     fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
771         run_lints!(self, check_path_list_item, late_passes, item);
772         hir_visit::walk_path_list_item(self, prefix, item);
773     }
774
775     fn visit_attribute(&mut self, attr: &ast::Attribute) {
776         run_lints!(self, check_attribute, late_passes, attr);
777     }
778 }
779
780 impl<'a, 'v> ast_visit::Visitor<'v> for EarlyContext<'a> {
781     fn visit_item(&mut self, it: &ast::Item) {
782         self.with_lint_attrs(&it.attrs, |cx| {
783             run_lints!(cx, check_item, early_passes, it);
784             cx.visit_ids(|v| v.visit_item(it));
785             ast_visit::walk_item(cx, it);
786         })
787     }
788
789     fn visit_foreign_item(&mut self, it: &ast::ForeignItem) {
790         self.with_lint_attrs(&it.attrs, |cx| {
791             run_lints!(cx, check_foreign_item, early_passes, it);
792             ast_visit::walk_foreign_item(cx, it);
793         })
794     }
795
796     fn visit_pat(&mut self, p: &ast::Pat) {
797         run_lints!(self, check_pat, early_passes, p);
798         ast_visit::walk_pat(self, p);
799     }
800
801     fn visit_expr(&mut self, e: &ast::Expr) {
802         run_lints!(self, check_expr, early_passes, e);
803         ast_visit::walk_expr(self, e);
804     }
805
806     fn visit_stmt(&mut self, s: &ast::Stmt) {
807         run_lints!(self, check_stmt, early_passes, s);
808         ast_visit::walk_stmt(self, s);
809     }
810
811     fn visit_fn(&mut self, fk: ast_visit::FnKind<'v>, decl: &'v ast::FnDecl,
812                 body: &'v ast::Block, span: Span, id: ast::NodeId) {
813         run_lints!(self, check_fn, early_passes, fk, decl, body, span, id);
814         ast_visit::walk_fn(self, fk, decl, body, span);
815     }
816
817     fn visit_struct_def(&mut self,
818                         s: &ast::StructDef,
819                         ident: ast::Ident,
820                         g: &ast::Generics,
821                         id: ast::NodeId) {
822         run_lints!(self, check_struct_def, early_passes, s, ident, g, id);
823         ast_visit::walk_struct_def(self, s);
824         run_lints!(self, check_struct_def_post, early_passes, s, ident, g, id);
825     }
826
827     fn visit_struct_field(&mut self, s: &ast::StructField) {
828         self.with_lint_attrs(&s.node.attrs, |cx| {
829             run_lints!(cx, check_struct_field, early_passes, s);
830             ast_visit::walk_struct_field(cx, s);
831         })
832     }
833
834     fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
835         self.with_lint_attrs(&v.node.attrs, |cx| {
836             run_lints!(cx, check_variant, early_passes, v, g);
837             ast_visit::walk_variant(cx, v, g);
838             run_lints!(cx, check_variant_post, early_passes, v, g);
839         })
840     }
841
842     fn visit_ty(&mut self, t: &ast::Ty) {
843         run_lints!(self, check_ty, early_passes, t);
844         ast_visit::walk_ty(self, t);
845     }
846
847     fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
848         run_lints!(self, check_ident, early_passes, sp, id);
849     }
850
851     fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId) {
852         run_lints!(self, check_mod, early_passes, m, s, n);
853         ast_visit::walk_mod(self, m);
854     }
855
856     fn visit_local(&mut self, l: &ast::Local) {
857         run_lints!(self, check_local, early_passes, l);
858         ast_visit::walk_local(self, l);
859     }
860
861     fn visit_block(&mut self, b: &ast::Block) {
862         run_lints!(self, check_block, early_passes, b);
863         ast_visit::walk_block(self, b);
864     }
865
866     fn visit_arm(&mut self, a: &ast::Arm) {
867         run_lints!(self, check_arm, early_passes, a);
868         ast_visit::walk_arm(self, a);
869     }
870
871     fn visit_decl(&mut self, d: &ast::Decl) {
872         run_lints!(self, check_decl, early_passes, d);
873         ast_visit::walk_decl(self, d);
874     }
875
876     fn visit_expr_post(&mut self, e: &ast::Expr) {
877         run_lints!(self, check_expr_post, early_passes, e);
878     }
879
880     fn visit_generics(&mut self, g: &ast::Generics) {
881         run_lints!(self, check_generics, early_passes, g);
882         ast_visit::walk_generics(self, g);
883     }
884
885     fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
886         self.with_lint_attrs(&trait_item.attrs, |cx| {
887             run_lints!(cx, check_trait_item, early_passes, trait_item);
888             cx.visit_ids(|v| v.visit_trait_item(trait_item));
889             ast_visit::walk_trait_item(cx, trait_item);
890         });
891     }
892
893     fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
894         self.with_lint_attrs(&impl_item.attrs, |cx| {
895             run_lints!(cx, check_impl_item, early_passes, impl_item);
896             cx.visit_ids(|v| v.visit_impl_item(impl_item));
897             ast_visit::walk_impl_item(cx, impl_item);
898         });
899     }
900
901     fn visit_lifetime(&mut self, lt: &ast::Lifetime) {
902         run_lints!(self, check_lifetime, early_passes, lt);
903     }
904
905     fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) {
906         run_lints!(self, check_lifetime_def, early_passes, lt);
907     }
908
909     fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf) {
910         run_lints!(self, check_explicit_self, early_passes, es);
911         ast_visit::walk_explicit_self(self, es);
912     }
913
914     fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId) {
915         run_lints!(self, check_path, early_passes, p, id);
916         ast_visit::walk_path(self, p);
917     }
918
919     fn visit_path_list_item(&mut self, prefix: &ast::Path, item: &ast::PathListItem) {
920         run_lints!(self, check_path_list_item, early_passes, item);
921         ast_visit::walk_path_list_item(self, prefix, item);
922     }
923
924     fn visit_attribute(&mut self, attr: &ast::Attribute) {
925         run_lints!(self, check_attribute, early_passes, attr);
926     }
927 }
928
929 // Output any lints that were previously added to the session.
930 impl<'a, 'tcx> IdVisitingOperation for LateContext<'a, 'tcx> {
931     fn visit_id(&mut self, id: ast::NodeId) {
932         match self.sess().lints.borrow_mut().remove(&id) {
933             None => {}
934             Some(lints) => {
935                 for (lint_id, span, msg) in lints {
936                     self.span_lint(lint_id.lint, span, &msg[..])
937                 }
938             }
939         }
940     }
941 }
942 impl<'a> IdVisitingOperation for EarlyContext<'a> {
943     fn visit_id(&mut self, id: ast::NodeId) {
944         match self.sess.lints.borrow_mut().remove(&id) {
945             None => {}
946             Some(lints) => {
947                 for (lint_id, span, msg) in lints {
948                     self.span_lint(lint_id.lint, span, &msg[..])
949                 }
950             }
951         }
952     }
953 }
954
955 // This lint pass is defined here because it touches parts of the `LateContext`
956 // that we don't want to expose. It records the lint level at certain AST
957 // nodes, so that the variant size difference check in trans can call
958 // `raw_emit_lint`.
959
960 pub struct GatherNodeLevels;
961
962 impl LintPass for GatherNodeLevels {
963     fn get_lints(&self) -> LintArray {
964         lint_array!()
965     }
966 }
967
968 impl LateLintPass for GatherNodeLevels {
969     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
970         match it.node {
971             hir::ItemEnum(..) => {
972                 let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCES);
973                 let lvlsrc = cx.lints.get_level_source(lint_id);
974                 match lvlsrc {
975                     (lvl, _) if lvl != Allow => {
976                         cx.node_levels.borrow_mut()
977                             .insert((it.id, lint_id), lvlsrc);
978                     },
979                     _ => { }
980                 }
981             },
982             _ => { }
983         }
984     }
985 }
986
987 /// Perform lint checking on a crate.
988 ///
989 /// Consumes the `lint_store` field of the `Session`.
990 pub fn check_crate(tcx: &ty::ctxt,
991                    krate: &hir::Crate,
992                    exported_items: &ExportedItems) {
993
994     let mut cx = LateContext::new(tcx, krate, exported_items);
995
996     // Visit the whole crate.
997     cx.with_lint_attrs(&krate.attrs, |cx| {
998         cx.visit_id(ast::CRATE_NODE_ID);
999         cx.visit_ids(|v| {
1000             v.visited_outermost = true;
1001             hir_visit::walk_crate(v, krate);
1002         });
1003
1004         // since the root module isn't visited as an item (because it isn't an
1005         // item), warn for it here.
1006         run_lints!(cx, check_crate, late_passes, krate);
1007
1008         hir_visit::walk_crate(cx, krate);
1009     });
1010
1011     // If we missed any lints added to the session, then there's a bug somewhere
1012     // in the iteration code.
1013     for (id, v) in tcx.sess.lints.borrow().iter() {
1014         for &(lint, span, ref msg) in v {
1015             tcx.sess.span_bug(span,
1016                               &format!("unprocessed lint {} at {}: {}",
1017                                        lint.as_str(), tcx.map.node_to_string(*id), *msg))
1018         }
1019     }
1020
1021     *tcx.node_lint_levels.borrow_mut() = cx.node_levels.into_inner();
1022 }
1023
1024 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1025     let mut cx = EarlyContext::new(sess, krate);
1026
1027     // Visit the whole crate.
1028     cx.with_lint_attrs(&krate.attrs, |cx| {
1029         cx.visit_id(ast::CRATE_NODE_ID);
1030         cx.visit_ids(|v| {
1031             v.visited_outermost = true;
1032             ast_visit::walk_crate(v, krate);
1033         });
1034
1035         // since the root module isn't visited as an item (because it isn't an
1036         // item), warn for it here.
1037         run_lints!(cx, check_crate, early_passes, krate);
1038
1039         ast_visit::walk_crate(cx, krate);
1040     });
1041
1042     // Put the lint store back in the session.
1043     mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1044
1045     // If we missed any lints added to the session, then there's a bug somewhere
1046     // in the iteration code.
1047     for (_, v) in sess.lints.borrow().iter() {
1048         for &(lint, span, ref msg) in v {
1049             sess.span_bug(span,
1050                           &format!("unprocessed lint {}: {}",
1051                                    lint.as_str(), *msg))
1052         }
1053     }
1054 }