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 dep_graph::DepNode;
29 use middle::privacy::AccessLevels;
31 use session::{config, early_error, Session};
32 use lint::{Level, LevelSource, Lint, LintId, LintPass, LintSource};
33 use lint::{EarlyLintPassObject, LateLintPassObject};
34 use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
36 use util::nodemap::FnvHashMap;
39 use std::default::Default as StdDefault;
41 use syntax::attr::{self, AttrMetaMethods};
42 use syntax::parse::token::InternedString;
45 use errors::DiagnosticBuilder;
47 use hir::intravisit as hir_visit;
48 use syntax::visit as ast_visit;
50 /// Information about the registered lints.
52 /// This is basically the subset of `Context` that we can
53 /// build early in the compile pipeline.
54 pub struct LintStore {
55 /// Registered lints. The bool is true if the lint was
56 /// added by a plugin.
57 lints: Vec<(&'static Lint, bool)>,
59 /// Trait objects for each lint pass.
60 /// This is only `None` while iterating over the objects. See the definition
62 early_passes: Option<Vec<EarlyLintPassObject>>,
63 late_passes: Option<Vec<LateLintPassObject>>,
65 /// Lints indexed by name.
66 by_name: FnvHashMap<String, TargetLint>,
68 /// Current levels of each lint, and where they were set.
69 levels: FnvHashMap<LintId, LevelSource>,
71 /// Map of registered lint groups to what lints they expand to. The bool
72 /// is true if the lint group was added by a plugin.
73 lint_groups: FnvHashMap<&'static str, (Vec<LintId>, bool)>,
75 /// Extra info for future incompatibility lints, descibing the
76 /// issue or RFC that caused the incompatibility.
77 future_incompatible: FnvHashMap<LintId, FutureIncompatibleInfo>,
79 /// Maximum level a lint can be
80 lint_cap: Option<Level>,
83 /// Extra information for a future incompatibility lint. See the call
84 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
86 pub struct FutureIncompatibleInfo {
88 pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
91 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
93 /// A direct lint target
96 /// Temporary renaming, used for easing migration pain; see #16545
97 Renamed(String, LintId),
99 /// Lint with this name existed previously, but has been removed/deprecated.
100 /// The string argument is the reason for removal.
110 fn get_level_source(&self, lint: LintId) -> LevelSource {
111 match self.levels.get(&lint) {
113 None => (Allow, Default),
117 fn set_level(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
118 if let Some(cap) = self.lint_cap {
119 lvlsrc.0 = cmp::min(lvlsrc.0, cap);
121 if lvlsrc.0 == Allow {
122 self.levels.remove(&lint);
124 self.levels.insert(lint, lvlsrc);
128 pub fn new() -> LintStore {
131 early_passes: Some(vec!()),
132 late_passes: Some(vec!()),
133 by_name: FnvHashMap(),
134 levels: FnvHashMap(),
135 future_incompatible: FnvHashMap(),
136 lint_groups: FnvHashMap(),
141 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
145 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
146 self.lint_groups.iter().map(|(k, v)| (*k,
151 pub fn register_early_pass(&mut self,
152 sess: Option<&Session>,
154 pass: EarlyLintPassObject) {
155 self.push_pass(sess, from_plugin, &pass);
156 self.early_passes.as_mut().unwrap().push(pass);
159 pub fn register_late_pass(&mut self,
160 sess: Option<&Session>,
162 pass: LateLintPassObject) {
163 self.push_pass(sess, from_plugin, &pass);
164 self.late_passes.as_mut().unwrap().push(pass);
167 // Helper method for register_early/late_pass
168 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
169 sess: Option<&Session>,
172 for &lint in pass.get_lints() {
173 self.lints.push((*lint, from_plugin));
175 let id = LintId::of(*lint);
176 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
177 let msg = format!("duplicate specification of lint {}", lint.name_lower());
178 match (sess, from_plugin) {
179 // We load builtin lints first, so a duplicate is a compiler bug.
180 // Use early_error when handling -W help with no crate.
181 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
182 (Some(_), false) => bug!("{}", msg),
184 // A duplicate name from a plugin is a user error.
185 (Some(sess), true) => sess.err(&msg[..]),
189 if lint.default_level != Allow {
190 self.levels.insert(id, (lint.default_level, Default));
195 pub fn register_future_incompatible(&mut self,
196 sess: Option<&Session>,
197 lints: Vec<FutureIncompatibleInfo>) {
198 let ids = lints.iter().map(|f| f.id).collect();
199 self.register_group(sess, false, "future_incompatible", ids);
201 self.future_incompatible.insert(info.id, info);
205 pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
206 self.future_incompatible.get(&id)
209 pub fn register_group(&mut self, sess: Option<&Session>,
210 from_plugin: bool, name: &'static str,
212 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
215 let msg = format!("duplicate specification of lint group {}", name);
216 match (sess, from_plugin) {
217 // We load builtin lints first, so a duplicate is a compiler bug.
218 // Use early_error when handling -W help with no crate.
219 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
220 (Some(_), false) => bug!("{}", msg),
222 // A duplicate name from a plugin is a user error.
223 (Some(sess), true) => sess.err(&msg[..]),
228 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
229 let target = match self.by_name.get(new_name) {
230 Some(&Id(lint_id)) => lint_id.clone(),
231 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
233 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
236 pub fn register_removed(&mut self, name: &str, reason: &str) {
237 self.by_name.insert(name.into(), Removed(reason.into()));
240 #[allow(unused_variables)]
241 fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
242 -> Result<LintId, FindLintError>
244 match self.by_name.get(lint_name) {
245 Some(&Id(lint_id)) => Ok(lint_id),
246 Some(&Renamed(_, lint_id)) => {
249 Some(&Removed(ref reason)) => {
250 Err(FindLintError::Removed)
252 None => Err(FindLintError::NotFound)
256 pub fn process_command_line(&mut self, sess: &Session) {
257 for &(ref lint_name, level) in &sess.opts.lint_opts {
258 check_lint_name_cmdline(sess, self,
259 &lint_name[..], level);
261 match self.find_lint(&lint_name[..], sess, None) {
262 Ok(lint_id) => self.set_level(lint_id, (level, CommandLine)),
263 Err(FindLintError::Removed) => { }
265 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
266 .collect::<FnvHashMap<&'static str,
268 .get(&lint_name[..]) {
271 .map(|lint_id: &LintId|
272 self.set_level(*lint_id, (level, CommandLine)))
273 .collect::<Vec<()>>();
276 // The lint or lint group doesn't exist.
277 // This is an error, but it was handled
278 // by check_lint_name_cmdline.
285 self.lint_cap = sess.opts.lint_cap;
286 if let Some(cap) = self.lint_cap {
287 for level in self.levels.iter_mut().map(|p| &mut (p.1).0) {
288 *level = cmp::min(*level, cap);
294 /// Context for lint checking after type checking.
295 pub struct LateContext<'a, 'tcx: 'a> {
296 /// Type context we're checking in.
297 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
299 /// The crate being checked.
300 pub krate: &'a hir::Crate,
302 /// Items accessible from the crate being checked.
303 pub access_levels: &'a AccessLevels,
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 /// Context for lint checking of the AST, after expansion, before lowering to
316 pub struct EarlyContext<'a> {
317 /// Type context we're checking in.
318 pub sess: &'a Session,
320 /// The crate being checked.
321 pub krate: &'a ast::Crate,
323 /// The store of registered lints.
326 /// When recursing into an attributed node of the ast which modifies lint
327 /// levels, this stack keeps track of the previous lint levels of whatever
329 level_stack: Vec<(LintId, LevelSource)>,
332 /// Convenience macro for calling a `LintPass` method on every pass in the context.
333 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
334 // Move the vector of passes out of `$cx` so that we can
335 // iterate over it mutably while passing `$cx` to the methods.
336 let mut passes = $cx.mut_lints().$ps.take().unwrap();
337 for obj in &mut passes {
338 obj.$f($cx, $($args),*);
340 $cx.mut_lints().$ps = Some(passes);
343 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
344 /// attributes. Writing this as an iterator is an enormous mess.
345 // See also the hir version just below.
346 pub fn gather_attrs(attrs: &[ast::Attribute])
347 -> Vec<Result<(InternedString, Level, Span), Span>> {
348 let mut out = vec!();
350 let r = gather_attr(attr);
351 out.extend(r.into_iter());
356 pub fn gather_attr(attr: &ast::Attribute)
357 -> Vec<Result<(InternedString, Level, Span), Span>> {
358 let mut out = vec!();
360 let level = match Level::from_str(&attr.name()) {
365 attr::mark_used(attr);
367 let meta = &attr.node.value;
368 let metas = if let Some(metas) = meta.meta_item_list() {
371 out.push(Err(meta.span));
376 out.push(if meta.is_word() {
377 Ok((meta.name().clone(), level, meta.span))
386 /// Emit a lint as a warning or an error (or not at all)
387 /// according to `level`.
389 /// This lives outside of `Context` so it can be used by checks
390 /// in trans that run after the main lint pass is finished. Most
391 /// lints elsewhere in the compiler should call
392 /// `Session::add_lint()` instead.
393 pub fn raw_emit_lint(sess: &Session,
399 raw_struct_lint(sess, lints, lint, lvlsrc, span, msg).emit();
402 pub fn raw_struct_lint<'a>(sess: &'a Session,
408 -> DiagnosticBuilder<'a> {
409 let (mut level, source) = lvlsrc;
411 return sess.diagnostic().struct_dummy();
414 let name = lint.name_lower();
416 let msg = match source {
418 format!("{}, #[{}({})] on by default", msg,
419 level.as_str(), name)
422 format!("{} [-{} {}]", msg,
424 Warn => 'W', Deny => 'D', Forbid => 'F',
426 }, name.replace("_", "-"))
434 // For purposes of printing, we can treat forbid as deny.
435 if level == Forbid { level = Deny; }
437 let mut err = match (level, span) {
438 (Warn, Some(sp)) => sess.struct_span_warn(sp, &msg[..]),
439 (Warn, None) => sess.struct_warn(&msg[..]),
440 (Deny, Some(sp)) => sess.struct_span_err(sp, &msg[..]),
441 (Deny, None) => sess.struct_err(&msg[..]),
442 _ => bug!("impossible level in raw_emit_lint"),
445 // Check for future incompatibility lints and issue a stronger warning.
446 if let Some(future_incompatible) = lints.future_incompatible(LintId::of(lint)) {
447 let explanation = format!("this was previously accepted by the compiler \
448 but is being phased out; \
449 it will become a hard error in a future release!");
450 let citation = format!("for more information, see {}",
451 future_incompatible.reference);
452 err.warn(&explanation);
456 if let Some(span) = def {
457 let explanation = "lint level defined here";
458 err.span_note(span, &explanation);
464 pub trait LintContext: Sized {
465 fn sess(&self) -> &Session;
466 fn lints(&self) -> &LintStore;
467 fn mut_lints(&mut self) -> &mut LintStore;
468 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>;
469 fn enter_attrs(&mut self, attrs: &[ast::Attribute]);
470 fn exit_attrs(&mut self, attrs: &[ast::Attribute]);
472 /// Get the level of `lint` at the current position of the lint
474 fn current_level(&self, lint: &'static Lint) -> Level {
475 self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
478 fn level_src(&self, lint: &'static Lint) -> Option<LevelSource> {
479 self.lints().levels.get(&LintId::of(lint)).map(|ls| match ls {
481 let lint_id = LintId::of(builtin::WARNINGS);
482 let warn_src = self.lints().get_level_source(lint_id);
483 if warn_src.0 != Warn {
493 fn lookup_and_emit(&self, lint: &'static Lint, span: Option<Span>, msg: &str) {
494 let (level, src) = match self.level_src(lint) {
499 raw_emit_lint(&self.sess(), self.lints(), lint, (level, src), span, msg);
506 -> DiagnosticBuilder {
507 let (level, src) = match self.level_src(lint) {
508 None => return self.sess().diagnostic().struct_dummy(),
512 raw_struct_lint(&self.sess(), self.lints(), lint, (level, src), span, msg)
515 /// Emit a lint at the appropriate level, for a particular span.
516 fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) {
517 self.lookup_and_emit(lint, Some(span), msg);
520 fn struct_span_lint(&self,
524 -> DiagnosticBuilder {
525 self.lookup(lint, Some(span), msg)
528 /// Emit a lint and note at the appropriate level, for a particular span.
529 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
530 note_span: Span, note: &str) {
531 let mut err = self.lookup(lint, Some(span), msg);
532 if self.current_level(lint) != Level::Allow {
533 if note_span == span {
536 err.span_note(note_span, note);
542 /// Emit a lint and help at the appropriate level, for a particular span.
543 fn span_lint_help(&self, lint: &'static Lint, span: Span,
544 msg: &str, help: &str) {
545 let mut err = self.lookup(lint, Some(span), msg);
546 self.span_lint(lint, span, msg);
547 if self.current_level(lint) != Level::Allow {
548 err.span_help(span, help);
553 /// Emit a lint at the appropriate level, with no associated span.
554 fn lint(&self, lint: &'static Lint, msg: &str) {
555 self.lookup_and_emit(lint, None, msg);
558 /// Merge the lints specified by any lint attributes into the
559 /// current lint context, call the provided function, then reset the
560 /// lints in effect to their previous state.
561 fn with_lint_attrs<F>(&mut self,
562 attrs: &[ast::Attribute],
564 where F: FnOnce(&mut Self),
566 // Parse all of the lint attributes, and then add them all to the
567 // current dictionary of lint information. Along the way, keep a history
568 // of what we changed so we can roll everything back after invoking the
572 for result in gather_attrs(attrs) {
573 let v = match result {
575 span_err!(self.sess(), span, E0452,
576 "malformed lint attribute");
579 Ok((lint_name, level, span)) => {
580 match self.lints().find_lint(&lint_name, &self.sess(), Some(span)) {
581 Ok(lint_id) => vec![(lint_id, level, span)],
582 Err(FindLintError::NotFound) => {
583 match self.lints().lint_groups.get(&lint_name[..]) {
584 Some(&(ref v, _)) => v.iter()
585 .map(|lint_id: &LintId|
586 (*lint_id, level, span))
589 // The lint or lint group doesn't exist.
590 // This is an error, but it was handled
591 // by check_lint_name_attribute.
596 Err(FindLintError::Removed) => { continue; }
601 for (lint_id, level, span) in v {
602 let (now, now_source) = self.lints().get_level_source(lint_id);
603 if now == Forbid && level != Forbid {
604 let lint_name = lint_id.as_str();
605 let mut diag_builder = struct_span_err!(self.sess(), span, E0453,
606 "{}({}) overruled by outer forbid({})",
607 level.as_str(), lint_name,
610 LintSource::Default => &mut diag_builder,
611 LintSource::Node(forbid_source_span) => {
612 diag_builder.span_note(forbid_source_span,
613 "`forbid` lint level set here")
615 LintSource::CommandLine => {
616 diag_builder.note("`forbid` lint level was set on command line")
619 } else if now != level {
620 let src = self.lints().get_level_source(lint_id).1;
621 self.level_stack().push((lint_id, (now, src)));
623 self.mut_lints().set_level(lint_id, (level, Node(span)));
628 self.enter_attrs(attrs);
630 self.exit_attrs(attrs);
634 let (lint, lvlsrc) = self.level_stack().pop().unwrap();
635 self.mut_lints().set_level(lint, lvlsrc);
641 impl<'a> EarlyContext<'a> {
642 fn new(sess: &'a Session,
643 krate: &'a ast::Crate) -> EarlyContext<'a> {
644 // We want to own the lint store, so move it out of the session. Remember
645 // to put it back later...
646 let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
657 impl<'a, 'tcx> LateContext<'a, 'tcx> {
658 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
659 krate: &'a hir::Crate,
660 access_levels: &'a AccessLevels) -> LateContext<'a, 'tcx> {
661 // We want to own the lint store, so move it out of the session.
662 let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
668 access_levels: access_levels,
674 fn visit_ids<F>(&mut self, f: F)
675 where F: FnOnce(&mut IdVisitor)
677 let mut v = IdVisitor {
684 impl<'a, 'tcx> LintContext for LateContext<'a, 'tcx> {
685 /// Get the overall compiler `Session` object.
686 fn sess(&self) -> &Session {
690 fn lints(&self) -> &LintStore {
694 fn mut_lints(&mut self) -> &mut LintStore {
698 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
699 &mut self.level_stack
702 fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
703 debug!("late context: enter_attrs({:?})", attrs);
704 run_lints!(self, enter_lint_attrs, late_passes, attrs);
707 fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
708 debug!("late context: exit_attrs({:?})", attrs);
709 run_lints!(self, exit_lint_attrs, late_passes, attrs);
713 impl<'a> LintContext for EarlyContext<'a> {
714 /// Get the overall compiler `Session` object.
715 fn sess(&self) -> &Session {
719 fn lints(&self) -> &LintStore {
723 fn mut_lints(&mut self) -> &mut LintStore {
727 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
728 &mut self.level_stack
731 fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
732 debug!("early context: enter_attrs({:?})", attrs);
733 run_lints!(self, enter_lint_attrs, early_passes, attrs);
736 fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
737 debug!("early context: exit_attrs({:?})", attrs);
738 run_lints!(self, exit_lint_attrs, early_passes, attrs);
742 impl<'a, 'tcx, 'v> hir_visit::Visitor<'v> for LateContext<'a, 'tcx> {
743 /// Because lints are scoped lexically, we want to walk nested
744 /// items in the context of the outer item, so enable
746 fn visit_nested_item(&mut self, item: hir::ItemId) {
748 self.visit_item(tcx.map.expect_item(item.id))
751 fn visit_item(&mut self, it: &hir::Item) {
752 self.with_lint_attrs(&it.attrs, |cx| {
753 run_lints!(cx, check_item, late_passes, it);
754 cx.visit_ids(|v| v.visit_item(it));
755 hir_visit::walk_item(cx, it);
756 run_lints!(cx, check_item_post, late_passes, it);
760 fn visit_foreign_item(&mut self, it: &hir::ForeignItem) {
761 self.with_lint_attrs(&it.attrs, |cx| {
762 run_lints!(cx, check_foreign_item, late_passes, it);
763 hir_visit::walk_foreign_item(cx, it);
764 run_lints!(cx, check_foreign_item_post, late_passes, it);
768 fn visit_pat(&mut self, p: &hir::Pat) {
769 run_lints!(self, check_pat, late_passes, p);
770 hir_visit::walk_pat(self, p);
773 fn visit_expr(&mut self, e: &hir::Expr) {
774 self.with_lint_attrs(&e.attrs, |cx| {
775 run_lints!(cx, check_expr, late_passes, e);
776 hir_visit::walk_expr(cx, e);
780 fn visit_stmt(&mut self, s: &hir::Stmt) {
781 // statement attributes are actually just attributes on one of
785 // so we keep track of lint levels there
786 run_lints!(self, check_stmt, late_passes, s);
787 hir_visit::walk_stmt(self, s);
790 fn visit_fn(&mut self, fk: hir_visit::FnKind<'v>, decl: &'v hir::FnDecl,
791 body: &'v hir::Block, span: Span, id: ast::NodeId) {
792 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
793 hir_visit::walk_fn(self, fk, decl, body, span, id);
794 run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
797 fn visit_variant_data(&mut self,
798 s: &hir::VariantData,
801 item_id: ast::NodeId,
803 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
804 hir_visit::walk_struct_def(self, s);
805 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
808 fn visit_struct_field(&mut self, s: &hir::StructField) {
809 self.with_lint_attrs(&s.attrs, |cx| {
810 run_lints!(cx, check_struct_field, late_passes, s);
811 hir_visit::walk_struct_field(cx, s);
815 fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics, item_id: ast::NodeId) {
816 self.with_lint_attrs(&v.node.attrs, |cx| {
817 run_lints!(cx, check_variant, late_passes, v, g);
818 hir_visit::walk_variant(cx, v, g, item_id);
819 run_lints!(cx, check_variant_post, late_passes, v, g);
823 fn visit_ty(&mut self, t: &hir::Ty) {
824 run_lints!(self, check_ty, late_passes, t);
825 hir_visit::walk_ty(self, t);
828 fn visit_name(&mut self, sp: Span, name: ast::Name) {
829 run_lints!(self, check_name, late_passes, sp, name);
832 fn visit_mod(&mut self, m: &hir::Mod, s: Span, n: ast::NodeId) {
833 run_lints!(self, check_mod, late_passes, m, s, n);
834 hir_visit::walk_mod(self, m, n);
835 run_lints!(self, check_mod_post, late_passes, m, s, n);
838 fn visit_local(&mut self, l: &hir::Local) {
839 self.with_lint_attrs(&l.attrs, |cx| {
840 run_lints!(cx, check_local, late_passes, l);
841 hir_visit::walk_local(cx, l);
845 fn visit_block(&mut self, b: &hir::Block) {
846 run_lints!(self, check_block, late_passes, b);
847 hir_visit::walk_block(self, b);
848 run_lints!(self, check_block_post, late_passes, b);
851 fn visit_arm(&mut self, a: &hir::Arm) {
852 run_lints!(self, check_arm, late_passes, a);
853 hir_visit::walk_arm(self, a);
856 fn visit_decl(&mut self, d: &hir::Decl) {
857 run_lints!(self, check_decl, late_passes, d);
858 hir_visit::walk_decl(self, d);
861 fn visit_expr_post(&mut self, e: &hir::Expr) {
862 run_lints!(self, check_expr_post, late_passes, e);
865 fn visit_generics(&mut self, g: &hir::Generics) {
866 run_lints!(self, check_generics, late_passes, g);
867 hir_visit::walk_generics(self, g);
870 fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
871 self.with_lint_attrs(&trait_item.attrs, |cx| {
872 run_lints!(cx, check_trait_item, late_passes, trait_item);
873 cx.visit_ids(|v| hir_visit::walk_trait_item(v, trait_item));
874 hir_visit::walk_trait_item(cx, trait_item);
875 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
879 fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
880 self.with_lint_attrs(&impl_item.attrs, |cx| {
881 run_lints!(cx, check_impl_item, late_passes, impl_item);
882 cx.visit_ids(|v| hir_visit::walk_impl_item(v, impl_item));
883 hir_visit::walk_impl_item(cx, impl_item);
884 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
888 fn visit_lifetime(&mut self, lt: &hir::Lifetime) {
889 run_lints!(self, check_lifetime, late_passes, lt);
892 fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) {
893 run_lints!(self, check_lifetime_def, late_passes, lt);
896 fn visit_path(&mut self, p: &hir::Path, id: ast::NodeId) {
897 run_lints!(self, check_path, late_passes, p, id);
898 hir_visit::walk_path(self, p);
901 fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
902 run_lints!(self, check_path_list_item, late_passes, item);
903 hir_visit::walk_path_list_item(self, prefix, item);
906 fn visit_attribute(&mut self, attr: &ast::Attribute) {
907 check_lint_name_attribute(self, attr);
908 run_lints!(self, check_attribute, late_passes, attr);
912 impl<'a> ast_visit::Visitor for EarlyContext<'a> {
913 fn visit_item(&mut self, it: &ast::Item) {
914 self.with_lint_attrs(&it.attrs, |cx| {
915 run_lints!(cx, check_item, early_passes, it);
916 ast_visit::walk_item(cx, it);
917 run_lints!(cx, check_item_post, early_passes, it);
921 fn visit_foreign_item(&mut self, it: &ast::ForeignItem) {
922 self.with_lint_attrs(&it.attrs, |cx| {
923 run_lints!(cx, check_foreign_item, early_passes, it);
924 ast_visit::walk_foreign_item(cx, it);
925 run_lints!(cx, check_foreign_item_post, early_passes, it);
929 fn visit_pat(&mut self, p: &ast::Pat) {
930 run_lints!(self, check_pat, early_passes, p);
931 ast_visit::walk_pat(self, p);
934 fn visit_expr(&mut self, e: &ast::Expr) {
935 self.with_lint_attrs(&e.attrs, |cx| {
936 run_lints!(cx, check_expr, early_passes, e);
937 ast_visit::walk_expr(cx, e);
941 fn visit_stmt(&mut self, s: &ast::Stmt) {
942 run_lints!(self, check_stmt, early_passes, s);
943 ast_visit::walk_stmt(self, s);
946 fn visit_fn(&mut self, fk: ast_visit::FnKind, decl: &ast::FnDecl,
947 body: &ast::Block, span: Span, id: ast::NodeId) {
948 run_lints!(self, check_fn, early_passes, fk, decl, body, span, id);
949 ast_visit::walk_fn(self, fk, decl, body, span);
950 run_lints!(self, check_fn_post, early_passes, fk, decl, body, span, id);
953 fn visit_variant_data(&mut self,
954 s: &ast::VariantData,
957 item_id: ast::NodeId,
959 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
960 ast_visit::walk_struct_def(self, s);
961 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
964 fn visit_struct_field(&mut self, s: &ast::StructField) {
965 self.with_lint_attrs(&s.attrs, |cx| {
966 run_lints!(cx, check_struct_field, early_passes, s);
967 ast_visit::walk_struct_field(cx, s);
971 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, item_id: ast::NodeId) {
972 self.with_lint_attrs(&v.node.attrs, |cx| {
973 run_lints!(cx, check_variant, early_passes, v, g);
974 ast_visit::walk_variant(cx, v, g, item_id);
975 run_lints!(cx, check_variant_post, early_passes, v, g);
979 fn visit_ty(&mut self, t: &ast::Ty) {
980 run_lints!(self, check_ty, early_passes, t);
981 ast_visit::walk_ty(self, t);
984 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
985 run_lints!(self, check_ident, early_passes, sp, id);
988 fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId) {
989 run_lints!(self, check_mod, early_passes, m, s, n);
990 ast_visit::walk_mod(self, m);
991 run_lints!(self, check_mod_post, early_passes, m, s, n);
994 fn visit_local(&mut self, l: &ast::Local) {
995 self.with_lint_attrs(&l.attrs, |cx| {
996 run_lints!(cx, check_local, early_passes, l);
997 ast_visit::walk_local(cx, l);
1001 fn visit_block(&mut self, b: &ast::Block) {
1002 run_lints!(self, check_block, early_passes, b);
1003 ast_visit::walk_block(self, b);
1004 run_lints!(self, check_block_post, early_passes, b);
1007 fn visit_arm(&mut self, a: &ast::Arm) {
1008 run_lints!(self, check_arm, early_passes, a);
1009 ast_visit::walk_arm(self, a);
1012 fn visit_expr_post(&mut self, e: &ast::Expr) {
1013 run_lints!(self, check_expr_post, early_passes, e);
1016 fn visit_generics(&mut self, g: &ast::Generics) {
1017 run_lints!(self, check_generics, early_passes, g);
1018 ast_visit::walk_generics(self, g);
1021 fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
1022 self.with_lint_attrs(&trait_item.attrs, |cx| {
1023 run_lints!(cx, check_trait_item, early_passes, trait_item);
1024 ast_visit::walk_trait_item(cx, trait_item);
1025 run_lints!(cx, check_trait_item_post, early_passes, trait_item);
1029 fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
1030 self.with_lint_attrs(&impl_item.attrs, |cx| {
1031 run_lints!(cx, check_impl_item, early_passes, impl_item);
1032 ast_visit::walk_impl_item(cx, impl_item);
1033 run_lints!(cx, check_impl_item_post, early_passes, impl_item);
1037 fn visit_lifetime(&mut self, lt: &ast::Lifetime) {
1038 run_lints!(self, check_lifetime, early_passes, lt);
1041 fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) {
1042 run_lints!(self, check_lifetime_def, early_passes, lt);
1045 fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId) {
1046 run_lints!(self, check_path, early_passes, p, id);
1047 ast_visit::walk_path(self, p);
1050 fn visit_path_list_item(&mut self, prefix: &ast::Path, item: &ast::PathListItem) {
1051 run_lints!(self, check_path_list_item, early_passes, item);
1052 ast_visit::walk_path_list_item(self, prefix, item);
1055 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1056 run_lints!(self, check_attribute, early_passes, attr);
1060 struct IdVisitor<'a, 'b: 'a, 'tcx: 'a+'b> {
1061 cx: &'a mut LateContext<'b, 'tcx>
1064 // Output any lints that were previously added to the session.
1065 impl<'a, 'b, 'tcx, 'v> hir_visit::Visitor<'v> for IdVisitor<'a, 'b, 'tcx> {
1067 fn visit_id(&mut self, id: ast::NodeId) {
1068 if let Some(lints) = self.cx.sess().lints.borrow_mut().remove(&id) {
1069 debug!("LateContext::visit_id: id={:?} lints={:?}", id, lints);
1070 for (lint_id, span, msg) in lints {
1071 self.cx.span_lint(lint_id.lint, span, &msg[..])
1076 fn visit_trait_item(&mut self, _ti: &hir::TraitItem) {
1077 // Do not recurse into trait or impl items automatically. These are
1078 // processed separately by calling hir_visit::walk_trait_item()
1081 fn visit_impl_item(&mut self, _ii: &hir::ImplItem) {
1082 // See visit_trait_item()
1086 enum CheckLintNameResult {
1088 // Lint doesn't exist
1090 // The lint is either renamed or removed. This is the warning
1095 /// Checks the name of a lint for its existence, and whether it was
1096 /// renamed or removed. Generates a DiagnosticBuilder containing a
1097 /// warning for renamed and removed lints. This is over both lint
1098 /// names from attributes and those passed on the command line. Since
1099 /// it emits non-fatal warnings and there are *two* lint passes that
1100 /// inspect attributes, this is only run from the late pass to avoid
1101 /// printing duplicate warnings.
1102 fn check_lint_name(lint_cx: &LintStore,
1103 lint_name: &str) -> CheckLintNameResult {
1104 match lint_cx.by_name.get(lint_name) {
1105 Some(&Renamed(ref new_name, _)) => {
1106 CheckLintNameResult::Warning(
1107 format!("lint {} has been renamed to {}", lint_name, new_name)
1110 Some(&Removed(ref reason)) => {
1111 CheckLintNameResult::Warning(
1112 format!("lint {} has been removed: {}", lint_name, reason)
1116 match lint_cx.lint_groups.get(lint_name) {
1118 CheckLintNameResult::NoLint
1121 /* lint group exists */
1122 CheckLintNameResult::Ok
1128 CheckLintNameResult::Ok
1133 // Checks the validity of lint names derived from attributes
1134 fn check_lint_name_attribute(cx: &LateContext, attr: &ast::Attribute) {
1135 for result in gather_attr(attr) {
1138 // Malformed lint attr. Reported by with_lint_attrs
1141 Ok((lint_name, _, span)) => {
1142 match check_lint_name(&cx.lints,
1144 CheckLintNameResult::Ok => (),
1145 CheckLintNameResult::Warning(ref msg) => {
1146 cx.span_lint(builtin::RENAMED_AND_REMOVED_LINTS,
1149 CheckLintNameResult::NoLint => {
1150 cx.span_lint(builtin::UNKNOWN_LINTS, span,
1151 &format!("unknown lint: `{}`",
1160 // Checks the validity of lint names derived from the command line
1161 fn check_lint_name_cmdline(sess: &Session, lint_cx: &LintStore,
1162 lint_name: &str, level: Level) {
1163 let db = match check_lint_name(lint_cx, lint_name) {
1164 CheckLintNameResult::Ok => None,
1165 CheckLintNameResult::Warning(ref msg) => {
1166 Some(sess.struct_warn(msg))
1168 CheckLintNameResult::NoLint => {
1169 Some(sess.struct_err(&format!("unknown lint: `{}`", lint_name)))
1173 if let Some(mut db) = db {
1174 let msg = format!("requested on the command line with `{} {}`",
1176 Level::Allow => "-A",
1177 Level::Warn => "-W",
1178 Level::Deny => "-D",
1179 Level::Forbid => "-F",
1188 /// Perform lint checking on a crate.
1190 /// Consumes the `lint_store` field of the `Session`.
1191 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1192 access_levels: &AccessLevels) {
1193 let _task = tcx.dep_graph.in_task(DepNode::LateLintCheck);
1195 let krate = tcx.map.krate();
1196 let mut cx = LateContext::new(tcx, krate, access_levels);
1198 // Visit the whole crate.
1199 cx.with_lint_attrs(&krate.attrs, |cx| {
1201 hir_visit::walk_crate(v, krate);
1204 // since the root module isn't visited as an item (because it isn't an
1205 // item), warn for it here.
1206 run_lints!(cx, check_crate, late_passes, krate);
1208 hir_visit::walk_crate(cx, krate);
1210 run_lints!(cx, check_crate_post, late_passes, krate);
1213 // If we missed any lints added to the session, then there's a bug somewhere
1214 // in the iteration code.
1215 for (id, v) in tcx.sess.lints.borrow().iter() {
1216 for &(lint, span, ref msg) in v {
1218 "unprocessed lint {} at {}: {}",
1219 lint.as_str(), tcx.map.node_to_string(*id), *msg)
1223 // Put the lint store back in the session.
1224 mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), cx.lints);
1227 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1228 let mut cx = EarlyContext::new(sess, krate);
1230 // Visit the whole crate.
1231 cx.with_lint_attrs(&krate.attrs, |cx| {
1232 // Lints may be assigned to the whole crate.
1233 if let Some(lints) = cx.sess.lints.borrow_mut().remove(&ast::CRATE_NODE_ID) {
1234 for (lint_id, span, msg) in lints {
1235 cx.span_lint(lint_id.lint, span, &msg[..])
1239 // since the root module isn't visited as an item (because it isn't an
1240 // item), warn for it here.
1241 run_lints!(cx, check_crate, early_passes, krate);
1243 ast_visit::walk_crate(cx, krate);
1245 run_lints!(cx, check_crate_post, early_passes, krate);
1248 // Put the lint store back in the session.
1249 mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1251 // If we missed any lints added to the session, then there's a bug somewhere
1252 // in the iteration code.
1253 for (_, v) in sess.lints.borrow().iter() {
1254 for &(lint, span, ref msg) in v {
1255 span_bug!(span, "unprocessed lint {}: {}", lint.as_str(), *msg)