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 ty::{self, TyCtxt};
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 rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
37 use util::nodemap::FxHashMap;
40 use std::default::Default as StdDefault;
45 use syntax_pos::{MultiSpan, Span};
46 use errors::{self, Diagnostic, DiagnosticBuilder};
48 use hir::intravisit as hir_visit;
49 use syntax::visit as ast_visit;
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: FxHashMap<String, TargetLint>,
69 /// Current levels of each lint, and where they were set.
70 levels: FxHashMap<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: FxHashMap<&'static str, (Vec<LintId>, bool)>,
76 /// Extra info for future incompatibility lints, descibing the
77 /// issue or RFC that caused the incompatibility.
78 future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
80 /// Maximum level a lint can be
81 lint_cap: Option<Level>,
84 /// When you call `add_lint` on the session, you wind up storing one
85 /// of these, which records a "potential lint" at a particular point.
86 #[derive(PartialEq, RustcEncodable, RustcDecodable)]
87 pub struct EarlyLint {
88 /// what lint is this? (e.g., `dead_code`)
92 pub diagnostic: Diagnostic,
95 impl fmt::Debug for EarlyLint {
96 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97 f.debug_struct("EarlyLint")
98 .field("id", &self.id)
99 .field("span", &self.diagnostic.span)
100 .field("diagnostic", &self.diagnostic)
105 pub trait IntoEarlyLint {
106 fn into_early_lint(self, id: LintId) -> EarlyLint;
109 impl<'a, S: Into<MultiSpan>> IntoEarlyLint for (S, &'a str) {
110 fn into_early_lint(self, id: LintId) -> EarlyLint {
111 let (span, msg) = self;
112 let mut diagnostic = Diagnostic::new(errors::Level::Warning, msg);
113 diagnostic.set_span(span);
114 EarlyLint { id: id, diagnostic: diagnostic }
118 impl IntoEarlyLint for Diagnostic {
119 fn into_early_lint(self, id: LintId) -> EarlyLint {
120 EarlyLint { id: id, diagnostic: self }
124 /// Extra information for a future incompatibility lint. See the call
125 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
127 pub struct FutureIncompatibleInfo {
129 pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
132 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
134 /// A direct lint target
137 /// Temporary renaming, used for easing migration pain; see #16545
138 Renamed(String, LintId),
140 /// Lint with this name existed previously, but has been removed/deprecated.
141 /// The string argument is the reason for removal.
151 fn get_level_source(&self, lint: LintId) -> LevelSource {
152 match self.levels.get(&lint) {
154 None => (Allow, Default),
158 fn set_level(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
159 if let Some(cap) = self.lint_cap {
160 lvlsrc.0 = cmp::min(lvlsrc.0, cap);
162 if lvlsrc.0 == Allow {
163 self.levels.remove(&lint);
165 self.levels.insert(lint, lvlsrc);
169 pub fn new() -> LintStore {
172 early_passes: Some(vec![]),
173 late_passes: Some(vec![]),
174 by_name: FxHashMap(),
176 future_incompatible: FxHashMap(),
177 lint_groups: FxHashMap(),
182 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
186 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
187 self.lint_groups.iter().map(|(k, v)| (*k,
192 pub fn register_early_pass(&mut self,
193 sess: Option<&Session>,
195 pass: EarlyLintPassObject) {
196 self.push_pass(sess, from_plugin, &pass);
197 self.early_passes.as_mut().unwrap().push(pass);
200 pub fn register_late_pass(&mut self,
201 sess: Option<&Session>,
203 pass: LateLintPassObject) {
204 self.push_pass(sess, from_plugin, &pass);
205 self.late_passes.as_mut().unwrap().push(pass);
208 // Helper method for register_early/late_pass
209 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
210 sess: Option<&Session>,
213 for &lint in pass.get_lints() {
214 self.lints.push((*lint, from_plugin));
216 let id = LintId::of(*lint);
217 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
218 let msg = format!("duplicate specification of lint {}", lint.name_lower());
219 match (sess, from_plugin) {
220 // We load builtin lints first, so a duplicate is a compiler bug.
221 // Use early_error when handling -W help with no crate.
222 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
223 (Some(_), false) => bug!("{}", msg),
225 // A duplicate name from a plugin is a user error.
226 (Some(sess), true) => sess.err(&msg[..]),
230 if lint.default_level != Allow {
231 self.levels.insert(id, (lint.default_level, Default));
236 pub fn register_future_incompatible(&mut self,
237 sess: Option<&Session>,
238 lints: Vec<FutureIncompatibleInfo>) {
239 let ids = lints.iter().map(|f| f.id).collect();
240 self.register_group(sess, false, "future_incompatible", ids);
242 self.future_incompatible.insert(info.id, info);
246 pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
247 self.future_incompatible.get(&id)
250 pub fn register_group(&mut self, sess: Option<&Session>,
251 from_plugin: bool, name: &'static str,
253 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
256 let msg = format!("duplicate specification of lint group {}", name);
257 match (sess, from_plugin) {
258 // We load builtin lints first, so a duplicate is a compiler bug.
259 // Use early_error when handling -W help with no crate.
260 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
261 (Some(_), false) => bug!("{}", msg),
263 // A duplicate name from a plugin is a user error.
264 (Some(sess), true) => sess.err(&msg[..]),
269 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
270 let target = match self.by_name.get(new_name) {
271 Some(&Id(lint_id)) => lint_id.clone(),
272 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
274 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
277 pub fn register_removed(&mut self, name: &str, reason: &str) {
278 self.by_name.insert(name.into(), Removed(reason.into()));
281 #[allow(unused_variables)]
282 fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
283 -> Result<LintId, FindLintError>
285 match self.by_name.get(lint_name) {
286 Some(&Id(lint_id)) => Ok(lint_id),
287 Some(&Renamed(_, lint_id)) => {
290 Some(&Removed(ref reason)) => {
291 Err(FindLintError::Removed)
293 None => Err(FindLintError::NotFound)
297 pub fn process_command_line(&mut self, sess: &Session) {
298 for &(ref lint_name, level) in &sess.opts.lint_opts {
299 check_lint_name_cmdline(sess, self,
300 &lint_name[..], level);
302 match self.find_lint(&lint_name[..], sess, None) {
303 Ok(lint_id) => self.set_level(lint_id, (level, CommandLine)),
304 Err(FindLintError::Removed) => { }
306 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
307 .collect::<FxHashMap<&'static str,
309 .get(&lint_name[..]) {
312 .map(|lint_id: &LintId|
313 self.set_level(*lint_id, (level, CommandLine)))
314 .collect::<Vec<()>>();
317 // The lint or lint group doesn't exist.
318 // This is an error, but it was handled
319 // by check_lint_name_cmdline.
326 self.lint_cap = sess.opts.lint_cap;
327 if let Some(cap) = self.lint_cap {
328 for level in self.levels.iter_mut().map(|p| &mut (p.1).0) {
329 *level = cmp::min(*level, cap);
335 /// Context for lint checking after type checking.
336 pub struct LateContext<'a, 'tcx: 'a> {
337 /// Type context we're checking in.
338 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
340 /// Side-tables for the body we are in.
341 pub tables: &'a ty::TypeckTables<'tcx>,
343 /// The crate being checked.
344 pub krate: &'a hir::Crate,
346 /// Items accessible from the crate being checked.
347 pub access_levels: &'a AccessLevels,
349 /// The store of registered lints.
352 /// When recursing into an attributed node of the ast which modifies lint
353 /// levels, this stack keeps track of the previous lint levels of whatever
355 level_stack: Vec<(LintId, LevelSource)>,
358 /// Context for lint checking of the AST, after expansion, before lowering to
360 pub struct EarlyContext<'a> {
361 /// Type context we're checking in.
362 pub sess: &'a Session,
364 /// The crate being checked.
365 pub krate: &'a ast::Crate,
367 /// The store of registered lints.
370 /// When recursing into an attributed node of the ast which modifies lint
371 /// levels, this stack keeps track of the previous lint levels of whatever
373 level_stack: Vec<(LintId, LevelSource)>,
376 /// Convenience macro for calling a `LintPass` method on every pass in the context.
377 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
378 // Move the vector of passes out of `$cx` so that we can
379 // iterate over it mutably while passing `$cx` to the methods.
380 let mut passes = $cx.mut_lints().$ps.take().unwrap();
381 for obj in &mut passes {
382 obj.$f($cx, $($args),*);
384 $cx.mut_lints().$ps = Some(passes);
387 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
388 /// attributes. Writing this as an iterator is an enormous mess.
389 // See also the hir version just below.
390 pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec<Result<(ast::Name, Level, Span), Span>> {
391 let mut out = vec![];
393 let r = gather_attr(attr);
394 out.extend(r.into_iter());
399 pub fn gather_attr(attr: &ast::Attribute) -> Vec<Result<(ast::Name, Level, Span), Span>> {
400 let mut out = vec![];
402 let level = match Level::from_str(&attr.name().as_str()) {
407 attr::mark_used(attr);
409 let meta = &attr.value;
410 let metas = if let Some(metas) = meta.meta_item_list() {
413 out.push(Err(meta.span));
418 out.push(li.word().map_or(Err(li.span), |word| Ok((word.name(), level, word.span))));
424 /// Emit a lint as a warning or an error (or not at all)
425 /// according to `level`.
427 /// This lives outside of `Context` so it can be used by checks
428 /// in trans that run after the main lint pass is finished. Most
429 /// lints elsewhere in the compiler should call
430 /// `Session::add_lint()` instead.
431 pub fn raw_emit_lint<S: Into<MultiSpan>>(sess: &Session,
437 raw_struct_lint(sess, lints, lint, lvlsrc, span, msg).emit();
440 pub fn raw_struct_lint<'a, S>(sess: &'a Session,
446 -> DiagnosticBuilder<'a>
447 where S: Into<MultiSpan>
449 let (mut level, source) = lvlsrc;
451 return sess.diagnostic().struct_dummy();
454 let name = lint.name_lower();
456 let msg = match source {
458 format!("{}, #[{}({})] on by default", msg,
459 level.as_str(), name)
462 format!("{} [-{} {}]", msg,
464 Warn => 'W', Deny => 'D', Forbid => 'F',
466 }, name.replace("_", "-"))
474 // For purposes of printing, we can treat forbid as deny.
475 if level == Forbid { level = Deny; }
477 let mut err = match (level, span) {
478 (Warn, Some(sp)) => sess.struct_span_warn(sp, &msg[..]),
479 (Warn, None) => sess.struct_warn(&msg[..]),
480 (Deny, Some(sp)) => sess.struct_span_err(sp, &msg[..]),
481 (Deny, None) => sess.struct_err(&msg[..]),
482 _ => bug!("impossible level in raw_emit_lint"),
485 // Check for future incompatibility lints and issue a stronger warning.
486 if let Some(future_incompatible) = lints.future_incompatible(LintId::of(lint)) {
487 let explanation = format!("this was previously accepted by the compiler \
488 but is being phased out; \
489 it will become a hard error in a future release!");
490 let citation = format!("for more information, see {}",
491 future_incompatible.reference);
492 err.warn(&explanation);
496 if let Some(span) = def {
497 sess.diag_span_note_once(&mut err, lint, span, "lint level defined here");
503 pub trait LintContext<'tcx>: Sized {
504 fn sess(&self) -> &Session;
505 fn lints(&self) -> &LintStore;
506 fn mut_lints(&mut self) -> &mut LintStore;
507 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>;
508 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
509 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
511 /// Get the level of `lint` at the current position of the lint
513 fn current_level(&self, lint: &'static Lint) -> Level {
514 self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
517 fn level_src(&self, lint: &'static Lint) -> Option<LevelSource> {
518 self.lints().levels.get(&LintId::of(lint)).map(|ls| match ls {
520 let lint_id = LintId::of(builtin::WARNINGS);
521 let warn_src = self.lints().get_level_source(lint_id);
522 if warn_src.0 != Warn {
532 fn lookup_and_emit<S: Into<MultiSpan>>(&self,
536 let (level, src) = match self.level_src(lint) {
541 raw_emit_lint(&self.sess(), self.lints(), lint, (level, src), span, msg);
544 fn lookup<S: Into<MultiSpan>>(&self,
548 -> DiagnosticBuilder {
549 let (level, src) = match self.level_src(lint) {
550 None => return self.sess().diagnostic().struct_dummy(),
554 raw_struct_lint(&self.sess(), self.lints(), lint, (level, src), span, msg)
557 /// Emit a lint at the appropriate level, for a particular span.
558 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
559 self.lookup_and_emit(lint, Some(span), msg);
562 fn early_lint(&self, early_lint: &EarlyLint) {
563 let span = early_lint.diagnostic.span.primary_span().expect("early lint w/o primary span");
564 let mut err = self.struct_span_lint(early_lint.id.lint,
566 &early_lint.diagnostic.message());
567 err.copy_details_not_message(&early_lint.diagnostic);
571 fn struct_span_lint<S: Into<MultiSpan>>(&self,
575 -> DiagnosticBuilder {
576 self.lookup(lint, Some(span), msg)
579 /// Emit a lint and note at the appropriate level, for a particular span.
580 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
581 note_span: Span, note: &str) {
582 let mut err = self.lookup(lint, Some(span), msg);
583 if self.current_level(lint) != Level::Allow {
584 if note_span == span {
587 err.span_note(note_span, note);
593 /// Emit a lint and help at the appropriate level, for a particular span.
594 fn span_lint_help(&self, lint: &'static Lint, span: Span,
595 msg: &str, help: &str) {
596 let mut err = self.lookup(lint, Some(span), msg);
597 self.span_lint(lint, span, msg);
598 if self.current_level(lint) != Level::Allow {
599 err.span_help(span, help);
604 /// Emit a lint at the appropriate level, with no associated span.
605 fn lint(&self, lint: &'static Lint, msg: &str) {
606 self.lookup_and_emit(lint, None as Option<Span>, msg);
609 /// Merge the lints specified by any lint attributes into the
610 /// current lint context, call the provided function, then reset the
611 /// lints in effect to their previous state.
612 fn with_lint_attrs<F>(&mut self,
613 attrs: &'tcx [ast::Attribute],
615 where F: FnOnce(&mut Self),
617 // Parse all of the lint attributes, and then add them all to the
618 // current dictionary of lint information. Along the way, keep a history
619 // of what we changed so we can roll everything back after invoking the
623 for result in gather_attrs(attrs) {
624 let v = match result {
626 span_err!(self.sess(), span, E0452,
627 "malformed lint attribute");
630 Ok((lint_name, level, span)) => {
631 match self.lints().find_lint(&lint_name.as_str(), &self.sess(), Some(span)) {
632 Ok(lint_id) => vec![(lint_id, level, span)],
633 Err(FindLintError::NotFound) => {
634 match self.lints().lint_groups.get(&*lint_name.as_str()) {
635 Some(&(ref v, _)) => v.iter()
636 .map(|lint_id: &LintId|
637 (*lint_id, level, span))
640 // The lint or lint group doesn't exist.
641 // This is an error, but it was handled
642 // by check_lint_name_attribute.
647 Err(FindLintError::Removed) => { continue; }
652 for (lint_id, level, span) in v {
653 let (now, now_source) = self.lints().get_level_source(lint_id);
654 if now == Forbid && level != Forbid {
655 let lint_name = lint_id.to_string();
656 let mut diag_builder = struct_span_err!(self.sess(), span, E0453,
657 "{}({}) overruled by outer forbid({})",
658 level.as_str(), lint_name,
660 diag_builder.span_label(span, &format!("overruled by previous forbid"));
662 LintSource::Default => &mut diag_builder,
663 LintSource::Node(forbid_source_span) => {
664 diag_builder.span_label(forbid_source_span,
665 &format!("`forbid` level set here"))
667 LintSource::CommandLine => {
668 diag_builder.note("`forbid` lint level was set on command line")
671 } else if now != level {
672 let src = self.lints().get_level_source(lint_id).1;
673 self.level_stack().push((lint_id, (now, src)));
675 self.mut_lints().set_level(lint_id, (level, Node(span)));
680 self.enter_attrs(attrs);
682 self.exit_attrs(attrs);
686 let (lint, lvlsrc) = self.level_stack().pop().unwrap();
687 self.mut_lints().set_level(lint, lvlsrc);
693 impl<'a> EarlyContext<'a> {
694 fn new(sess: &'a Session,
695 krate: &'a ast::Crate) -> EarlyContext<'a> {
696 // We want to own the lint store, so move it out of the session. Remember
697 // to put it back later...
698 let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
709 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
710 /// Get the overall compiler `Session` object.
711 fn sess(&self) -> &Session {
715 fn lints(&self) -> &LintStore {
719 fn mut_lints(&mut self) -> &mut LintStore {
723 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
724 &mut self.level_stack
727 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
728 debug!("late context: enter_attrs({:?})", attrs);
729 run_lints!(self, enter_lint_attrs, late_passes, attrs);
732 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
733 debug!("late context: exit_attrs({:?})", attrs);
734 run_lints!(self, exit_lint_attrs, late_passes, attrs);
738 impl<'a> LintContext<'a> for EarlyContext<'a> {
739 /// Get the overall compiler `Session` object.
740 fn sess(&self) -> &Session {
744 fn lints(&self) -> &LintStore {
748 fn mut_lints(&mut self) -> &mut LintStore {
752 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
753 &mut self.level_stack
756 fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
757 debug!("early context: enter_attrs({:?})", attrs);
758 run_lints!(self, enter_lint_attrs, early_passes, attrs);
761 fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
762 debug!("early context: exit_attrs({:?})", attrs);
763 run_lints!(self, exit_lint_attrs, early_passes, attrs);
767 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
768 /// Because lints are scoped lexically, we want to walk nested
769 /// items in the context of the outer item, so enable
771 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
772 hir_visit::NestedVisitorMap::All(&self.tcx.hir)
775 // Output any lints that were previously added to the session.
776 fn visit_id(&mut self, id: ast::NodeId) {
777 let lints = self.sess().lints.borrow_mut().take(id);
778 for early_lint in lints.iter().chain(self.tables.lints.get(id)) {
779 debug!("LateContext::visit_id: id={:?} early_lint={:?}", id, early_lint);
780 self.early_lint(early_lint);
784 fn visit_nested_body(&mut self, body: hir::BodyId) {
785 let old_tables = self.tables;
786 self.tables = self.tcx.body_tables(body);
787 let body = self.tcx.hir.body(body);
788 self.visit_body(body);
789 self.tables = old_tables;
792 fn visit_item(&mut self, it: &'tcx hir::Item) {
793 self.with_lint_attrs(&it.attrs, |cx| {
794 run_lints!(cx, check_item, late_passes, it);
795 hir_visit::walk_item(cx, it);
796 run_lints!(cx, check_item_post, late_passes, it);
800 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
801 self.with_lint_attrs(&it.attrs, |cx| {
802 run_lints!(cx, check_foreign_item, late_passes, it);
803 hir_visit::walk_foreign_item(cx, it);
804 run_lints!(cx, check_foreign_item_post, late_passes, it);
808 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
809 run_lints!(self, check_pat, late_passes, p);
810 hir_visit::walk_pat(self, p);
813 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
814 self.with_lint_attrs(&e.attrs, |cx| {
815 run_lints!(cx, check_expr, late_passes, e);
816 hir_visit::walk_expr(cx, e);
817 run_lints!(cx, check_expr_post, late_passes, e);
821 fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
822 // statement attributes are actually just attributes on one of
826 // so we keep track of lint levels there
827 run_lints!(self, check_stmt, late_passes, s);
828 hir_visit::walk_stmt(self, s);
831 fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
832 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
833 // Wrap in tables here, not just in visit_nested_body,
834 // in order for `check_fn` to be able to use them.
835 let old_tables = self.tables;
836 self.tables = self.tcx.body_tables(body_id);
837 let body = self.tcx.hir.body(body_id);
838 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
839 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
840 run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
841 self.tables = old_tables;
844 fn visit_variant_data(&mut self,
845 s: &'tcx hir::VariantData,
847 g: &'tcx hir::Generics,
848 item_id: ast::NodeId,
850 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
851 hir_visit::walk_struct_def(self, s);
852 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
855 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
856 self.with_lint_attrs(&s.attrs, |cx| {
857 run_lints!(cx, check_struct_field, late_passes, s);
858 hir_visit::walk_struct_field(cx, s);
862 fn visit_variant(&mut self,
863 v: &'tcx hir::Variant,
864 g: &'tcx hir::Generics,
865 item_id: ast::NodeId) {
866 self.with_lint_attrs(&v.node.attrs, |cx| {
867 run_lints!(cx, check_variant, late_passes, v, g);
868 hir_visit::walk_variant(cx, v, g, item_id);
869 run_lints!(cx, check_variant_post, late_passes, v, g);
873 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
874 run_lints!(self, check_ty, late_passes, t);
875 hir_visit::walk_ty(self, t);
878 fn visit_name(&mut self, sp: Span, name: ast::Name) {
879 run_lints!(self, check_name, late_passes, sp, name);
882 fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
883 run_lints!(self, check_mod, late_passes, m, s, n);
884 hir_visit::walk_mod(self, m, n);
885 run_lints!(self, check_mod_post, late_passes, m, s, n);
888 fn visit_local(&mut self, l: &'tcx hir::Local) {
889 self.with_lint_attrs(&l.attrs, |cx| {
890 run_lints!(cx, check_local, late_passes, l);
891 hir_visit::walk_local(cx, l);
895 fn visit_block(&mut self, b: &'tcx hir::Block) {
896 run_lints!(self, check_block, late_passes, b);
897 hir_visit::walk_block(self, b);
898 run_lints!(self, check_block_post, late_passes, b);
901 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
902 run_lints!(self, check_arm, late_passes, a);
903 hir_visit::walk_arm(self, a);
906 fn visit_decl(&mut self, d: &'tcx hir::Decl) {
907 run_lints!(self, check_decl, late_passes, d);
908 hir_visit::walk_decl(self, d);
911 fn visit_generics(&mut self, g: &'tcx hir::Generics) {
912 run_lints!(self, check_generics, late_passes, g);
913 hir_visit::walk_generics(self, g);
916 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
917 self.with_lint_attrs(&trait_item.attrs, |cx| {
918 run_lints!(cx, check_trait_item, late_passes, trait_item);
919 hir_visit::walk_trait_item(cx, trait_item);
920 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
924 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
925 self.with_lint_attrs(&impl_item.attrs, |cx| {
926 run_lints!(cx, check_impl_item, late_passes, impl_item);
927 hir_visit::walk_impl_item(cx, impl_item);
928 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
932 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
933 run_lints!(self, check_lifetime, late_passes, lt);
934 hir_visit::walk_lifetime(self, lt);
937 fn visit_lifetime_def(&mut self, lt: &'tcx hir::LifetimeDef) {
938 run_lints!(self, check_lifetime_def, late_passes, lt);
939 hir_visit::walk_lifetime_def(self, lt);
942 fn visit_path(&mut self, p: &'tcx hir::Path, id: ast::NodeId) {
943 run_lints!(self, check_path, late_passes, p, id);
944 hir_visit::walk_path(self, p);
947 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
948 check_lint_name_attribute(self, attr);
949 run_lints!(self, check_attribute, late_passes, attr);
953 impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> {
954 fn visit_item(&mut self, it: &'a ast::Item) {
955 self.with_lint_attrs(&it.attrs, |cx| {
956 run_lints!(cx, check_item, early_passes, it);
957 ast_visit::walk_item(cx, it);
958 run_lints!(cx, check_item_post, early_passes, it);
962 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
963 self.with_lint_attrs(&it.attrs, |cx| {
964 run_lints!(cx, check_foreign_item, early_passes, it);
965 ast_visit::walk_foreign_item(cx, it);
966 run_lints!(cx, check_foreign_item_post, early_passes, it);
970 fn visit_pat(&mut self, p: &'a ast::Pat) {
971 run_lints!(self, check_pat, early_passes, p);
972 ast_visit::walk_pat(self, p);
975 fn visit_expr(&mut self, e: &'a ast::Expr) {
976 self.with_lint_attrs(&e.attrs, |cx| {
977 run_lints!(cx, check_expr, early_passes, e);
978 ast_visit::walk_expr(cx, e);
982 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
983 run_lints!(self, check_stmt, early_passes, s);
984 ast_visit::walk_stmt(self, s);
987 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
988 span: Span, id: ast::NodeId) {
989 run_lints!(self, check_fn, early_passes, fk, decl, span, id);
990 ast_visit::walk_fn(self, fk, decl, span);
991 run_lints!(self, check_fn_post, early_passes, fk, decl, span, id);
994 fn visit_variant_data(&mut self,
995 s: &'a ast::VariantData,
997 g: &'a ast::Generics,
998 item_id: ast::NodeId,
1000 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
1001 ast_visit::walk_struct_def(self, s);
1002 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
1005 fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1006 self.with_lint_attrs(&s.attrs, |cx| {
1007 run_lints!(cx, check_struct_field, early_passes, s);
1008 ast_visit::walk_struct_field(cx, s);
1012 fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1013 self.with_lint_attrs(&v.node.attrs, |cx| {
1014 run_lints!(cx, check_variant, early_passes, v, g);
1015 ast_visit::walk_variant(cx, v, g, item_id);
1016 run_lints!(cx, check_variant_post, early_passes, v, g);
1020 fn visit_ty(&mut self, t: &'a ast::Ty) {
1021 run_lints!(self, check_ty, early_passes, t);
1022 ast_visit::walk_ty(self, t);
1025 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
1026 run_lints!(self, check_ident, early_passes, sp, id);
1029 fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, n: ast::NodeId) {
1030 run_lints!(self, check_mod, early_passes, m, s, n);
1031 ast_visit::walk_mod(self, m);
1032 run_lints!(self, check_mod_post, early_passes, m, s, n);
1035 fn visit_local(&mut self, l: &'a ast::Local) {
1036 self.with_lint_attrs(&l.attrs, |cx| {
1037 run_lints!(cx, check_local, early_passes, l);
1038 ast_visit::walk_local(cx, l);
1042 fn visit_block(&mut self, b: &'a ast::Block) {
1043 run_lints!(self, check_block, early_passes, b);
1044 ast_visit::walk_block(self, b);
1045 run_lints!(self, check_block_post, early_passes, b);
1048 fn visit_arm(&mut self, a: &'a ast::Arm) {
1049 run_lints!(self, check_arm, early_passes, a);
1050 ast_visit::walk_arm(self, a);
1053 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1054 run_lints!(self, check_expr_post, early_passes, e);
1057 fn visit_generics(&mut self, g: &'a ast::Generics) {
1058 run_lints!(self, check_generics, early_passes, g);
1059 ast_visit::walk_generics(self, g);
1062 fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1063 self.with_lint_attrs(&trait_item.attrs, |cx| {
1064 run_lints!(cx, check_trait_item, early_passes, trait_item);
1065 ast_visit::walk_trait_item(cx, trait_item);
1066 run_lints!(cx, check_trait_item_post, early_passes, trait_item);
1070 fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1071 self.with_lint_attrs(&impl_item.attrs, |cx| {
1072 run_lints!(cx, check_impl_item, early_passes, impl_item);
1073 ast_visit::walk_impl_item(cx, impl_item);
1074 run_lints!(cx, check_impl_item_post, early_passes, impl_item);
1078 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1079 run_lints!(self, check_lifetime, early_passes, lt);
1082 fn visit_lifetime_def(&mut self, lt: &'a ast::LifetimeDef) {
1083 run_lints!(self, check_lifetime_def, early_passes, lt);
1086 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1087 run_lints!(self, check_path, early_passes, p, id);
1088 ast_visit::walk_path(self, p);
1091 fn visit_path_list_item(&mut self, prefix: &'a ast::Path, item: &'a ast::PathListItem) {
1092 run_lints!(self, check_path_list_item, early_passes, item);
1093 ast_visit::walk_path_list_item(self, prefix, item);
1096 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1097 run_lints!(self, check_attribute, early_passes, attr);
1101 enum CheckLintNameResult {
1103 // Lint doesn't exist
1105 // The lint is either renamed or removed. This is the warning
1110 /// Checks the name of a lint for its existence, and whether it was
1111 /// renamed or removed. Generates a DiagnosticBuilder containing a
1112 /// warning for renamed and removed lints. This is over both lint
1113 /// names from attributes and those passed on the command line. Since
1114 /// it emits non-fatal warnings and there are *two* lint passes that
1115 /// inspect attributes, this is only run from the late pass to avoid
1116 /// printing duplicate warnings.
1117 fn check_lint_name(lint_cx: &LintStore,
1118 lint_name: &str) -> CheckLintNameResult {
1119 match lint_cx.by_name.get(lint_name) {
1120 Some(&Renamed(ref new_name, _)) => {
1121 CheckLintNameResult::Warning(
1122 format!("lint {} has been renamed to {}", lint_name, new_name)
1125 Some(&Removed(ref reason)) => {
1126 CheckLintNameResult::Warning(
1127 format!("lint {} has been removed: {}", lint_name, reason)
1131 match lint_cx.lint_groups.get(lint_name) {
1133 CheckLintNameResult::NoLint
1136 /* lint group exists */
1137 CheckLintNameResult::Ok
1143 CheckLintNameResult::Ok
1148 // Checks the validity of lint names derived from attributes
1149 fn check_lint_name_attribute(cx: &LateContext, attr: &ast::Attribute) {
1150 for result in gather_attr(attr) {
1153 // Malformed lint attr. Reported by with_lint_attrs
1156 Ok((lint_name, _, span)) => {
1157 match check_lint_name(&cx.lints, &lint_name.as_str()) {
1158 CheckLintNameResult::Ok => (),
1159 CheckLintNameResult::Warning(ref msg) => {
1160 cx.span_lint(builtin::RENAMED_AND_REMOVED_LINTS,
1163 CheckLintNameResult::NoLint => {
1164 cx.span_lint(builtin::UNKNOWN_LINTS, span,
1165 &format!("unknown lint: `{}`",
1174 // Checks the validity of lint names derived from the command line
1175 fn check_lint_name_cmdline(sess: &Session, lint_cx: &LintStore,
1176 lint_name: &str, level: Level) {
1177 let db = match check_lint_name(lint_cx, lint_name) {
1178 CheckLintNameResult::Ok => None,
1179 CheckLintNameResult::Warning(ref msg) => {
1180 Some(sess.struct_warn(msg))
1182 CheckLintNameResult::NoLint => {
1183 Some(sess.struct_err(&format!("unknown lint: `{}`", lint_name)))
1187 if let Some(mut db) = db {
1188 let msg = format!("requested on the command line with `{} {}`",
1190 Level::Allow => "-A",
1191 Level::Warn => "-W",
1192 Level::Deny => "-D",
1193 Level::Forbid => "-F",
1202 /// Perform lint checking on a crate.
1204 /// Consumes the `lint_store` field of the `Session`.
1205 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1206 access_levels: &AccessLevels) {
1207 let _task = tcx.dep_graph.in_task(DepNode::LateLintCheck);
1209 let krate = tcx.hir.krate();
1211 // We want to own the lint store, so move it out of the session.
1212 let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), LintStore::new());
1213 let mut cx = LateContext {
1215 tables: &ty::TypeckTables::empty(),
1217 access_levels: access_levels,
1219 level_stack: vec![],
1222 // Visit the whole crate.
1223 cx.with_lint_attrs(&krate.attrs, |cx| {
1224 // since the root module isn't visited as an item (because it isn't an
1225 // item), warn for it here.
1226 run_lints!(cx, check_crate, late_passes, krate);
1228 hir_visit::walk_crate(cx, krate);
1230 run_lints!(cx, check_crate_post, late_passes, krate);
1233 // If we missed any lints added to the session, then there's a bug somewhere
1234 // in the iteration code.
1235 if let Some((id, v)) = tcx.sess.lints.borrow().get_any() {
1236 for early_lint in v {
1237 span_bug!(early_lint.diagnostic.span.clone(),
1238 "unprocessed lint {:?} at {}",
1239 early_lint, tcx.hir.node_to_string(*id));
1243 // Put the lint store back in the session.
1244 mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), cx.lints);
1247 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1248 let mut cx = EarlyContext::new(sess, krate);
1250 // Visit the whole crate.
1251 cx.with_lint_attrs(&krate.attrs, |cx| {
1252 // Lints may be assigned to the whole crate.
1253 let lints = cx.sess.lints.borrow_mut().take(ast::CRATE_NODE_ID);
1254 for early_lint in lints {
1255 cx.early_lint(&early_lint);
1258 // since the root module isn't visited as an item (because it isn't an
1259 // item), warn for it here.
1260 run_lints!(cx, check_crate, early_passes, krate);
1262 ast_visit::walk_crate(cx, krate);
1264 run_lints!(cx, check_crate_post, early_passes, krate);
1267 // Put the lint store back in the session.
1268 mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1270 // If we missed any lints added to the session, then there's a bug somewhere
1271 // in the iteration code.
1272 for (_, v) in sess.lints.borrow().get_any() {
1273 for early_lint in v {
1274 span_bug!(early_lint.diagnostic.span.clone(), "unprocessed lint {:?}", early_lint);
1279 impl Encodable for LintId {
1280 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1281 s.emit_str(&self.lint.name.to_lowercase())
1285 impl Decodable for LintId {
1287 fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1288 let s = d.read_str()?;
1289 ty::tls::with(|tcx| {
1290 match tcx.sess.lint_store.borrow().find_lint(&s, tcx.sess, None) {
1292 Err(_) => panic!("invalid lint-id `{}`", s),