]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/context.rs
fe88401a24c2007f2c1585e32cdf835d2da5e6a4
[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: &[hir::Attribute]);
412     fn exit_attrs(&mut self, attrs: &[hir::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     fn with_ast_lint_attrs<F>(&mut self,
515                           attrs: &[ast::Attribute],
516                           f: F)
517         where F: FnOnce(&mut Self),
518     {
519         self.with_lint_attrs(&lower_attrs(attrs), f)
520     }
521 }
522
523
524 impl<'a> EarlyContext<'a> {
525     fn new(sess: &'a Session,
526            krate: &'a ast::Crate) -> EarlyContext<'a> {
527         // We want to own the lint store, so move it out of the session. Remember
528         // to put it back later...
529         let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
530                                       LintStore::new());
531         EarlyContext {
532             sess: sess,
533             krate: krate,
534             lints: lint_store,
535             level_stack: vec![],
536         }
537     }
538
539     fn visit_ids<F>(&mut self, f: F)
540         where F: FnOnce(&mut ast_util::IdVisitor<EarlyContext>)
541     {
542         let mut v = ast_util::IdVisitor {
543             operation: self,
544             pass_through_items: false,
545             visited_outermost: false,
546         };
547         f(&mut v);
548     }
549 }
550
551 impl<'a, 'tcx> LateContext<'a, 'tcx> {
552     fn new(tcx: &'a ty::ctxt<'tcx>,
553            krate: &'a hir::Crate,
554            exported_items: &'a ExportedItems) -> LateContext<'a, 'tcx> {
555         // We want to own the lint store, so move it out of the session.
556         let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
557                                       LintStore::new());
558
559         LateContext {
560             tcx: tcx,
561             krate: krate,
562             exported_items: exported_items,
563             lints: lint_store,
564             level_stack: vec![],
565             node_levels: RefCell::new(FnvHashMap()),
566         }
567     }
568
569     fn visit_ids<F>(&mut self, f: F)
570         where F: FnOnce(&mut util::IdVisitor<LateContext>)
571     {
572         let mut v = util::IdVisitor {
573             operation: self,
574             pass_through_items: false,
575             visited_outermost: false,
576         };
577         f(&mut v);
578     }
579 }
580
581 impl<'a, 'tcx> LintContext for LateContext<'a, 'tcx> {
582     /// Get the overall compiler `Session` object.
583     fn sess(&self) -> &Session {
584         &self.tcx.sess
585     }
586
587     fn lints(&self) -> &LintStore {
588         &self.lints
589     }
590
591     fn mut_lints(&mut self) -> &mut LintStore {
592         &mut self.lints
593     }
594
595     fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
596         &mut self.level_stack
597     }
598
599     fn enter_attrs(&mut self, attrs: &[hir::Attribute]) {
600         run_lints!(self, enter_lint_attrs, late_passes, attrs);
601     }
602
603     fn exit_attrs(&mut self, attrs: &[hir::Attribute]) {
604         run_lints!(self, exit_lint_attrs, late_passes, attrs);
605     }
606 }
607
608 impl<'a> LintContext for EarlyContext<'a> {
609     /// Get the overall compiler `Session` object.
610     fn sess(&self) -> &Session {
611         &self.sess
612     }
613
614     fn lints(&self) -> &LintStore {
615         &self.lints
616     }
617
618     fn mut_lints(&mut self) -> &mut LintStore {
619         &mut self.lints
620     }
621
622     fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
623         &mut self.level_stack
624     }
625
626     fn enter_attrs(&mut self, attrs: &[hir::Attribute]) {
627         run_lints!(self, enter_lint_attrs, early_passes, attrs);
628     }
629
630     fn exit_attrs(&mut self, attrs: &[hir::Attribute]) {
631         run_lints!(self, exit_lint_attrs, early_passes, attrs);
632     }
633 }
634
635 impl<'a, 'tcx, 'v> hir_visit::Visitor<'v> for LateContext<'a, 'tcx> {
636     fn visit_item(&mut self, it: &hir::Item) {
637         self.with_lint_attrs(&it.attrs, |cx| {
638             run_lints!(cx, check_item, late_passes, it);
639             cx.visit_ids(|v| v.visit_item(it));
640             hir_visit::walk_item(cx, it);
641         })
642     }
643
644     fn visit_foreign_item(&mut self, it: &hir::ForeignItem) {
645         self.with_lint_attrs(&it.attrs, |cx| {
646             run_lints!(cx, check_foreign_item, late_passes, it);
647             hir_visit::walk_foreign_item(cx, it);
648         })
649     }
650
651     fn visit_pat(&mut self, p: &hir::Pat) {
652         run_lints!(self, check_pat, late_passes, p);
653         hir_visit::walk_pat(self, p);
654     }
655
656     fn visit_expr(&mut self, e: &hir::Expr) {
657         run_lints!(self, check_expr, late_passes, e);
658         hir_visit::walk_expr(self, e);
659     }
660
661     fn visit_stmt(&mut self, s: &hir::Stmt) {
662         run_lints!(self, check_stmt, late_passes, s);
663         hir_visit::walk_stmt(self, s);
664     }
665
666     fn visit_fn(&mut self, fk: hir_visit::FnKind<'v>, decl: &'v hir::FnDecl,
667                 body: &'v hir::Block, span: Span, id: ast::NodeId) {
668         run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
669         hir_visit::walk_fn(self, fk, decl, body, span);
670     }
671
672     fn visit_struct_def(&mut self,
673                         s: &hir::StructDef,
674                         ident: ast::Ident,
675                         g: &hir::Generics,
676                         id: ast::NodeId) {
677         run_lints!(self, check_struct_def, late_passes, s, ident, g, id);
678         hir_visit::walk_struct_def(self, s);
679         run_lints!(self, check_struct_def_post, late_passes, s, ident, g, id);
680     }
681
682     fn visit_struct_field(&mut self, s: &hir::StructField) {
683         self.with_lint_attrs(&s.node.attrs, |cx| {
684             run_lints!(cx, check_struct_field, late_passes, s);
685             hir_visit::walk_struct_field(cx, s);
686         })
687     }
688
689     fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics) {
690         self.with_lint_attrs(&v.node.attrs, |cx| {
691             run_lints!(cx, check_variant, late_passes, v, g);
692             hir_visit::walk_variant(cx, v, g);
693             run_lints!(cx, check_variant_post, late_passes, v, g);
694         })
695     }
696
697     fn visit_ty(&mut self, t: &hir::Ty) {
698         run_lints!(self, check_ty, late_passes, t);
699         hir_visit::walk_ty(self, t);
700     }
701
702     fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
703         run_lints!(self, check_ident, late_passes, sp, id);
704     }
705
706     fn visit_mod(&mut self, m: &hir::Mod, s: Span, n: ast::NodeId) {
707         run_lints!(self, check_mod, late_passes, m, s, n);
708         hir_visit::walk_mod(self, m);
709     }
710
711     fn visit_local(&mut self, l: &hir::Local) {
712         run_lints!(self, check_local, late_passes, l);
713         hir_visit::walk_local(self, l);
714     }
715
716     fn visit_block(&mut self, b: &hir::Block) {
717         run_lints!(self, check_block, late_passes, b);
718         hir_visit::walk_block(self, b);
719     }
720
721     fn visit_arm(&mut self, a: &hir::Arm) {
722         run_lints!(self, check_arm, late_passes, a);
723         hir_visit::walk_arm(self, a);
724     }
725
726     fn visit_decl(&mut self, d: &hir::Decl) {
727         run_lints!(self, check_decl, late_passes, d);
728         hir_visit::walk_decl(self, d);
729     }
730
731     fn visit_expr_post(&mut self, e: &hir::Expr) {
732         run_lints!(self, check_expr_post, late_passes, e);
733     }
734
735     fn visit_generics(&mut self, g: &hir::Generics) {
736         run_lints!(self, check_generics, late_passes, g);
737         hir_visit::walk_generics(self, g);
738     }
739
740     fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
741         self.with_lint_attrs(&trait_item.attrs, |cx| {
742             run_lints!(cx, check_trait_item, late_passes, trait_item);
743             cx.visit_ids(|v| v.visit_trait_item(trait_item));
744             hir_visit::walk_trait_item(cx, trait_item);
745         });
746     }
747
748     fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
749         self.with_lint_attrs(&impl_item.attrs, |cx| {
750             run_lints!(cx, check_impl_item, late_passes, impl_item);
751             cx.visit_ids(|v| v.visit_impl_item(impl_item));
752             hir_visit::walk_impl_item(cx, impl_item);
753         });
754     }
755
756     fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<hir::Lifetime>) {
757         run_lints!(self, check_opt_lifetime_ref, late_passes, sp, lt);
758     }
759
760     fn visit_lifetime_ref(&mut self, lt: &hir::Lifetime) {
761         run_lints!(self, check_lifetime_ref, late_passes, lt);
762     }
763
764     fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) {
765         run_lints!(self, check_lifetime_def, late_passes, lt);
766     }
767
768     fn visit_explicit_self(&mut self, es: &hir::ExplicitSelf) {
769         run_lints!(self, check_explicit_self, late_passes, es);
770         hir_visit::walk_explicit_self(self, es);
771     }
772
773     fn visit_path(&mut self, p: &hir::Path, id: ast::NodeId) {
774         run_lints!(self, check_path, late_passes, p, id);
775         hir_visit::walk_path(self, p);
776     }
777
778     fn visit_attribute(&mut self, attr: &ast::Attribute) {
779         run_lints!(self, check_attribute, late_passes, attr);
780     }
781 }
782
783 impl<'a, 'v> ast_visit::Visitor<'v> for EarlyContext<'a> {
784     fn visit_item(&mut self, it: &ast::Item) {
785         self.with_ast_lint_attrs(&it.attrs, |cx| {
786             run_lints!(cx, check_item, early_passes, it);
787             cx.visit_ids(|v| v.visit_item(it));
788             ast_visit::walk_item(cx, it);
789         })
790     }
791
792     fn visit_foreign_item(&mut self, it: &ast::ForeignItem) {
793         self.with_ast_lint_attrs(&it.attrs, |cx| {
794             run_lints!(cx, check_foreign_item, early_passes, it);
795             ast_visit::walk_foreign_item(cx, it);
796         })
797     }
798
799     fn visit_pat(&mut self, p: &ast::Pat) {
800         run_lints!(self, check_pat, early_passes, p);
801         ast_visit::walk_pat(self, p);
802     }
803
804     fn visit_expr(&mut self, e: &ast::Expr) {
805         run_lints!(self, check_expr, early_passes, e);
806         ast_visit::walk_expr(self, e);
807     }
808
809     fn visit_stmt(&mut self, s: &ast::Stmt) {
810         run_lints!(self, check_stmt, early_passes, s);
811         ast_visit::walk_stmt(self, s);
812     }
813
814     fn visit_fn(&mut self, fk: ast_visit::FnKind<'v>, decl: &'v ast::FnDecl,
815                 body: &'v ast::Block, span: Span, id: ast::NodeId) {
816         run_lints!(self, check_fn, early_passes, fk, decl, body, span, id);
817         ast_visit::walk_fn(self, fk, decl, body, span);
818     }
819
820     fn visit_struct_def(&mut self,
821                         s: &ast::StructDef,
822                         ident: ast::Ident,
823                         g: &ast::Generics,
824                         id: ast::NodeId) {
825         run_lints!(self, check_struct_def, early_passes, s, ident, g, id);
826         ast_visit::walk_struct_def(self, s);
827         run_lints!(self, check_struct_def_post, early_passes, s, ident, g, id);
828     }
829
830     fn visit_struct_field(&mut self, s: &ast::StructField) {
831         self.with_ast_lint_attrs(&s.node.attrs, |cx| {
832             run_lints!(cx, check_struct_field, early_passes, s);
833             ast_visit::walk_struct_field(cx, s);
834         })
835     }
836
837     fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
838         self.with_ast_lint_attrs(&v.node.attrs, |cx| {
839             run_lints!(cx, check_variant, early_passes, v, g);
840             ast_visit::walk_variant(cx, v, g);
841             run_lints!(cx, check_variant_post, early_passes, v, g);
842         })
843     }
844
845     fn visit_ty(&mut self, t: &ast::Ty) {
846         run_lints!(self, check_ty, early_passes, t);
847         ast_visit::walk_ty(self, t);
848     }
849
850     fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
851         run_lints!(self, check_ident, early_passes, sp, id);
852     }
853
854     fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId) {
855         run_lints!(self, check_mod, early_passes, m, s, n);
856         ast_visit::walk_mod(self, m);
857     }
858
859     fn visit_local(&mut self, l: &ast::Local) {
860         run_lints!(self, check_local, early_passes, l);
861         ast_visit::walk_local(self, l);
862     }
863
864     fn visit_block(&mut self, b: &ast::Block) {
865         run_lints!(self, check_block, early_passes, b);
866         ast_visit::walk_block(self, b);
867     }
868
869     fn visit_arm(&mut self, a: &ast::Arm) {
870         run_lints!(self, check_arm, early_passes, a);
871         ast_visit::walk_arm(self, a);
872     }
873
874     fn visit_decl(&mut self, d: &ast::Decl) {
875         run_lints!(self, check_decl, early_passes, d);
876         ast_visit::walk_decl(self, d);
877     }
878
879     fn visit_expr_post(&mut self, e: &ast::Expr) {
880         run_lints!(self, check_expr_post, early_passes, e);
881     }
882
883     fn visit_generics(&mut self, g: &ast::Generics) {
884         run_lints!(self, check_generics, early_passes, g);
885         ast_visit::walk_generics(self, g);
886     }
887
888     fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
889         self.with_ast_lint_attrs(&trait_item.attrs, |cx| {
890             run_lints!(cx, check_trait_item, early_passes, trait_item);
891             cx.visit_ids(|v| v.visit_trait_item(trait_item));
892             ast_visit::walk_trait_item(cx, trait_item);
893         });
894     }
895
896     fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
897         self.with_ast_lint_attrs(&impl_item.attrs, |cx| {
898             run_lints!(cx, check_impl_item, early_passes, impl_item);
899             cx.visit_ids(|v| v.visit_impl_item(impl_item));
900             ast_visit::walk_impl_item(cx, impl_item);
901         });
902     }
903
904     fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<ast::Lifetime>) {
905         run_lints!(self, check_opt_lifetime_ref, early_passes, sp, lt);
906     }
907
908     fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime) {
909         run_lints!(self, check_lifetime_ref, early_passes, lt);
910     }
911
912     fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) {
913         run_lints!(self, check_lifetime_def, early_passes, lt);
914     }
915
916     fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf) {
917         run_lints!(self, check_explicit_self, early_passes, es);
918         ast_visit::walk_explicit_self(self, es);
919     }
920
921     fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId) {
922         run_lints!(self, check_path, early_passes, p, id);
923         ast_visit::walk_path(self, p);
924     }
925
926     fn visit_attribute(&mut self, attr: &ast::Attribute) {
927         run_lints!(self, check_attribute, early_passes, attr);
928     }
929 }
930
931 // Output any lints that were previously added to the session.
932 impl<'a, 'tcx> IdVisitingOperation for LateContext<'a, 'tcx> {
933     fn visit_id(&mut self, id: ast::NodeId) {
934         match self.sess().lints.borrow_mut().remove(&id) {
935             None => {}
936             Some(lints) => {
937                 for (lint_id, span, msg) in lints {
938                     self.span_lint(lint_id.lint, span, &msg[..])
939                 }
940             }
941         }
942     }
943 }
944 impl<'a> IdVisitingOperation for EarlyContext<'a> {
945     fn visit_id(&mut self, id: ast::NodeId) {
946         match self.sess.lints.borrow_mut().remove(&id) {
947             None => {}
948             Some(lints) => {
949                 for (lint_id, span, msg) in lints {
950                     self.span_lint(lint_id.lint, span, &msg[..])
951                 }
952             }
953         }
954     }
955 }
956
957 // This lint pass is defined here because it touches parts of the `LateContext`
958 // that we don't want to expose. It records the lint level at certain AST
959 // nodes, so that the variant size difference check in trans can call
960 // `raw_emit_lint`.
961
962 pub struct GatherNodeLevels;
963
964 impl LintPass for GatherNodeLevels {
965     fn get_lints(&self) -> LintArray {
966         lint_array!()
967     }
968 }
969
970 impl LateLintPass for GatherNodeLevels {
971     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
972         match it.node {
973             hir::ItemEnum(..) => {
974                 let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCES);
975                 let lvlsrc = cx.lints.get_level_source(lint_id);
976                 match lvlsrc {
977                     (lvl, _) if lvl != Allow => {
978                         cx.node_levels.borrow_mut()
979                             .insert((it.id, lint_id), lvlsrc);
980                     },
981                     _ => { }
982                 }
983             },
984             _ => { }
985         }
986     }
987 }
988
989 /// Perform lint checking on a crate.
990 ///
991 /// Consumes the `lint_store` field of the `Session`.
992 pub fn check_crate(tcx: &ty::ctxt,
993                    krate: &hir::Crate,
994                    exported_items: &ExportedItems) {
995
996     let mut cx = LateContext::new(tcx, krate, exported_items);
997
998     // Visit the whole crate.
999     cx.with_lint_attrs(&krate.attrs, |cx| {
1000         cx.visit_id(ast::CRATE_NODE_ID);
1001         cx.visit_ids(|v| {
1002             v.visited_outermost = true;
1003             hir_visit::walk_crate(v, krate);
1004         });
1005
1006         // since the root module isn't visited as an item (because it isn't an
1007         // item), warn for it here.
1008         run_lints!(cx, check_crate, late_passes, krate);
1009
1010         hir_visit::walk_crate(cx, krate);
1011     });
1012
1013     // If we missed any lints added to the session, then there's a bug somewhere
1014     // in the iteration code.
1015     for (id, v) in tcx.sess.lints.borrow().iter() {
1016         for &(lint, span, ref msg) in v {
1017             tcx.sess.span_bug(span,
1018                               &format!("unprocessed lint {} at {}: {}",
1019                                        lint.as_str(), tcx.map.node_to_string(*id), *msg))
1020         }
1021     }
1022
1023     *tcx.node_lint_levels.borrow_mut() = cx.node_levels.into_inner();
1024 }
1025
1026 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1027     let mut cx = EarlyContext::new(sess, krate);
1028
1029     // Visit the whole crate.
1030     cx.with_ast_lint_attrs(&krate.attrs, |cx| {
1031         cx.visit_id(ast::CRATE_NODE_ID);
1032         cx.visit_ids(|v| {
1033             v.visited_outermost = true;
1034             ast_visit::walk_crate(v, krate);
1035         });
1036
1037         // since the root module isn't visited as an item (because it isn't an
1038         // item), warn for it here.
1039         run_lints!(cx, check_crate, early_passes, krate);
1040
1041         ast_visit::walk_crate(cx, krate);
1042     });
1043
1044     // Put the lint store back in the session.
1045     mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1046
1047     // If we missed any lints added to the session, then there's a bug somewhere
1048     // in the iteration code.
1049     for (_, v) in sess.lints.borrow().iter() {
1050         for &(lint, span, ref msg) in v {
1051             sess.span_bug(span,
1052                           &format!("unprocessed lint {}: {}",
1053                                    lint.as_str(), *msg))
1054         }
1055     }
1056 }