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;
30 use middle::ty::TyCtxt;
31 use session::{config, early_error, Session};
32 use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass};
33 use lint::{EarlyLintPass, EarlyLintPassObject, LateLintPass, LateLintPassObject};
34 use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
36 use util::nodemap::FnvHashMap;
38 use std::cell::RefCell;
40 use std::default::Default as StdDefault;
42 use syntax::ast_util::{self, IdVisitingOperation};
43 use syntax::attr::{self, AttrMetaMethods};
44 use syntax::codemap::Span;
45 use syntax::errors::DiagnosticBuilder;
46 use syntax::parse::token::InternedString;
48 use syntax::attr::ThinAttributesExt;
50 use rustc_front::util;
51 use rustc_front::intravisit as hir_visit;
52 use syntax::visit as ast_visit;
54 /// Information about the registered lints.
56 /// This is basically the subset of `Context` that we can
57 /// build early in the compile pipeline.
58 pub struct LintStore {
59 /// Registered lints. The bool is true if the lint was
60 /// added by a plugin.
61 lints: Vec<(&'static Lint, bool)>,
63 /// Trait objects for each lint pass.
64 /// This is only `None` while iterating over the objects. See the definition
66 early_passes: Option<Vec<EarlyLintPassObject>>,
67 late_passes: Option<Vec<LateLintPassObject>>,
69 /// Lints indexed by name.
70 by_name: FnvHashMap<String, TargetLint>,
72 /// Current levels of each lint, and where they were set.
73 levels: FnvHashMap<LintId, LevelSource>,
75 /// Map of registered lint groups to what lints they expand to. The bool
76 /// is true if the lint group was added by a plugin.
77 lint_groups: FnvHashMap<&'static str, (Vec<LintId>, bool)>,
79 /// Extra info for future incompatibility lints, descibing the
80 /// issue or RFC that caused the incompatibility.
81 future_incompatible: FnvHashMap<LintId, FutureIncompatibleInfo>,
83 /// Maximum level a lint can be
84 lint_cap: Option<Level>,
87 /// Extra information for a future incompatibility lint. See the call
88 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
90 pub struct FutureIncompatibleInfo {
92 pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
95 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
97 /// A direct lint target
100 /// Temporary renaming, used for easing migration pain; see #16545
101 Renamed(String, LintId),
103 /// Lint with this name existed previously, but has been removed/deprecated.
104 /// The string argument is the reason for removal.
114 fn get_level_source(&self, lint: LintId) -> LevelSource {
115 match self.levels.get(&lint) {
117 None => (Allow, Default),
121 fn set_level(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
122 if let Some(cap) = self.lint_cap {
123 lvlsrc.0 = cmp::min(lvlsrc.0, cap);
125 if lvlsrc.0 == Allow {
126 self.levels.remove(&lint);
128 self.levels.insert(lint, lvlsrc);
132 pub fn new() -> LintStore {
135 early_passes: Some(vec!()),
136 late_passes: Some(vec!()),
137 by_name: FnvHashMap(),
138 levels: FnvHashMap(),
139 future_incompatible: FnvHashMap(),
140 lint_groups: FnvHashMap(),
145 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
149 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
150 self.lint_groups.iter().map(|(k, v)| (*k,
155 pub fn register_early_pass(&mut self,
156 sess: Option<&Session>,
158 pass: EarlyLintPassObject) {
159 self.push_pass(sess, from_plugin, &pass);
160 self.early_passes.as_mut().unwrap().push(pass);
163 pub fn register_late_pass(&mut self,
164 sess: Option<&Session>,
166 pass: LateLintPassObject) {
167 self.push_pass(sess, from_plugin, &pass);
168 self.late_passes.as_mut().unwrap().push(pass);
171 // Helper method for register_early/late_pass
172 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
173 sess: Option<&Session>,
176 for &lint in pass.get_lints() {
177 self.lints.push((*lint, from_plugin));
179 let id = LintId::of(*lint);
180 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
181 let msg = format!("duplicate specification of lint {}", lint.name_lower());
182 match (sess, from_plugin) {
183 // We load builtin lints first, so a duplicate is a compiler bug.
184 // Use early_error when handling -W help with no crate.
185 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
186 (Some(sess), false) => sess.bug(&msg[..]),
188 // A duplicate name from a plugin is a user error.
189 (Some(sess), true) => sess.err(&msg[..]),
193 if lint.default_level != Allow {
194 self.levels.insert(id, (lint.default_level, Default));
199 pub fn register_future_incompatible(&mut self,
200 sess: Option<&Session>,
201 lints: Vec<FutureIncompatibleInfo>) {
202 let ids = lints.iter().map(|f| f.id).collect();
203 self.register_group(sess, false, "future_incompatible", ids);
205 self.future_incompatible.insert(info.id, info);
209 pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
210 self.future_incompatible.get(&id)
213 pub fn register_group(&mut self, sess: Option<&Session>,
214 from_plugin: bool, name: &'static str,
216 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
219 let msg = format!("duplicate specification of lint group {}", name);
220 match (sess, from_plugin) {
221 // We load builtin lints first, so a duplicate is a compiler bug.
222 // Use early_error when handling -W help with no crate.
223 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
224 (Some(sess), false) => sess.bug(&msg[..]),
226 // A duplicate name from a plugin is a user error.
227 (Some(sess), true) => sess.err(&msg[..]),
232 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
233 let target = match self.by_name.get(new_name) {
234 Some(&Id(lint_id)) => lint_id.clone(),
235 _ => panic!("invalid lint renaming of {} to {}", old_name, new_name)
237 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
240 pub fn register_removed(&mut self, name: &str, reason: &str) {
241 self.by_name.insert(name.into(), Removed(reason.into()));
244 #[allow(unused_variables)]
245 fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
246 -> Result<LintId, FindLintError>
248 match self.by_name.get(lint_name) {
249 Some(&Id(lint_id)) => Ok(lint_id),
250 Some(&Renamed(_, lint_id)) => {
253 Some(&Removed(ref reason)) => {
254 Err(FindLintError::Removed)
256 None => Err(FindLintError::NotFound)
260 pub fn process_command_line(&mut self, sess: &Session) {
261 for &(ref lint_name, level) in &sess.opts.lint_opts {
262 check_lint_name_cmdline(sess, self,
263 &lint_name[..], level);
265 match self.find_lint(&lint_name[..], sess, None) {
266 Ok(lint_id) => self.set_level(lint_id, (level, CommandLine)),
267 Err(FindLintError::Removed) => { }
269 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
270 .collect::<FnvHashMap<&'static str,
272 .get(&lint_name[..]) {
275 .map(|lint_id: &LintId|
276 self.set_level(*lint_id, (level, CommandLine)))
277 .collect::<Vec<()>>();
280 // The lint or lint group doesn't exist.
281 // This is an error, but it was handled
282 // by check_lint_name_cmdline.
289 self.lint_cap = sess.opts.lint_cap;
290 if let Some(cap) = self.lint_cap {
291 for level in self.levels.iter_mut().map(|p| &mut (p.1).0) {
292 *level = cmp::min(*level, cap);
298 /// Context for lint checking after type checking.
299 pub struct LateContext<'a, 'tcx: 'a> {
300 /// Type context we're checking in.
301 pub tcx: &'a TyCtxt<'tcx>,
303 /// The crate being checked.
304 pub krate: &'a hir::Crate,
306 /// Items accessible from the crate being checked.
307 pub access_levels: &'a AccessLevels,
309 /// The store of registered lints.
312 /// When recursing into an attributed node of the ast which modifies lint
313 /// levels, this stack keeps track of the previous lint levels of whatever
315 level_stack: Vec<(LintId, LevelSource)>,
317 /// Level of lints for certain NodeIds, stored here because the body of
318 /// the lint needs to run in trans.
319 node_levels: RefCell<FnvHashMap<(ast::NodeId, LintId), LevelSource>>,
322 /// Context for lint checking of the AST, after expansion, before lowering to
324 pub struct EarlyContext<'a> {
325 /// Type context we're checking in.
326 pub sess: &'a Session,
328 /// The crate being checked.
329 pub krate: &'a ast::Crate,
331 /// The store of registered lints.
334 /// When recursing into an attributed node of the ast which modifies lint
335 /// levels, this stack keeps track of the previous lint levels of whatever
337 level_stack: Vec<(LintId, LevelSource)>,
340 /// Convenience macro for calling a `LintPass` method on every pass in the context.
341 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
342 // Move the vector of passes out of `$cx` so that we can
343 // iterate over it mutably while passing `$cx` to the methods.
344 let mut passes = $cx.mut_lints().$ps.take().unwrap();
345 for obj in &mut passes {
346 obj.$f($cx, $($args),*);
348 $cx.mut_lints().$ps = Some(passes);
351 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
352 /// attributes. Writing this as an iterator is an enormous mess.
353 // See also the hir version just below.
354 pub fn gather_attrs(attrs: &[ast::Attribute])
355 -> Vec<Result<(InternedString, Level, Span), Span>> {
356 let mut out = vec!();
358 let r = gather_attr(attr);
359 out.extend(r.into_iter());
364 pub fn gather_attr(attr: &ast::Attribute)
365 -> Vec<Result<(InternedString, Level, Span), Span>> {
366 let mut out = vec!();
368 let level = match Level::from_str(&attr.name()) {
373 attr::mark_used(attr);
375 let meta = &attr.node.value;
376 let metas = match meta.node {
377 ast::MetaItemKind::List(_, ref metas) => metas,
379 out.push(Err(meta.span));
385 out.push(match meta.node {
386 ast::MetaItemKind::Word(ref lint_name) => Ok((lint_name.clone(), level, meta.span)),
394 /// Emit a lint as a warning or an error (or not at all)
395 /// according to `level`.
397 /// This lives outside of `Context` so it can be used by checks
398 /// in trans that run after the main lint pass is finished. Most
399 /// lints elsewhere in the compiler should call
400 /// `Session::add_lint()` instead.
401 pub fn raw_emit_lint(sess: &Session,
407 raw_struct_lint(sess, lints, lint, lvlsrc, span, msg).emit();
410 pub fn raw_struct_lint<'a>(sess: &'a Session,
416 -> DiagnosticBuilder<'a> {
417 let (mut level, source) = lvlsrc;
419 return sess.diagnostic().struct_dummy();
422 let name = lint.name_lower();
424 let msg = match source {
426 format!("{}, #[{}({})] on by default", msg,
427 level.as_str(), name)
430 format!("{} [-{} {}]", msg,
432 Warn => 'W', Deny => 'D', Forbid => 'F',
434 }, name.replace("_", "-"))
442 // For purposes of printing, we can treat forbid as deny.
443 if level == Forbid { level = Deny; }
445 let mut err = match (level, span) {
446 (Warn, Some(sp)) => sess.struct_span_warn(sp, &msg[..]),
447 (Warn, None) => sess.struct_warn(&msg[..]),
448 (Deny, Some(sp)) => sess.struct_span_err(sp, &msg[..]),
449 (Deny, None) => sess.struct_err(&msg[..]),
450 _ => sess.bug("impossible level in raw_emit_lint"),
453 // Check for future incompatibility lints and issue a stronger warning.
454 if let Some(future_incompatible) = lints.future_incompatible(LintId::of(lint)) {
455 let explanation = format!("this was previously accepted by the compiler \
456 but is being phased out; \
457 it will become a hard error in a future release!");
458 let citation = format!("for more information, see {}",
459 future_incompatible.reference);
460 if let Some(sp) = span {
461 err.fileline_warn(sp, &explanation);
462 err.fileline_note(sp, &citation);
464 err.warn(&explanation);
469 if let Some(span) = def {
470 err.span_note(span, "lint level defined here");
476 pub trait LintContext: Sized {
477 fn sess(&self) -> &Session;
478 fn lints(&self) -> &LintStore;
479 fn mut_lints(&mut self) -> &mut LintStore;
480 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>;
481 fn enter_attrs(&mut self, attrs: &[ast::Attribute]);
482 fn exit_attrs(&mut self, attrs: &[ast::Attribute]);
484 /// Get the level of `lint` at the current position of the lint
486 fn current_level(&self, lint: &'static Lint) -> Level {
487 self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
490 fn level_src(&self, lint: &'static Lint) -> Option<LevelSource> {
491 self.lints().levels.get(&LintId::of(lint)).map(|ls| match ls {
493 let lint_id = LintId::of(builtin::WARNINGS);
494 let warn_src = self.lints().get_level_source(lint_id);
495 if warn_src.0 != Warn {
505 fn lookup_and_emit(&self, lint: &'static Lint, span: Option<Span>, msg: &str) {
506 let (level, src) = match self.level_src(lint) {
511 raw_emit_lint(&self.sess(), self.lints(), lint, (level, src), span, msg);
518 -> DiagnosticBuilder {
519 let (level, src) = match self.level_src(lint) {
520 None => return self.sess().diagnostic().struct_dummy(),
524 raw_struct_lint(&self.sess(), self.lints(), lint, (level, src), span, msg)
527 /// Emit a lint at the appropriate level, for a particular span.
528 fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) {
529 self.lookup_and_emit(lint, Some(span), msg);
532 fn struct_span_lint(&self,
536 -> DiagnosticBuilder {
537 self.lookup(lint, Some(span), msg)
540 /// Emit a lint and note at the appropriate level, for a particular span.
541 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
542 note_span: Span, note: &str) {
543 let mut err = self.lookup(lint, Some(span), msg);
544 if self.current_level(lint) != Level::Allow {
545 if note_span == span {
546 err.fileline_note(note_span, note);
548 err.span_note(note_span, note);
554 /// Emit a lint and help at the appropriate level, for a particular span.
555 fn span_lint_help(&self, lint: &'static Lint, span: Span,
556 msg: &str, help: &str) {
557 let mut err = self.lookup(lint, Some(span), msg);
558 self.span_lint(lint, span, msg);
559 if self.current_level(lint) != Level::Allow {
560 err.span_help(span, help);
565 /// Emit a lint at the appropriate level, with no associated span.
566 fn lint(&self, lint: &'static Lint, msg: &str) {
567 self.lookup_and_emit(lint, None, msg);
570 /// Merge the lints specified by any lint attributes into the
571 /// current lint context, call the provided function, then reset the
572 /// lints in effect to their previous state.
573 fn with_lint_attrs<F>(&mut self,
574 attrs: &[ast::Attribute],
576 where F: FnOnce(&mut Self),
578 // Parse all of the lint attributes, and then add them all to the
579 // current dictionary of lint information. Along the way, keep a history
580 // of what we changed so we can roll everything back after invoking the
584 for result in gather_attrs(attrs) {
585 let v = match result {
587 span_err!(self.sess(), span, E0452,
588 "malformed lint attribute");
591 Ok((lint_name, level, span)) => {
592 match self.lints().find_lint(&lint_name, &self.sess(), Some(span)) {
593 Ok(lint_id) => vec![(lint_id, level, span)],
594 Err(FindLintError::NotFound) => {
595 match self.lints().lint_groups.get(&lint_name[..]) {
596 Some(&(ref v, _)) => v.iter()
597 .map(|lint_id: &LintId|
598 (*lint_id, level, span))
601 // The lint or lint group doesn't exist.
602 // This is an error, but it was handled
603 // by check_lint_name_attribute.
608 Err(FindLintError::Removed) => { continue; }
613 for (lint_id, level, span) in v {
614 let now = self.lints().get_level_source(lint_id).0;
615 if now == Forbid && level != Forbid {
616 let lint_name = lint_id.as_str();
617 span_err!(self.sess(), span, E0453,
618 "{}({}) overruled by outer forbid({})",
619 level.as_str(), lint_name,
621 } else if now != level {
622 let src = self.lints().get_level_source(lint_id).1;
623 self.level_stack().push((lint_id, (now, src)));
625 self.mut_lints().set_level(lint_id, (level, Node(span)));
630 self.enter_attrs(attrs);
632 self.exit_attrs(attrs);
636 let (lint, lvlsrc) = self.level_stack().pop().unwrap();
637 self.mut_lints().set_level(lint, lvlsrc);
643 impl<'a> EarlyContext<'a> {
644 fn new(sess: &'a Session,
645 krate: &'a ast::Crate) -> EarlyContext<'a> {
646 // We want to own the lint store, so move it out of the session. Remember
647 // to put it back later...
648 let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
658 fn visit_ids<F>(&mut self, f: F)
659 where F: FnOnce(&mut ast_util::IdVisitor<EarlyContext>)
661 let mut v = ast_util::IdVisitor {
663 visited_outermost: false,
669 impl<'a, 'tcx> LateContext<'a, 'tcx> {
670 fn new(tcx: &'a TyCtxt<'tcx>,
671 krate: &'a hir::Crate,
672 access_levels: &'a AccessLevels) -> LateContext<'a, 'tcx> {
673 // We want to own the lint store, so move it out of the session.
674 let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
680 access_levels: access_levels,
683 node_levels: RefCell::new(FnvHashMap()),
687 fn visit_ids<F>(&mut self, f: F)
688 where F: FnOnce(&mut util::IdVisitor<LateContext>)
690 let mut v = util::IdVisitor::new(self);
695 impl<'a, 'tcx> LintContext for LateContext<'a, 'tcx> {
696 /// Get the overall compiler `Session` object.
697 fn sess(&self) -> &Session {
701 fn lints(&self) -> &LintStore {
705 fn mut_lints(&mut self) -> &mut LintStore {
709 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
710 &mut self.level_stack
713 fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
714 debug!("late context: enter_attrs({:?})", attrs);
715 run_lints!(self, enter_lint_attrs, late_passes, attrs);
718 fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
719 debug!("late context: exit_attrs({:?})", attrs);
720 run_lints!(self, exit_lint_attrs, late_passes, attrs);
724 impl<'a> LintContext for EarlyContext<'a> {
725 /// Get the overall compiler `Session` object.
726 fn sess(&self) -> &Session {
730 fn lints(&self) -> &LintStore {
734 fn mut_lints(&mut self) -> &mut LintStore {
738 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
739 &mut self.level_stack
742 fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
743 debug!("early context: enter_attrs({:?})", attrs);
744 run_lints!(self, enter_lint_attrs, early_passes, attrs);
747 fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
748 debug!("early context: exit_attrs({:?})", attrs);
749 run_lints!(self, exit_lint_attrs, early_passes, attrs);
753 impl<'a, 'tcx, 'v> hir_visit::Visitor<'v> for LateContext<'a, 'tcx> {
754 /// Because lints are scoped lexically, we want to walk nested
755 /// items in the context of the outer item, so enable
757 fn visit_nested_item(&mut self, item: hir::ItemId) {
758 self.visit_item(self.tcx.map.expect_item(item.id))
761 fn visit_item(&mut self, it: &hir::Item) {
762 self.with_lint_attrs(&it.attrs, |cx| {
763 run_lints!(cx, check_item, late_passes, it);
764 cx.visit_ids(|v| v.visit_item(it));
765 hir_visit::walk_item(cx, it);
766 run_lints!(cx, check_item_post, late_passes, it);
770 fn visit_foreign_item(&mut self, it: &hir::ForeignItem) {
771 self.with_lint_attrs(&it.attrs, |cx| {
772 run_lints!(cx, check_foreign_item, late_passes, it);
773 hir_visit::walk_foreign_item(cx, it);
774 run_lints!(cx, check_foreign_item_post, late_passes, it);
778 fn visit_pat(&mut self, p: &hir::Pat) {
779 run_lints!(self, check_pat, late_passes, p);
780 hir_visit::walk_pat(self, p);
783 fn visit_expr(&mut self, e: &hir::Expr) {
784 self.with_lint_attrs(e.attrs.as_attr_slice(), |cx| {
785 run_lints!(cx, check_expr, late_passes, e);
786 hir_visit::walk_expr(cx, e);
790 fn visit_stmt(&mut self, s: &hir::Stmt) {
791 // statement attributes are actually just attributes on one of
795 // so we keep track of lint levels there
796 run_lints!(self, check_stmt, late_passes, s);
797 hir_visit::walk_stmt(self, s);
800 fn visit_fn(&mut self, fk: hir_visit::FnKind<'v>, decl: &'v hir::FnDecl,
801 body: &'v hir::Block, span: Span, id: ast::NodeId) {
802 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
803 hir_visit::walk_fn(self, fk, decl, body, span);
804 run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
807 fn visit_variant_data(&mut self,
808 s: &hir::VariantData,
811 item_id: ast::NodeId,
813 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
814 hir_visit::walk_struct_def(self, s);
815 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
818 fn visit_struct_field(&mut self, s: &hir::StructField) {
819 self.with_lint_attrs(&s.attrs, |cx| {
820 run_lints!(cx, check_struct_field, late_passes, s);
821 hir_visit::walk_struct_field(cx, s);
825 fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics, item_id: ast::NodeId) {
826 self.with_lint_attrs(&v.node.attrs, |cx| {
827 run_lints!(cx, check_variant, late_passes, v, g);
828 hir_visit::walk_variant(cx, v, g, item_id);
829 run_lints!(cx, check_variant_post, late_passes, v, g);
833 fn visit_ty(&mut self, t: &hir::Ty) {
834 run_lints!(self, check_ty, late_passes, t);
835 hir_visit::walk_ty(self, t);
838 fn visit_name(&mut self, sp: Span, name: ast::Name) {
839 run_lints!(self, check_name, late_passes, sp, name);
842 fn visit_mod(&mut self, m: &hir::Mod, s: Span, n: ast::NodeId) {
843 run_lints!(self, check_mod, late_passes, m, s, n);
844 hir_visit::walk_mod(self, m);
845 run_lints!(self, check_mod_post, late_passes, m, s, n);
848 fn visit_local(&mut self, l: &hir::Local) {
849 self.with_lint_attrs(l.attrs.as_attr_slice(), |cx| {
850 run_lints!(cx, check_local, late_passes, l);
851 hir_visit::walk_local(cx, l);
855 fn visit_block(&mut self, b: &hir::Block) {
856 run_lints!(self, check_block, late_passes, b);
857 hir_visit::walk_block(self, b);
858 run_lints!(self, check_block_post, late_passes, b);
861 fn visit_arm(&mut self, a: &hir::Arm) {
862 run_lints!(self, check_arm, late_passes, a);
863 hir_visit::walk_arm(self, a);
866 fn visit_decl(&mut self, d: &hir::Decl) {
867 run_lints!(self, check_decl, late_passes, d);
868 hir_visit::walk_decl(self, d);
871 fn visit_expr_post(&mut self, e: &hir::Expr) {
872 run_lints!(self, check_expr_post, late_passes, e);
875 fn visit_generics(&mut self, g: &hir::Generics) {
876 run_lints!(self, check_generics, late_passes, g);
877 hir_visit::walk_generics(self, g);
880 fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
881 self.with_lint_attrs(&trait_item.attrs, |cx| {
882 run_lints!(cx, check_trait_item, late_passes, trait_item);
883 cx.visit_ids(|v| v.visit_trait_item(trait_item));
884 hir_visit::walk_trait_item(cx, trait_item);
885 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
889 fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
890 self.with_lint_attrs(&impl_item.attrs, |cx| {
891 run_lints!(cx, check_impl_item, late_passes, impl_item);
892 cx.visit_ids(|v| v.visit_impl_item(impl_item));
893 hir_visit::walk_impl_item(cx, impl_item);
894 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
898 fn visit_lifetime(&mut self, lt: &hir::Lifetime) {
899 run_lints!(self, check_lifetime, late_passes, lt);
902 fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) {
903 run_lints!(self, check_lifetime_def, late_passes, lt);
906 fn visit_explicit_self(&mut self, es: &hir::ExplicitSelf) {
907 run_lints!(self, check_explicit_self, late_passes, es);
908 hir_visit::walk_explicit_self(self, es);
911 fn visit_path(&mut self, p: &hir::Path, id: ast::NodeId) {
912 run_lints!(self, check_path, late_passes, p, id);
913 hir_visit::walk_path(self, p);
916 fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
917 run_lints!(self, check_path_list_item, late_passes, item);
918 hir_visit::walk_path_list_item(self, prefix, item);
921 fn visit_attribute(&mut self, attr: &ast::Attribute) {
922 check_lint_name_attribute(self, attr);
923 run_lints!(self, check_attribute, late_passes, attr);
927 impl<'a, 'v> ast_visit::Visitor<'v> for EarlyContext<'a> {
928 fn visit_item(&mut self, it: &ast::Item) {
929 self.with_lint_attrs(&it.attrs, |cx| {
930 run_lints!(cx, check_item, early_passes, it);
931 cx.visit_ids(|v| v.visit_item(it));
932 ast_visit::walk_item(cx, it);
933 run_lints!(cx, check_item_post, early_passes, it);
937 fn visit_foreign_item(&mut self, it: &ast::ForeignItem) {
938 self.with_lint_attrs(&it.attrs, |cx| {
939 run_lints!(cx, check_foreign_item, early_passes, it);
940 ast_visit::walk_foreign_item(cx, it);
941 run_lints!(cx, check_foreign_item_post, early_passes, it);
945 fn visit_pat(&mut self, p: &ast::Pat) {
946 run_lints!(self, check_pat, early_passes, p);
947 ast_visit::walk_pat(self, p);
950 fn visit_expr(&mut self, e: &ast::Expr) {
951 self.with_lint_attrs(e.attrs.as_attr_slice(), |cx| {
952 run_lints!(cx, check_expr, early_passes, e);
953 ast_visit::walk_expr(cx, e);
957 fn visit_stmt(&mut self, s: &ast::Stmt) {
958 run_lints!(self, check_stmt, early_passes, s);
959 ast_visit::walk_stmt(self, s);
962 fn visit_fn(&mut self, fk: ast_visit::FnKind<'v>, decl: &'v ast::FnDecl,
963 body: &'v ast::Block, span: Span, id: ast::NodeId) {
964 run_lints!(self, check_fn, early_passes, fk, decl, body, span, id);
965 ast_visit::walk_fn(self, fk, decl, body, span);
966 run_lints!(self, check_fn_post, early_passes, fk, decl, body, span, id);
969 fn visit_variant_data(&mut self,
970 s: &ast::VariantData,
973 item_id: ast::NodeId,
975 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
976 ast_visit::walk_struct_def(self, s);
977 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
980 fn visit_struct_field(&mut self, s: &ast::StructField) {
981 self.with_lint_attrs(&s.node.attrs, |cx| {
982 run_lints!(cx, check_struct_field, early_passes, s);
983 ast_visit::walk_struct_field(cx, s);
987 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, item_id: ast::NodeId) {
988 self.with_lint_attrs(&v.node.attrs, |cx| {
989 run_lints!(cx, check_variant, early_passes, v, g);
990 ast_visit::walk_variant(cx, v, g, item_id);
991 run_lints!(cx, check_variant_post, early_passes, v, g);
995 fn visit_ty(&mut self, t: &ast::Ty) {
996 run_lints!(self, check_ty, early_passes, t);
997 ast_visit::walk_ty(self, t);
1000 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
1001 run_lints!(self, check_ident, early_passes, sp, id);
1004 fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId) {
1005 run_lints!(self, check_mod, early_passes, m, s, n);
1006 ast_visit::walk_mod(self, m);
1007 run_lints!(self, check_mod_post, early_passes, m, s, n);
1010 fn visit_local(&mut self, l: &ast::Local) {
1011 self.with_lint_attrs(l.attrs.as_attr_slice(), |cx| {
1012 run_lints!(cx, check_local, early_passes, l);
1013 ast_visit::walk_local(cx, l);
1017 fn visit_block(&mut self, b: &ast::Block) {
1018 run_lints!(self, check_block, early_passes, b);
1019 ast_visit::walk_block(self, b);
1020 run_lints!(self, check_block_post, early_passes, b);
1023 fn visit_arm(&mut self, a: &ast::Arm) {
1024 run_lints!(self, check_arm, early_passes, a);
1025 ast_visit::walk_arm(self, a);
1028 fn visit_decl(&mut self, d: &ast::Decl) {
1029 run_lints!(self, check_decl, early_passes, d);
1030 ast_visit::walk_decl(self, d);
1033 fn visit_expr_post(&mut self, e: &ast::Expr) {
1034 run_lints!(self, check_expr_post, early_passes, e);
1037 fn visit_generics(&mut self, g: &ast::Generics) {
1038 run_lints!(self, check_generics, early_passes, g);
1039 ast_visit::walk_generics(self, g);
1042 fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
1043 self.with_lint_attrs(&trait_item.attrs, |cx| {
1044 run_lints!(cx, check_trait_item, early_passes, trait_item);
1045 cx.visit_ids(|v| v.visit_trait_item(trait_item));
1046 ast_visit::walk_trait_item(cx, trait_item);
1047 run_lints!(cx, check_trait_item_post, early_passes, trait_item);
1051 fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
1052 self.with_lint_attrs(&impl_item.attrs, |cx| {
1053 run_lints!(cx, check_impl_item, early_passes, impl_item);
1054 cx.visit_ids(|v| v.visit_impl_item(impl_item));
1055 ast_visit::walk_impl_item(cx, impl_item);
1056 run_lints!(cx, check_impl_item_post, early_passes, impl_item);
1060 fn visit_lifetime(&mut self, lt: &ast::Lifetime) {
1061 run_lints!(self, check_lifetime, early_passes, lt);
1064 fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) {
1065 run_lints!(self, check_lifetime_def, early_passes, lt);
1068 fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf) {
1069 run_lints!(self, check_explicit_self, early_passes, es);
1070 ast_visit::walk_explicit_self(self, es);
1073 fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId) {
1074 run_lints!(self, check_path, early_passes, p, id);
1075 ast_visit::walk_path(self, p);
1078 fn visit_path_list_item(&mut self, prefix: &ast::Path, item: &ast::PathListItem) {
1079 run_lints!(self, check_path_list_item, early_passes, item);
1080 ast_visit::walk_path_list_item(self, prefix, item);
1083 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1084 run_lints!(self, check_attribute, early_passes, attr);
1088 // Output any lints that were previously added to the session.
1089 impl<'a, 'tcx> IdVisitingOperation for LateContext<'a, 'tcx> {
1090 fn visit_id(&mut self, id: ast::NodeId) {
1091 match self.sess().lints.borrow_mut().remove(&id) {
1094 debug!("LateContext::visit_id: id={:?} lints={:?}", id, lints);
1095 for (lint_id, span, msg) in lints {
1096 self.span_lint(lint_id.lint, span, &msg[..])
1102 impl<'a> IdVisitingOperation for EarlyContext<'a> {
1103 fn visit_id(&mut self, id: ast::NodeId) {
1104 match self.sess.lints.borrow_mut().remove(&id) {
1107 for (lint_id, span, msg) in lints {
1108 self.span_lint(lint_id.lint, span, &msg[..])
1115 // This lint pass is defined here because it touches parts of the `LateContext`
1116 // that we don't want to expose. It records the lint level at certain AST
1117 // nodes, so that the variant size difference check in trans can call
1120 pub struct GatherNodeLevels;
1122 impl LintPass for GatherNodeLevels {
1123 fn get_lints(&self) -> LintArray {
1128 impl LateLintPass for GatherNodeLevels {
1129 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1131 hir::ItemEnum(..) => {
1132 let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCES);
1133 let lvlsrc = cx.lints.get_level_source(lint_id);
1135 (lvl, _) if lvl != Allow => {
1136 cx.node_levels.borrow_mut()
1137 .insert((it.id, lint_id), lvlsrc);
1147 enum CheckLintNameResult {
1149 // Lint doesn't exist
1151 // The lint is either renamed or removed. This is the warning
1156 /// Checks the name of a lint for its existence, and whether it was
1157 /// renamed or removed. Generates a DiagnosticBuilder containing a
1158 /// warning for renamed and removed lints. This is over both lint
1159 /// names from attributes and those passed on the command line. Since
1160 /// it emits non-fatal warnings and there are *two* lint passes that
1161 /// inspect attributes, this is only run from the late pass to avoid
1162 /// printing duplicate warnings.
1163 fn check_lint_name(lint_cx: &LintStore,
1164 lint_name: &str) -> CheckLintNameResult {
1165 match lint_cx.by_name.get(lint_name) {
1166 Some(&Renamed(ref new_name, _)) => {
1167 CheckLintNameResult::Warning(
1168 format!("lint {} has been renamed to {}", lint_name, new_name)
1171 Some(&Removed(ref reason)) => {
1172 CheckLintNameResult::Warning(
1173 format!("lint {} has been removed: {}", lint_name, reason)
1177 match lint_cx.lint_groups.get(lint_name) {
1179 CheckLintNameResult::NoLint
1182 /* lint group exists */
1183 CheckLintNameResult::Ok
1189 CheckLintNameResult::Ok
1194 // Checks the validity of lint names derived from attributes
1195 fn check_lint_name_attribute(cx: &LateContext, attr: &ast::Attribute) {
1196 for result in gather_attr(attr) {
1199 // Malformed lint attr. Reported by with_lint_attrs
1202 Ok((lint_name, _, span)) => {
1203 match check_lint_name(&cx.lints,
1205 CheckLintNameResult::Ok => (),
1206 CheckLintNameResult::Warning(ref msg) => {
1207 cx.span_lint(builtin::RENAMED_AND_REMOVED_LINTS,
1210 CheckLintNameResult::NoLint => {
1211 cx.span_lint(builtin::UNKNOWN_LINTS, span,
1212 &format!("unknown lint: `{}`",
1221 // Checks the validity of lint names derived from the command line
1222 fn check_lint_name_cmdline(sess: &Session, lint_cx: &LintStore,
1223 lint_name: &str, level: Level) {
1224 let db = match check_lint_name(lint_cx, lint_name) {
1225 CheckLintNameResult::Ok => None,
1226 CheckLintNameResult::Warning(ref msg) => {
1227 Some(sess.struct_warn(msg))
1229 CheckLintNameResult::NoLint => {
1230 Some(sess.struct_err(&format!("unknown lint: `{}`", lint_name)))
1234 if let Some(mut db) = db {
1235 let msg = format!("requested on the command line with `{} {}`",
1237 Level::Allow => "-A",
1238 Level::Warn => "-W",
1239 Level::Deny => "-D",
1240 Level::Forbid => "-F",
1249 /// Perform lint checking on a crate.
1251 /// Consumes the `lint_store` field of the `Session`.
1252 pub fn check_crate(tcx: &TyCtxt, access_levels: &AccessLevels) {
1253 let _task = tcx.dep_graph.in_task(DepNode::LateLintCheck);
1255 let krate = tcx.map.krate();
1256 let mut cx = LateContext::new(tcx, krate, access_levels);
1258 // Visit the whole crate.
1259 cx.with_lint_attrs(&krate.attrs, |cx| {
1260 cx.visit_id(ast::CRATE_NODE_ID);
1262 hir_visit::walk_crate(v, krate);
1265 // since the root module isn't visited as an item (because it isn't an
1266 // item), warn for it here.
1267 run_lints!(cx, check_crate, late_passes, krate);
1269 hir_visit::walk_crate(cx, krate);
1271 run_lints!(cx, check_crate_post, late_passes, krate);
1274 // If we missed any lints added to the session, then there's a bug somewhere
1275 // in the iteration code.
1276 for (id, v) in tcx.sess.lints.borrow().iter() {
1277 for &(lint, span, ref msg) in v {
1278 tcx.sess.span_bug(span,
1279 &format!("unprocessed lint {} at {}: {}",
1280 lint.as_str(), tcx.map.node_to_string(*id), *msg))
1284 *tcx.node_lint_levels.borrow_mut() = cx.node_levels.into_inner();
1286 // Put the lint store back in the session.
1287 mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), cx.lints);
1290 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1291 let mut cx = EarlyContext::new(sess, krate);
1293 // Visit the whole crate.
1294 cx.with_lint_attrs(&krate.attrs, |cx| {
1295 cx.visit_id(ast::CRATE_NODE_ID);
1297 v.visited_outermost = true;
1298 ast_visit::walk_crate(v, krate);
1301 // since the root module isn't visited as an item (because it isn't an
1302 // item), warn for it here.
1303 run_lints!(cx, check_crate, early_passes, krate);
1305 ast_visit::walk_crate(cx, krate);
1307 run_lints!(cx, check_crate_post, early_passes, krate);
1310 // Put the lint store back in the session.
1311 mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1313 // If we missed any lints added to the session, then there's a bug somewhere
1314 // in the iteration code.
1315 for (_, v) in sess.lints.borrow().iter() {
1316 for &(lint, span, ref msg) in v {
1318 &format!("unprocessed lint {}: {}",
1319 lint.as_str(), *msg))