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: &[ast::Attribute]);
412 fn exit_attrs(&mut self, attrs: &[ast::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);
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(),
531 fn visit_ids<F>(&mut self, f: F)
532 where F: FnOnce(&mut ast_util::IdVisitor<EarlyContext>)
534 let mut v = ast_util::IdVisitor {
536 pass_through_items: false,
537 visited_outermost: false,
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(),
554 exported_items: exported_items,
557 node_levels: RefCell::new(FnvHashMap()),
561 fn visit_ids<F>(&mut self, f: F)
562 where F: FnOnce(&mut util::IdVisitor<LateContext>)
564 let mut v = util::IdVisitor {
566 pass_through_items: false,
567 visited_outermost: false,
573 impl<'a, 'tcx> LintContext for LateContext<'a, 'tcx> {
574 /// Get the overall compiler `Session` object.
575 fn sess(&self) -> &Session {
579 fn lints(&self) -> &LintStore {
583 fn mut_lints(&mut self) -> &mut LintStore {
587 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
588 &mut self.level_stack
591 fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
592 run_lints!(self, enter_lint_attrs, late_passes, attrs);
595 fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
596 run_lints!(self, exit_lint_attrs, late_passes, attrs);
600 impl<'a> LintContext for EarlyContext<'a> {
601 /// Get the overall compiler `Session` object.
602 fn sess(&self) -> &Session {
606 fn lints(&self) -> &LintStore {
610 fn mut_lints(&mut self) -> &mut LintStore {
614 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
615 &mut self.level_stack
618 fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
619 run_lints!(self, enter_lint_attrs, early_passes, attrs);
622 fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
623 run_lints!(self, exit_lint_attrs, early_passes, attrs);
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);
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);
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);
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);
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);
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);
664 fn visit_struct_def(&mut self,
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);
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);
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);
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);
694 fn visit_name(&mut self, sp: Span, name: ast::Name) {
695 run_lints!(self, check_name, late_passes, sp, name);
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);
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);
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);
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);
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);
723 fn visit_expr_post(&mut self, e: &hir::Expr) {
724 run_lints!(self, check_expr_post, late_passes, e);
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);
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);
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);
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);
752 fn visit_lifetime_ref(&mut self, lt: &hir::Lifetime) {
753 run_lints!(self, check_lifetime_ref, late_passes, lt);
756 fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) {
757 run_lints!(self, check_lifetime_def, late_passes, lt);
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);
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);
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);
775 fn visit_attribute(&mut self, attr: &ast::Attribute) {
776 run_lints!(self, check_attribute, late_passes, attr);
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);
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);
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);
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);
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);
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);
817 fn visit_struct_def(&mut self,
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);
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);
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);
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);
847 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
848 run_lints!(self, check_ident, early_passes, sp, id);
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);
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);
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);
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);
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);
876 fn visit_expr_post(&mut self, e: &ast::Expr) {
877 run_lints!(self, check_expr_post, early_passes, e);
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);
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);
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);
901 fn visit_lifetime(&mut self, lt: &ast::Lifetime) {
902 run_lints!(self, check_lifetime, early_passes, lt);
905 fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) {
906 run_lints!(self, check_lifetime_def, early_passes, lt);
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);
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);
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);
924 fn visit_attribute(&mut self, attr: &ast::Attribute) {
925 run_lints!(self, check_attribute, early_passes, attr);
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) {
935 for (lint_id, span, msg) in lints {
936 self.span_lint(lint_id.lint, span, &msg[..])
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) {
947 for (lint_id, span, msg) in lints {
948 self.span_lint(lint_id.lint, span, &msg[..])
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
960 pub struct GatherNodeLevels;
962 impl LintPass for GatherNodeLevels {
963 fn get_lints(&self) -> LintArray {
968 impl LateLintPass for GatherNodeLevels {
969 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
971 hir::ItemEnum(..) => {
972 let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCES);
973 let lvlsrc = cx.lints.get_level_source(lint_id);
975 (lvl, _) if lvl != Allow => {
976 cx.node_levels.borrow_mut()
977 .insert((it.id, lint_id), lvlsrc);
987 /// Perform lint checking on a crate.
989 /// Consumes the `lint_store` field of the `Session`.
990 pub fn check_crate(tcx: &ty::ctxt,
992 exported_items: &ExportedItems) {
994 let mut cx = LateContext::new(tcx, krate, exported_items);
996 // Visit the whole crate.
997 cx.with_lint_attrs(&krate.attrs, |cx| {
998 cx.visit_id(ast::CRATE_NODE_ID);
1000 v.visited_outermost = true;
1001 hir_visit::walk_crate(v, krate);
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);
1008 hir_visit::walk_crate(cx, krate);
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))
1021 *tcx.node_lint_levels.borrow_mut() = cx.node_levels.into_inner();
1024 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1025 let mut cx = EarlyContext::new(sess, krate);
1027 // Visit the whole crate.
1028 cx.with_lint_attrs(&krate.attrs, |cx| {
1029 cx.visit_id(ast::CRATE_NODE_ID);
1031 v.visited_outermost = true;
1032 ast_visit::walk_crate(v, krate);
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);
1039 ast_visit::walk_crate(cx, krate);
1042 // Put the lint store back in the session.
1043 mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
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 {
1050 &format!("unprocessed lint {}: {}",
1051 lint.as_str(), *msg))