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;
46 use syntax_pos::{MultiSpan, Span};
47 use errors::{self, Diagnostic, DiagnosticBuilder};
49 use hir::intravisit as hir_visit;
50 use syntax::visit as ast_visit;
52 /// Information about the registered lints.
54 /// This is basically the subset of `Context` that we can
55 /// build early in the compile pipeline.
56 pub struct LintStore {
57 /// Registered lints. The bool is true if the lint was
58 /// added by a plugin.
59 lints: Vec<(&'static Lint, bool)>,
61 /// Trait objects for each lint pass.
62 /// This is only `None` while iterating over the objects. See the definition
64 early_passes: Option<Vec<EarlyLintPassObject>>,
65 late_passes: Option<Vec<LateLintPassObject>>,
67 /// Lints indexed by name.
68 by_name: FxHashMap<String, TargetLint>,
70 /// Current levels of each lint, and where they were set.
71 levels: FxHashMap<LintId, LevelSource>,
73 /// Map of registered lint groups to what lints they expand to. The bool
74 /// is true if the lint group was added by a plugin.
75 lint_groups: FxHashMap<&'static str, (Vec<LintId>, bool)>,
77 /// Extra info for future incompatibility lints, descibing the
78 /// issue or RFC that caused the incompatibility.
79 future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
81 /// Maximum level a lint can be
82 lint_cap: Option<Level>,
85 /// When you call `add_lint` on the session, you wind up storing one
86 /// of these, which records a "potential lint" at a particular point.
87 #[derive(PartialEq, RustcEncodable, RustcDecodable)]
88 pub struct EarlyLint {
89 /// what lint is this? (e.g., `dead_code`)
93 pub diagnostic: Diagnostic,
96 impl fmt::Debug for EarlyLint {
97 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98 f.debug_struct("EarlyLint")
99 .field("id", &self.id)
100 .field("span", &self.diagnostic.span)
101 .field("diagnostic", &self.diagnostic)
106 pub trait IntoEarlyLint {
107 fn into_early_lint(self, id: LintId) -> EarlyLint;
110 impl<'a, S: Into<MultiSpan>> IntoEarlyLint for (S, &'a str) {
111 fn into_early_lint(self, id: LintId) -> EarlyLint {
112 let (span, msg) = self;
113 let mut diagnostic = Diagnostic::new(errors::Level::Warning, msg);
114 diagnostic.set_span(span);
115 EarlyLint { id: id, diagnostic: diagnostic }
119 impl IntoEarlyLint for Diagnostic {
120 fn into_early_lint(self, id: LintId) -> EarlyLint {
121 EarlyLint { id: id, diagnostic: self }
125 /// Extra information for a future incompatibility lint. See the call
126 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
128 pub struct FutureIncompatibleInfo {
130 pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
133 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
135 /// A direct lint target
138 /// Temporary renaming, used for easing migration pain; see #16545
139 Renamed(String, LintId),
141 /// Lint with this name existed previously, but has been removed/deprecated.
142 /// The string argument is the reason for removal.
152 fn get_level_source(&self, lint: LintId) -> LevelSource {
153 match self.levels.get(&lint) {
155 None => (Allow, Default),
159 fn set_level(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
160 if let Some(cap) = self.lint_cap {
161 lvlsrc.0 = cmp::min(lvlsrc.0, cap);
163 if lvlsrc.0 == Allow {
164 self.levels.remove(&lint);
166 self.levels.insert(lint, lvlsrc);
170 pub fn new() -> LintStore {
173 early_passes: Some(vec![]),
174 late_passes: Some(vec![]),
175 by_name: FxHashMap(),
177 future_incompatible: FxHashMap(),
178 lint_groups: FxHashMap(),
183 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
187 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
188 self.lint_groups.iter().map(|(k, v)| (*k,
193 pub fn register_early_pass(&mut self,
194 sess: Option<&Session>,
196 pass: EarlyLintPassObject) {
197 self.push_pass(sess, from_plugin, &pass);
198 self.early_passes.as_mut().unwrap().push(pass);
201 pub fn register_late_pass(&mut self,
202 sess: Option<&Session>,
204 pass: LateLintPassObject) {
205 self.push_pass(sess, from_plugin, &pass);
206 self.late_passes.as_mut().unwrap().push(pass);
209 // Helper method for register_early/late_pass
210 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
211 sess: Option<&Session>,
214 for &lint in pass.get_lints() {
215 self.lints.push((*lint, from_plugin));
217 let id = LintId::of(*lint);
218 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
219 let msg = format!("duplicate specification of lint {}", lint.name_lower());
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(_), false) => bug!("{}", msg),
226 // A duplicate name from a plugin is a user error.
227 (Some(sess), true) => sess.err(&msg[..]),
231 if lint.default_level != Allow {
232 self.levels.insert(id, (lint.default_level, Default));
237 pub fn register_future_incompatible(&mut self,
238 sess: Option<&Session>,
239 lints: Vec<FutureIncompatibleInfo>) {
240 let ids = lints.iter().map(|f| f.id).collect();
241 self.register_group(sess, false, "future_incompatible", ids);
243 self.future_incompatible.insert(info.id, info);
247 pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
248 self.future_incompatible.get(&id)
251 pub fn register_group(&mut self, sess: Option<&Session>,
252 from_plugin: bool, name: &'static str,
254 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
257 let msg = format!("duplicate specification of lint group {}", name);
258 match (sess, from_plugin) {
259 // We load builtin lints first, so a duplicate is a compiler bug.
260 // Use early_error when handling -W help with no crate.
261 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
262 (Some(_), false) => bug!("{}", msg),
264 // A duplicate name from a plugin is a user error.
265 (Some(sess), true) => sess.err(&msg[..]),
270 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
271 let target = match self.by_name.get(new_name) {
272 Some(&Id(lint_id)) => lint_id.clone(),
273 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
275 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
278 pub fn register_removed(&mut self, name: &str, reason: &str) {
279 self.by_name.insert(name.into(), Removed(reason.into()));
282 #[allow(unused_variables)]
283 fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
284 -> Result<LintId, FindLintError>
286 match self.by_name.get(lint_name) {
287 Some(&Id(lint_id)) => Ok(lint_id),
288 Some(&Renamed(_, lint_id)) => {
291 Some(&Removed(ref reason)) => {
292 Err(FindLintError::Removed)
294 None => Err(FindLintError::NotFound)
298 pub fn process_command_line(&mut self, sess: &Session) {
299 for &(ref lint_name, level) in &sess.opts.lint_opts {
300 check_lint_name_cmdline(sess, self,
301 &lint_name[..], level);
303 match self.find_lint(&lint_name[..], sess, None) {
304 Ok(lint_id) => self.set_level(lint_id, (level, CommandLine)),
305 Err(FindLintError::Removed) => { }
307 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
308 .collect::<FxHashMap<&'static str,
310 .get(&lint_name[..]) {
313 .map(|lint_id: &LintId|
314 self.set_level(*lint_id, (level, CommandLine)))
315 .collect::<Vec<()>>();
318 // The lint or lint group doesn't exist.
319 // This is an error, but it was handled
320 // by check_lint_name_cmdline.
327 self.lint_cap = sess.opts.lint_cap;
328 if let Some(cap) = self.lint_cap {
329 for level in self.levels.iter_mut().map(|p| &mut (p.1).0) {
330 *level = cmp::min(*level, cap);
336 /// Context for lint checking after type checking.
337 pub struct LateContext<'a, 'tcx: 'a> {
338 /// Type context we're checking in.
339 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
341 /// Side-tables for the body we are in.
342 pub tables: &'a ty::TypeckTables<'tcx>,
344 /// The crate being checked.
345 pub krate: &'a hir::Crate,
347 /// Items accessible from the crate being checked.
348 pub access_levels: &'a AccessLevels,
350 /// The store of registered lints.
353 /// When recursing into an attributed node of the ast which modifies lint
354 /// levels, this stack keeps track of the previous lint levels of whatever
356 level_stack: Vec<(LintId, LevelSource)>,
359 /// Context for lint checking of the AST, after expansion, before lowering to
361 pub struct EarlyContext<'a> {
362 /// Type context we're checking in.
363 pub sess: &'a Session,
365 /// The crate being checked.
366 pub krate: &'a ast::Crate,
368 /// The store of registered lints.
371 /// When recursing into an attributed node of the ast which modifies lint
372 /// levels, this stack keeps track of the previous lint levels of whatever
374 level_stack: Vec<(LintId, LevelSource)>,
377 /// Convenience macro for calling a `LintPass` method on every pass in the context.
378 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
379 // Move the vector of passes out of `$cx` so that we can
380 // iterate over it mutably while passing `$cx` to the methods.
381 let mut passes = $cx.mut_lints().$ps.take().unwrap();
382 for obj in &mut passes {
383 obj.$f($cx, $($args),*);
385 $cx.mut_lints().$ps = Some(passes);
388 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
389 /// attributes. Writing this as an iterator is an enormous mess.
390 // See also the hir version just below.
391 pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec<Result<(ast::Name, Level, Span), Span>> {
392 let mut out = vec![];
394 let r = gather_attr(attr);
395 out.extend(r.into_iter());
400 pub fn gather_attr(attr: &ast::Attribute) -> Vec<Result<(ast::Name, Level, Span), Span>> {
401 let mut out = vec![];
403 let level = match Level::from_str(&attr.name().as_str()) {
408 attr::mark_used(attr);
410 let meta = &attr.value;
411 let metas = if let Some(metas) = meta.meta_item_list() {
414 out.push(Err(meta.span));
419 out.push(li.word().map_or(Err(li.span), |word| Ok((word.name(), level, word.span))));
425 /// Emit a lint as a warning or an error (or not at all)
426 /// according to `level`.
428 /// This lives outside of `Context` so it can be used by checks
429 /// in trans that run after the main lint pass is finished. Most
430 /// lints elsewhere in the compiler should call
431 /// `Session::add_lint()` instead.
432 pub fn raw_emit_lint<S: Into<MultiSpan>>(sess: &Session,
438 raw_struct_lint(sess, lints, lint, lvlsrc, span, msg).emit();
441 pub fn raw_struct_lint<'a, S>(sess: &'a Session,
447 -> DiagnosticBuilder<'a>
448 where S: Into<MultiSpan>
450 let (level, source) = lvlsrc;
452 return sess.diagnostic().struct_dummy();
455 let name = lint.name_lower();
458 // Except for possible note details, forbid behaves like deny.
459 let effective_level = if level == Forbid { Deny } else { level };
461 let mut err = match (effective_level, span) {
462 (Warn, Some(sp)) => sess.struct_span_warn(sp, &msg[..]),
463 (Warn, None) => sess.struct_warn(&msg[..]),
464 (Deny, Some(sp)) => sess.struct_span_err(sp, &msg[..]),
465 (Deny, None) => sess.struct_err(&msg[..]),
466 _ => bug!("impossible level in raw_emit_lint"),
471 err.note(&format!("#[{}({})] on by default", level.as_str(), name));
474 err.note(&format!("[-{} {}]",
476 Warn => 'W', Deny => 'D', Forbid => 'F',
478 }, name.replace("_", "-")));
480 Node(lint_attr_name, src) => {
482 if lint_attr_name.as_str().deref() != name {
483 let level_str = level.as_str();
484 err.note(&format!("#[{}({})] implies #[{}({})]",
485 level_str, lint_attr_name, level_str, name));
490 // Check for future incompatibility lints and issue a stronger warning.
491 if let Some(future_incompatible) = lints.future_incompatible(LintId::of(lint)) {
492 let explanation = format!("this was previously accepted by the compiler \
493 but is being phased out; \
494 it will become a hard error in a future release!");
495 let citation = format!("for more information, see {}",
496 future_incompatible.reference);
497 err.warn(&explanation);
501 if let Some(span) = def {
502 sess.diag_span_note_once(&mut err, lint, span, "lint level defined here");
508 pub trait LintContext<'tcx>: Sized {
509 fn sess(&self) -> &Session;
510 fn lints(&self) -> &LintStore;
511 fn mut_lints(&mut self) -> &mut LintStore;
512 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>;
513 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
514 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
516 /// Get the level of `lint` at the current position of the lint
518 fn current_level(&self, lint: &'static Lint) -> Level {
519 self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
522 fn level_src(&self, lint: &'static Lint) -> Option<LevelSource> {
523 self.lints().levels.get(&LintId::of(lint)).map(|ls| match ls {
525 let lint_id = LintId::of(builtin::WARNINGS);
526 let warn_src = self.lints().get_level_source(lint_id);
527 if warn_src.0 != Warn {
537 fn lookup_and_emit<S: Into<MultiSpan>>(&self,
541 let (level, src) = match self.level_src(lint) {
546 raw_emit_lint(&self.sess(), self.lints(), lint, (level, src), span, msg);
549 fn lookup<S: Into<MultiSpan>>(&self,
553 -> DiagnosticBuilder {
554 let (level, src) = match self.level_src(lint) {
555 None => return self.sess().diagnostic().struct_dummy(),
559 raw_struct_lint(&self.sess(), self.lints(), lint, (level, src), span, msg)
562 /// Emit a lint at the appropriate level, for a particular span.
563 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
564 self.lookup_and_emit(lint, Some(span), msg);
567 fn early_lint(&self, early_lint: &EarlyLint) {
568 let span = early_lint.diagnostic.span.primary_span().expect("early lint w/o primary span");
569 let mut err = self.struct_span_lint(early_lint.id.lint,
571 &early_lint.diagnostic.message());
572 err.copy_details_not_message(&early_lint.diagnostic);
576 fn struct_span_lint<S: Into<MultiSpan>>(&self,
580 -> DiagnosticBuilder {
581 self.lookup(lint, Some(span), msg)
584 /// Emit a lint and note at the appropriate level, for a particular span.
585 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
586 note_span: Span, note: &str) {
587 let mut err = self.lookup(lint, Some(span), msg);
588 if self.current_level(lint) != Level::Allow {
589 if note_span == span {
592 err.span_note(note_span, note);
598 /// Emit a lint and help at the appropriate level, for a particular span.
599 fn span_lint_help(&self, lint: &'static Lint, span: Span,
600 msg: &str, help: &str) {
601 let mut err = self.lookup(lint, Some(span), msg);
602 self.span_lint(lint, span, msg);
603 if self.current_level(lint) != Level::Allow {
604 err.span_help(span, help);
609 /// Emit a lint at the appropriate level, with no associated span.
610 fn lint(&self, lint: &'static Lint, msg: &str) {
611 self.lookup_and_emit(lint, None as Option<Span>, msg);
614 /// Merge the lints specified by any lint attributes into the
615 /// current lint context, call the provided function, then reset the
616 /// lints in effect to their previous state.
617 fn with_lint_attrs<F>(&mut self,
618 attrs: &'tcx [ast::Attribute],
620 where F: FnOnce(&mut Self),
622 // Parse all of the lint attributes, and then add them all to the
623 // current dictionary of lint information. Along the way, keep a history
624 // of what we changed so we can roll everything back after invoking the
628 for result in gather_attrs(attrs) {
629 let v = match result {
631 span_err!(self.sess(), span, E0452,
632 "malformed lint attribute");
635 Ok((lint_name, level, span)) => {
636 match self.lints().find_lint(&lint_name.as_str(), &self.sess(), Some(span)) {
637 Ok(lint_id) => vec![(lint_id, level, span)],
638 Err(FindLintError::NotFound) => {
639 match self.lints().lint_groups.get(&*lint_name.as_str()) {
640 Some(&(ref v, _)) => v.iter()
641 .map(|lint_id: &LintId|
642 (*lint_id, level, span))
645 // The lint or lint group doesn't exist.
646 // This is an error, but it was handled
647 // by check_lint_name_attribute.
652 Err(FindLintError::Removed) => { continue; }
657 let lint_attr_name = result.expect("lint attribute should be well-formed").0;
659 for (lint_id, level, span) in v {
660 let (now, now_source) = self.lints().get_level_source(lint_id);
661 if now == Forbid && level != Forbid {
662 let lint_name = lint_id.to_string();
663 let mut diag_builder = struct_span_err!(self.sess(), span, E0453,
664 "{}({}) overruled by outer forbid({})",
665 level.as_str(), lint_name,
667 diag_builder.span_label(span, &format!("overruled by previous forbid"));
669 LintSource::Default => &mut diag_builder,
670 LintSource::Node(_, forbid_source_span) => {
671 diag_builder.span_label(forbid_source_span,
672 &format!("`forbid` level set here"))
674 LintSource::CommandLine => {
675 diag_builder.note("`forbid` lint level was set on command line")
678 } else if now != level {
679 let src = self.lints().get_level_source(lint_id).1;
680 self.level_stack().push((lint_id, (now, src)));
682 self.mut_lints().set_level(lint_id, (level, Node(lint_attr_name, span)));
687 self.enter_attrs(attrs);
689 self.exit_attrs(attrs);
693 let (lint, lvlsrc) = self.level_stack().pop().unwrap();
694 self.mut_lints().set_level(lint, lvlsrc);
700 impl<'a> EarlyContext<'a> {
701 fn new(sess: &'a Session,
702 krate: &'a ast::Crate) -> EarlyContext<'a> {
703 // We want to own the lint store, so move it out of the session. Remember
704 // to put it back later...
705 let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
716 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
717 /// Get the overall compiler `Session` object.
718 fn sess(&self) -> &Session {
722 fn lints(&self) -> &LintStore {
726 fn mut_lints(&mut self) -> &mut LintStore {
730 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
731 &mut self.level_stack
734 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
735 debug!("late context: enter_attrs({:?})", attrs);
736 run_lints!(self, enter_lint_attrs, late_passes, attrs);
739 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
740 debug!("late context: exit_attrs({:?})", attrs);
741 run_lints!(self, exit_lint_attrs, late_passes, attrs);
745 impl<'a> LintContext<'a> for EarlyContext<'a> {
746 /// Get the overall compiler `Session` object.
747 fn sess(&self) -> &Session {
751 fn lints(&self) -> &LintStore {
755 fn mut_lints(&mut self) -> &mut LintStore {
759 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
760 &mut self.level_stack
763 fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
764 debug!("early context: enter_attrs({:?})", attrs);
765 run_lints!(self, enter_lint_attrs, early_passes, attrs);
768 fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
769 debug!("early context: exit_attrs({:?})", attrs);
770 run_lints!(self, exit_lint_attrs, early_passes, attrs);
774 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
775 /// Because lints are scoped lexically, we want to walk nested
776 /// items in the context of the outer item, so enable
778 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
779 hir_visit::NestedVisitorMap::All(&self.tcx.hir)
782 // Output any lints that were previously added to the session.
783 fn visit_id(&mut self, id: ast::NodeId) {
784 let lints = self.sess().lints.borrow_mut().take(id);
785 for early_lint in lints.iter().chain(self.tables.lints.get(id)) {
786 debug!("LateContext::visit_id: id={:?} early_lint={:?}", id, early_lint);
787 self.early_lint(early_lint);
791 fn visit_nested_body(&mut self, body: hir::BodyId) {
792 let old_tables = self.tables;
793 self.tables = self.tcx.body_tables(body);
794 let body = self.tcx.hir.body(body);
795 self.visit_body(body);
796 self.tables = old_tables;
799 fn visit_item(&mut self, it: &'tcx hir::Item) {
800 self.with_lint_attrs(&it.attrs, |cx| {
801 run_lints!(cx, check_item, late_passes, it);
802 hir_visit::walk_item(cx, it);
803 run_lints!(cx, check_item_post, late_passes, it);
807 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
808 self.with_lint_attrs(&it.attrs, |cx| {
809 run_lints!(cx, check_foreign_item, late_passes, it);
810 hir_visit::walk_foreign_item(cx, it);
811 run_lints!(cx, check_foreign_item_post, late_passes, it);
815 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
816 run_lints!(self, check_pat, late_passes, p);
817 hir_visit::walk_pat(self, p);
820 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
821 self.with_lint_attrs(&e.attrs, |cx| {
822 run_lints!(cx, check_expr, late_passes, e);
823 hir_visit::walk_expr(cx, e);
824 run_lints!(cx, check_expr_post, late_passes, e);
828 fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
829 // statement attributes are actually just attributes on one of
833 // so we keep track of lint levels there
834 run_lints!(self, check_stmt, late_passes, s);
835 hir_visit::walk_stmt(self, s);
838 fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
839 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
840 // Wrap in tables here, not just in visit_nested_body,
841 // in order for `check_fn` to be able to use them.
842 let old_tables = self.tables;
843 self.tables = self.tcx.body_tables(body_id);
844 let body = self.tcx.hir.body(body_id);
845 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
846 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
847 run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
848 self.tables = old_tables;
851 fn visit_variant_data(&mut self,
852 s: &'tcx hir::VariantData,
854 g: &'tcx hir::Generics,
855 item_id: ast::NodeId,
857 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
858 hir_visit::walk_struct_def(self, s);
859 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
862 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
863 self.with_lint_attrs(&s.attrs, |cx| {
864 run_lints!(cx, check_struct_field, late_passes, s);
865 hir_visit::walk_struct_field(cx, s);
869 fn visit_variant(&mut self,
870 v: &'tcx hir::Variant,
871 g: &'tcx hir::Generics,
872 item_id: ast::NodeId) {
873 self.with_lint_attrs(&v.node.attrs, |cx| {
874 run_lints!(cx, check_variant, late_passes, v, g);
875 hir_visit::walk_variant(cx, v, g, item_id);
876 run_lints!(cx, check_variant_post, late_passes, v, g);
880 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
881 run_lints!(self, check_ty, late_passes, t);
882 hir_visit::walk_ty(self, t);
885 fn visit_name(&mut self, sp: Span, name: ast::Name) {
886 run_lints!(self, check_name, late_passes, sp, name);
889 fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
890 run_lints!(self, check_mod, late_passes, m, s, n);
891 hir_visit::walk_mod(self, m, n);
892 run_lints!(self, check_mod_post, late_passes, m, s, n);
895 fn visit_local(&mut self, l: &'tcx hir::Local) {
896 self.with_lint_attrs(&l.attrs, |cx| {
897 run_lints!(cx, check_local, late_passes, l);
898 hir_visit::walk_local(cx, l);
902 fn visit_block(&mut self, b: &'tcx hir::Block) {
903 run_lints!(self, check_block, late_passes, b);
904 hir_visit::walk_block(self, b);
905 run_lints!(self, check_block_post, late_passes, b);
908 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
909 run_lints!(self, check_arm, late_passes, a);
910 hir_visit::walk_arm(self, a);
913 fn visit_decl(&mut self, d: &'tcx hir::Decl) {
914 run_lints!(self, check_decl, late_passes, d);
915 hir_visit::walk_decl(self, d);
918 fn visit_generics(&mut self, g: &'tcx hir::Generics) {
919 run_lints!(self, check_generics, late_passes, g);
920 hir_visit::walk_generics(self, g);
923 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
924 self.with_lint_attrs(&trait_item.attrs, |cx| {
925 run_lints!(cx, check_trait_item, late_passes, trait_item);
926 hir_visit::walk_trait_item(cx, trait_item);
927 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
931 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
932 self.with_lint_attrs(&impl_item.attrs, |cx| {
933 run_lints!(cx, check_impl_item, late_passes, impl_item);
934 hir_visit::walk_impl_item(cx, impl_item);
935 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
939 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
940 run_lints!(self, check_lifetime, late_passes, lt);
941 hir_visit::walk_lifetime(self, lt);
944 fn visit_lifetime_def(&mut self, lt: &'tcx hir::LifetimeDef) {
945 run_lints!(self, check_lifetime_def, late_passes, lt);
946 hir_visit::walk_lifetime_def(self, lt);
949 fn visit_path(&mut self, p: &'tcx hir::Path, id: ast::NodeId) {
950 run_lints!(self, check_path, late_passes, p, id);
951 hir_visit::walk_path(self, p);
954 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
955 check_lint_name_attribute(self, attr);
956 run_lints!(self, check_attribute, late_passes, attr);
960 impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> {
961 fn visit_item(&mut self, it: &'a ast::Item) {
962 self.with_lint_attrs(&it.attrs, |cx| {
963 run_lints!(cx, check_item, early_passes, it);
964 ast_visit::walk_item(cx, it);
965 run_lints!(cx, check_item_post, early_passes, it);
969 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
970 self.with_lint_attrs(&it.attrs, |cx| {
971 run_lints!(cx, check_foreign_item, early_passes, it);
972 ast_visit::walk_foreign_item(cx, it);
973 run_lints!(cx, check_foreign_item_post, early_passes, it);
977 fn visit_pat(&mut self, p: &'a ast::Pat) {
978 run_lints!(self, check_pat, early_passes, p);
979 ast_visit::walk_pat(self, p);
982 fn visit_expr(&mut self, e: &'a ast::Expr) {
983 self.with_lint_attrs(&e.attrs, |cx| {
984 run_lints!(cx, check_expr, early_passes, e);
985 ast_visit::walk_expr(cx, e);
989 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
990 run_lints!(self, check_stmt, early_passes, s);
991 ast_visit::walk_stmt(self, s);
994 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
995 span: Span, id: ast::NodeId) {
996 run_lints!(self, check_fn, early_passes, fk, decl, span, id);
997 ast_visit::walk_fn(self, fk, decl, span);
998 run_lints!(self, check_fn_post, early_passes, fk, decl, span, id);
1001 fn visit_variant_data(&mut self,
1002 s: &'a ast::VariantData,
1004 g: &'a ast::Generics,
1005 item_id: ast::NodeId,
1007 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
1008 ast_visit::walk_struct_def(self, s);
1009 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
1012 fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1013 self.with_lint_attrs(&s.attrs, |cx| {
1014 run_lints!(cx, check_struct_field, early_passes, s);
1015 ast_visit::walk_struct_field(cx, s);
1019 fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1020 self.with_lint_attrs(&v.node.attrs, |cx| {
1021 run_lints!(cx, check_variant, early_passes, v, g);
1022 ast_visit::walk_variant(cx, v, g, item_id);
1023 run_lints!(cx, check_variant_post, early_passes, v, g);
1027 fn visit_ty(&mut self, t: &'a ast::Ty) {
1028 run_lints!(self, check_ty, early_passes, t);
1029 ast_visit::walk_ty(self, t);
1032 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
1033 run_lints!(self, check_ident, early_passes, sp, id);
1036 fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, n: ast::NodeId) {
1037 run_lints!(self, check_mod, early_passes, m, s, n);
1038 ast_visit::walk_mod(self, m);
1039 run_lints!(self, check_mod_post, early_passes, m, s, n);
1042 fn visit_local(&mut self, l: &'a ast::Local) {
1043 self.with_lint_attrs(&l.attrs, |cx| {
1044 run_lints!(cx, check_local, early_passes, l);
1045 ast_visit::walk_local(cx, l);
1049 fn visit_block(&mut self, b: &'a ast::Block) {
1050 run_lints!(self, check_block, early_passes, b);
1051 ast_visit::walk_block(self, b);
1052 run_lints!(self, check_block_post, early_passes, b);
1055 fn visit_arm(&mut self, a: &'a ast::Arm) {
1056 run_lints!(self, check_arm, early_passes, a);
1057 ast_visit::walk_arm(self, a);
1060 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1061 run_lints!(self, check_expr_post, early_passes, e);
1064 fn visit_generics(&mut self, g: &'a ast::Generics) {
1065 run_lints!(self, check_generics, early_passes, g);
1066 ast_visit::walk_generics(self, g);
1069 fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1070 self.with_lint_attrs(&trait_item.attrs, |cx| {
1071 run_lints!(cx, check_trait_item, early_passes, trait_item);
1072 ast_visit::walk_trait_item(cx, trait_item);
1073 run_lints!(cx, check_trait_item_post, early_passes, trait_item);
1077 fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1078 self.with_lint_attrs(&impl_item.attrs, |cx| {
1079 run_lints!(cx, check_impl_item, early_passes, impl_item);
1080 ast_visit::walk_impl_item(cx, impl_item);
1081 run_lints!(cx, check_impl_item_post, early_passes, impl_item);
1085 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1086 run_lints!(self, check_lifetime, early_passes, lt);
1089 fn visit_lifetime_def(&mut self, lt: &'a ast::LifetimeDef) {
1090 run_lints!(self, check_lifetime_def, early_passes, lt);
1093 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1094 run_lints!(self, check_path, early_passes, p, id);
1095 ast_visit::walk_path(self, p);
1098 fn visit_path_list_item(&mut self, prefix: &'a ast::Path, item: &'a ast::PathListItem) {
1099 run_lints!(self, check_path_list_item, early_passes, item);
1100 ast_visit::walk_path_list_item(self, prefix, item);
1103 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1104 run_lints!(self, check_attribute, early_passes, attr);
1108 enum CheckLintNameResult {
1110 // Lint doesn't exist
1112 // The lint is either renamed or removed. This is the warning
1117 /// Checks the name of a lint for its existence, and whether it was
1118 /// renamed or removed. Generates a DiagnosticBuilder containing a
1119 /// warning for renamed and removed lints. This is over both lint
1120 /// names from attributes and those passed on the command line. Since
1121 /// it emits non-fatal warnings and there are *two* lint passes that
1122 /// inspect attributes, this is only run from the late pass to avoid
1123 /// printing duplicate warnings.
1124 fn check_lint_name(lint_cx: &LintStore,
1125 lint_name: &str) -> CheckLintNameResult {
1126 match lint_cx.by_name.get(lint_name) {
1127 Some(&Renamed(ref new_name, _)) => {
1128 CheckLintNameResult::Warning(
1129 format!("lint {} has been renamed to {}", lint_name, new_name)
1132 Some(&Removed(ref reason)) => {
1133 CheckLintNameResult::Warning(
1134 format!("lint {} has been removed: {}", lint_name, reason)
1138 match lint_cx.lint_groups.get(lint_name) {
1140 CheckLintNameResult::NoLint
1143 /* lint group exists */
1144 CheckLintNameResult::Ok
1150 CheckLintNameResult::Ok
1155 // Checks the validity of lint names derived from attributes
1156 fn check_lint_name_attribute(cx: &LateContext, attr: &ast::Attribute) {
1157 for result in gather_attr(attr) {
1160 // Malformed lint attr. Reported by with_lint_attrs
1163 Ok((lint_name, _, span)) => {
1164 match check_lint_name(&cx.lints, &lint_name.as_str()) {
1165 CheckLintNameResult::Ok => (),
1166 CheckLintNameResult::Warning(ref msg) => {
1167 cx.span_lint(builtin::RENAMED_AND_REMOVED_LINTS,
1170 CheckLintNameResult::NoLint => {
1171 cx.span_lint(builtin::UNKNOWN_LINTS, span,
1172 &format!("unknown lint: `{}`",
1181 // Checks the validity of lint names derived from the command line
1182 fn check_lint_name_cmdline(sess: &Session, lint_cx: &LintStore,
1183 lint_name: &str, level: Level) {
1184 let db = match check_lint_name(lint_cx, lint_name) {
1185 CheckLintNameResult::Ok => None,
1186 CheckLintNameResult::Warning(ref msg) => {
1187 Some(sess.struct_warn(msg))
1189 CheckLintNameResult::NoLint => {
1190 Some(sess.struct_err(&format!("unknown lint: `{}`", lint_name)))
1194 if let Some(mut db) = db {
1195 let msg = format!("requested on the command line with `{} {}`",
1197 Level::Allow => "-A",
1198 Level::Warn => "-W",
1199 Level::Deny => "-D",
1200 Level::Forbid => "-F",
1209 /// Perform lint checking on a crate.
1211 /// Consumes the `lint_store` field of the `Session`.
1212 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1213 access_levels: &AccessLevels) {
1214 let _task = tcx.dep_graph.in_task(DepNode::LateLintCheck);
1216 let krate = tcx.hir.krate();
1218 // We want to own the lint store, so move it out of the session.
1219 let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), LintStore::new());
1220 let mut cx = LateContext {
1222 tables: &ty::TypeckTables::empty(),
1224 access_levels: access_levels,
1226 level_stack: vec![],
1229 // Visit the whole crate.
1230 cx.with_lint_attrs(&krate.attrs, |cx| {
1231 // since the root module isn't visited as an item (because it isn't an
1232 // item), warn for it here.
1233 run_lints!(cx, check_crate, late_passes, krate);
1235 hir_visit::walk_crate(cx, krate);
1237 run_lints!(cx, check_crate_post, late_passes, krate);
1240 // If we missed any lints added to the session, then there's a bug somewhere
1241 // in the iteration code.
1242 if let Some((id, v)) = tcx.sess.lints.borrow().get_any() {
1243 for early_lint in v {
1244 span_bug!(early_lint.diagnostic.span.clone(),
1245 "unprocessed lint {:?} at {}",
1246 early_lint, tcx.hir.node_to_string(*id));
1250 // Put the lint store back in the session.
1251 mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), cx.lints);
1254 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1255 let mut cx = EarlyContext::new(sess, krate);
1257 // Visit the whole crate.
1258 cx.with_lint_attrs(&krate.attrs, |cx| {
1259 // Lints may be assigned to the whole crate.
1260 let lints = cx.sess.lints.borrow_mut().take(ast::CRATE_NODE_ID);
1261 for early_lint in lints {
1262 cx.early_lint(&early_lint);
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, early_passes, krate);
1269 ast_visit::walk_crate(cx, krate);
1271 run_lints!(cx, check_crate_post, early_passes, krate);
1274 // Put the lint store back in the session.
1275 mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1277 // If we missed any lints added to the session, then there's a bug somewhere
1278 // in the iteration code.
1279 for (_, v) in sess.lints.borrow().get_any() {
1280 for early_lint in v {
1281 span_bug!(early_lint.diagnostic.span.clone(), "unprocessed lint {:?}", early_lint);
1286 impl Encodable for LintId {
1287 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1288 s.emit_str(&self.lint.name.to_lowercase())
1292 impl Decodable for LintId {
1294 fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1295 let s = d.read_str()?;
1296 ty::tls::with(|tcx| {
1297 match tcx.sess.lint_store.borrow().find_lint(&s, tcx.sess, None) {
1299 Err(_) => panic!("invalid lint-id `{}`", s),