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.
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.
11 //! Implementation of lint checking.
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.
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::*;
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};
35 use util::nodemap::FnvHashMap;
37 use std::cell::RefCell;
40 use syntax::ast_util::{self, IdVisitingOperation};
41 use syntax::attr::{self, AttrMetaMethods};
42 use syntax::codemap::Span;
43 use syntax::parse::token::InternedString;
46 use rustc_front::util;
47 use rustc_front::visit as hir_visit;
48 use syntax::visit as ast_visit;
49 use syntax::diagnostic;
51 /// Information about the registered lints.
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)>,
60 /// Trait objects for each lint pass.
61 /// This is only `None` while iterating over the objects. See the definition
63 early_passes: Option<Vec<EarlyLintPassObject>>,
64 late_passes: Option<Vec<LateLintPassObject>>,
66 /// Lints indexed by name.
67 by_name: FnvHashMap<String, TargetLint>,
69 /// Current levels of each lint, and where they were set.
70 levels: FnvHashMap<LintId, LevelSource>,
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)>,
76 /// Maximum level a lint can be
77 lint_cap: Option<Level>,
80 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
82 /// A direct lint target
85 /// Temporary renaming, used for easing migration pain; see #16545
86 Renamed(String, LintId),
88 /// Lint with this name existed previously, but has been removed/deprecated.
89 /// The string argument is the reason for removal.
99 fn get_level_source(&self, lint: LintId) -> LevelSource {
100 match self.levels.get(&lint) {
102 None => (Allow, Default),
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);
110 if lvlsrc.0 == Allow {
111 self.levels.remove(&lint);
113 self.levels.insert(lint, lvlsrc);
117 pub fn new() -> LintStore {
120 early_passes: Some(vec!()),
121 late_passes: Some(vec!()),
122 by_name: FnvHashMap(),
123 levels: FnvHashMap(),
124 lint_groups: FnvHashMap(),
129 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
133 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
134 self.lint_groups.iter().map(|(k, v)| (*k,
139 pub fn register_early_pass(&mut self,
140 sess: Option<&Session>,
142 pass: EarlyLintPassObject) {
143 self.push_pass(sess, from_plugin, &pass);
144 self.early_passes.as_mut().unwrap().push(pass);
147 pub fn register_late_pass(&mut self,
148 sess: Option<&Session>,
150 pass: LateLintPassObject) {
151 self.push_pass(sess, from_plugin, &pass);
152 self.late_passes.as_mut().unwrap().push(pass);
155 // Helper method for register_early/late_pass
156 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
157 sess: Option<&Session>,
160 for &lint in pass.get_lints() {
161 self.lints.push((*lint, from_plugin));
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[..]),
172 // A duplicate name from a plugin is a user error.
173 (Some(sess), true) => sess.err(&msg[..]),
177 if lint.default_level != Allow {
178 self.levels.insert(id, (lint.default_level, Default));
183 pub fn register_group(&mut self, sess: Option<&Session>,
184 from_plugin: bool, name: &'static str,
186 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
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[..]),
196 // A duplicate name from a plugin is a user error.
197 (Some(sess), true) => sess.err(&msg[..]),
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)
207 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
210 pub fn register_removed(&mut self, name: &str, reason: &str) {
211 self.by_name.insert(name.into(), Removed(reason.into()));
214 #[allow(unused_variables)]
215 fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
216 -> Result<LintId, FindLintError>
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);
224 Some(span) => sess.span_warn(span, &warning[..]),
225 None => sess.warn(&warning[..]),
229 Some(&Removed(ref reason)) => {
230 let warning = format!("lint {} has been removed: {}", lint_name, reason);
232 Some(span) => sess.span_warn(span, &warning[..]),
233 None => sess.warn(&warning[..])
235 Err(FindLintError::Removed)
237 None => Err(FindLintError::NotFound)
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)),
246 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
247 .collect::<FnvHashMap<&'static str,
249 .get(&lint_name[..]) {
252 .map(|lint_id: &LintId|
253 self.set_level(*lint_id, (level, CommandLine)))
254 .collect::<Vec<()>>();
256 None => sess.err(&format!("unknown {} flag: {}",
257 level.as_str(), lint_name)),
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);
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>,
277 /// The crate being checked.
278 pub krate: &'a hir::Crate,
280 /// Items exported from the crate being checked.
281 pub exported_items: &'a ExportedItems,
283 /// The store of registered lints.
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
289 level_stack: Vec<(LintId, LevelSource)>,
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>>,
296 /// Context for lint checking of the AST, after expansion, before lowering to
298 pub struct EarlyContext<'a> {
299 /// Type context we're checking in.
300 pub sess: &'a Session,
302 /// The crate being checked.
303 pub krate: &'a ast::Crate,
305 /// The store of registered lints.
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
311 level_stack: Vec<(LintId, LevelSource)>,
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),*);
322 $cx.mut_lints().$ps = Some(passes);
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!();
332 let level = match Level::from_str(&attr.name()) {
337 attr::mark_used(attr);
339 let meta = &attr.node.value;
340 let metas = match meta.node {
341 ast::MetaList(_, ref metas) => metas,
343 out.push(Err(meta.span));
349 out.push(match meta.node {
350 ast::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)),
358 /// Emit a lint as a warning or an error (or not at all)
359 /// according to `level`.
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 }
370 let name = lint.name_lower();
372 let msg = match source {
374 format!("{}, #[{}({})] on by default", msg,
375 level.as_str(), name)
378 format!("{} [-{} {}]", msg,
380 Warn => 'W', Deny => 'D', Forbid => 'F',
382 }, name.replace("_", "-"))
390 // For purposes of printing, we can treat forbid as deny.
391 if level == Forbid { level = Deny; }
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"),
401 if let Some(span) = def {
402 sess.span_note(span, "lint level defined here");
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]);
414 /// Get the level of `lint` at the current position of the lint
416 fn current_level(&self, lint: &'static Lint) -> Level {
417 self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
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)) {
423 Some(&(Warn, src)) => {
424 let lint_id = LintId::of(builtin::WARNINGS);
425 (self.lints().get_level_source(lint_id).0, src)
430 raw_emit_lint(&self.sess(), lint, (level, src), span, msg);
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);
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);
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],
449 where F: FnOnce(&mut Self),
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
457 for result in gather_attrs(attrs) {
458 let v = match result {
460 span_err!(self.sess(), span, E0452,
461 "malformed lint attribute");
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))
474 self.span_lint(builtin::UNKNOWN_LINTS, span,
475 &format!("unknown `{}` attribute: `{}`",
476 level.as_str(), lint_name));
481 Err(FindLintError::Removed) => { continue; }
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,
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)));
498 self.mut_lints().set_level(lint_id, (level, Node(span)));
503 self.enter_attrs(attrs);
505 self.exit_attrs(attrs);
509 let (lint, lvlsrc) = self.level_stack().pop().unwrap();
510 self.mut_lints().set_level(lint, lvlsrc);
514 fn with_ast_lint_attrs<F>(&mut self,
515 attrs: &[ast::Attribute],
517 where F: FnOnce(&mut Self),
519 self.with_lint_attrs(&lower_attrs(attrs), f)
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(),
539 fn visit_ids<F>(&mut self, f: F)
540 where F: FnOnce(&mut ast_util::IdVisitor<EarlyContext>)
542 let mut v = ast_util::IdVisitor {
544 pass_through_items: false,
545 visited_outermost: false,
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(),
562 exported_items: exported_items,
565 node_levels: RefCell::new(FnvHashMap()),
569 fn visit_ids<F>(&mut self, f: F)
570 where F: FnOnce(&mut util::IdVisitor<LateContext>)
572 let mut v = util::IdVisitor {
574 pass_through_items: false,
575 visited_outermost: false,
581 impl<'a, 'tcx> LintContext for LateContext<'a, 'tcx> {
582 /// Get the overall compiler `Session` object.
583 fn sess(&self) -> &Session {
587 fn lints(&self) -> &LintStore {
591 fn mut_lints(&mut self) -> &mut LintStore {
595 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
596 &mut self.level_stack
599 fn enter_attrs(&mut self, attrs: &[hir::Attribute]) {
600 run_lints!(self, enter_lint_attrs, late_passes, attrs);
603 fn exit_attrs(&mut self, attrs: &[hir::Attribute]) {
604 run_lints!(self, exit_lint_attrs, late_passes, attrs);
608 impl<'a> LintContext for EarlyContext<'a> {
609 /// Get the overall compiler `Session` object.
610 fn sess(&self) -> &Session {
614 fn lints(&self) -> &LintStore {
618 fn mut_lints(&mut self) -> &mut LintStore {
622 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
623 &mut self.level_stack
626 fn enter_attrs(&mut self, attrs: &[hir::Attribute]) {
627 run_lints!(self, enter_lint_attrs, early_passes, attrs);
630 fn exit_attrs(&mut self, attrs: &[hir::Attribute]) {
631 run_lints!(self, exit_lint_attrs, early_passes, attrs);
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);
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);
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);
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);
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);
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);
672 fn visit_struct_def(&mut self,
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);
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);
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);
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);
702 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
703 run_lints!(self, check_ident, late_passes, sp, id);
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);
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);
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);
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);
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);
731 fn visit_expr_post(&mut self, e: &hir::Expr) {
732 run_lints!(self, check_expr_post, late_passes, e);
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);
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);
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);
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);
760 fn visit_lifetime_ref(&mut self, lt: &hir::Lifetime) {
761 run_lints!(self, check_lifetime_ref, late_passes, lt);
764 fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) {
765 run_lints!(self, check_lifetime_def, late_passes, lt);
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);
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);
778 fn visit_attribute(&mut self, attr: &ast::Attribute) {
779 run_lints!(self, check_attribute, late_passes, attr);
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);
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);
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);
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);
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);
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);
820 fn visit_struct_def(&mut self,
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);
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);
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);
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);
850 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
851 run_lints!(self, check_ident, early_passes, sp, id);
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);
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);
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);
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);
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);
879 fn visit_expr_post(&mut self, e: &ast::Expr) {
880 run_lints!(self, check_expr_post, early_passes, e);
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);
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);
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);
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);
908 fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime) {
909 run_lints!(self, check_lifetime_ref, early_passes, lt);
912 fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) {
913 run_lints!(self, check_lifetime_def, early_passes, lt);
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);
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);
926 fn visit_attribute(&mut self, attr: &ast::Attribute) {
927 run_lints!(self, check_attribute, early_passes, attr);
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) {
937 for (lint_id, span, msg) in lints {
938 self.span_lint(lint_id.lint, span, &msg[..])
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) {
949 for (lint_id, span, msg) in lints {
950 self.span_lint(lint_id.lint, span, &msg[..])
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
962 pub struct GatherNodeLevels;
964 impl LintPass for GatherNodeLevels {
965 fn get_lints(&self) -> LintArray {
970 impl LateLintPass for GatherNodeLevels {
971 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
973 hir::ItemEnum(..) => {
974 let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCES);
975 let lvlsrc = cx.lints.get_level_source(lint_id);
977 (lvl, _) if lvl != Allow => {
978 cx.node_levels.borrow_mut()
979 .insert((it.id, lint_id), lvlsrc);
989 /// Perform lint checking on a crate.
991 /// Consumes the `lint_store` field of the `Session`.
992 pub fn check_crate(tcx: &ty::ctxt,
994 exported_items: &ExportedItems) {
996 let mut cx = LateContext::new(tcx, krate, exported_items);
998 // Visit the whole crate.
999 cx.with_lint_attrs(&krate.attrs, |cx| {
1000 cx.visit_id(ast::CRATE_NODE_ID);
1002 v.visited_outermost = true;
1003 hir_visit::walk_crate(v, krate);
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);
1010 hir_visit::walk_crate(cx, krate);
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))
1023 *tcx.node_lint_levels.borrow_mut() = cx.node_levels.into_inner();
1026 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1027 let mut cx = EarlyContext::new(sess, krate);
1029 // Visit the whole crate.
1030 cx.with_ast_lint_attrs(&krate.attrs, |cx| {
1031 cx.visit_id(ast::CRATE_NODE_ID);
1033 v.visited_outermost = true;
1034 ast_visit::walk_crate(v, krate);
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);
1041 ast_visit::walk_crate(cx, krate);
1044 // Put the lint store back in the session.
1045 mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
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 {
1052 &format!("unprocessed lint {}: {}",
1053 lint.as_str(), *msg))