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::symbol::Symbol;
46 use syntax_pos::{MultiSpan, Span};
47 use errors::{self, Diagnostic, DiagnosticBuilder};
49 use hir::def_id::LOCAL_CRATE;
50 use hir::intravisit as hir_visit;
51 use syntax::visit as ast_visit;
53 /// Information about the registered lints.
55 /// This is basically the subset of `Context` that we can
56 /// build early in the compile pipeline.
57 pub struct LintStore {
58 /// Registered lints. The bool is true if the lint was
59 /// added by a plugin.
60 lints: Vec<(&'static Lint, bool)>,
62 /// Trait objects for each lint pass.
63 /// This is only `None` while iterating over the objects. See the definition
65 early_passes: Option<Vec<EarlyLintPassObject>>,
66 late_passes: Option<Vec<LateLintPassObject>>,
68 /// Lints indexed by name.
69 by_name: FxHashMap<String, TargetLint>,
71 /// Current levels of each lint, and where they were set.
72 levels: FxHashMap<LintId, LevelSource>,
74 /// Map of registered lint groups to what lints they expand to. The bool
75 /// is true if the lint group was added by a plugin.
76 lint_groups: FxHashMap<&'static str, (Vec<LintId>, bool)>,
78 /// Extra info for future incompatibility lints, descibing the
79 /// issue or RFC that caused the incompatibility.
80 future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
82 /// Maximum level a lint can be
83 lint_cap: Option<Level>,
86 /// When you call `add_lint` on the session, you wind up storing one
87 /// of these, which records a "potential lint" at a particular point.
88 #[derive(PartialEq, RustcEncodable, RustcDecodable)]
89 pub struct EarlyLint {
90 /// what lint is this? (e.g., `dead_code`)
94 pub diagnostic: Diagnostic,
97 impl fmt::Debug for EarlyLint {
98 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99 f.debug_struct("EarlyLint")
100 .field("id", &self.id)
101 .field("span", &self.diagnostic.span)
102 .field("diagnostic", &self.diagnostic)
107 pub trait IntoEarlyLint {
108 fn into_early_lint(self, id: LintId) -> EarlyLint;
111 impl<'a, S: Into<MultiSpan>> IntoEarlyLint for (S, &'a str) {
112 fn into_early_lint(self, id: LintId) -> EarlyLint {
113 let (span, msg) = self;
114 let mut diagnostic = Diagnostic::new(errors::Level::Warning, msg);
115 diagnostic.set_span(span);
118 diagnostic: diagnostic,
123 impl IntoEarlyLint for Diagnostic {
124 fn into_early_lint(self, id: LintId) -> EarlyLint {
132 /// Extra information for a future incompatibility lint. See the call
133 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
135 pub struct FutureIncompatibleInfo {
137 pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
140 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
142 /// A direct lint target
145 /// Temporary renaming, used for easing migration pain; see #16545
146 Renamed(String, LintId),
148 /// Lint with this name existed previously, but has been removed/deprecated.
149 /// The string argument is the reason for removal.
159 fn get_level_source(&self, lint: LintId) -> LevelSource {
160 match self.levels.get(&lint) {
162 None => (Allow, Default),
166 fn set_level(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
167 if let Some(cap) = self.lint_cap {
168 lvlsrc.0 = cmp::min(lvlsrc.0, cap);
170 if lvlsrc.0 == Allow {
171 self.levels.remove(&lint);
173 self.levels.insert(lint, lvlsrc);
177 pub fn new() -> LintStore {
180 early_passes: Some(vec![]),
181 late_passes: Some(vec![]),
182 by_name: FxHashMap(),
184 future_incompatible: FxHashMap(),
185 lint_groups: FxHashMap(),
190 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
194 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
195 self.lint_groups.iter().map(|(k, v)| (*k,
200 pub fn register_early_pass(&mut self,
201 sess: Option<&Session>,
203 pass: EarlyLintPassObject) {
204 self.push_pass(sess, from_plugin, &pass);
205 self.early_passes.as_mut().unwrap().push(pass);
208 pub fn register_late_pass(&mut self,
209 sess: Option<&Session>,
211 pass: LateLintPassObject) {
212 self.push_pass(sess, from_plugin, &pass);
213 self.late_passes.as_mut().unwrap().push(pass);
216 // Helper method for register_early/late_pass
217 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
218 sess: Option<&Session>,
221 for &lint in pass.get_lints() {
222 self.lints.push((*lint, from_plugin));
224 let id = LintId::of(*lint);
225 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
226 let msg = format!("duplicate specification of lint {}", lint.name_lower());
227 match (sess, from_plugin) {
228 // We load builtin lints first, so a duplicate is a compiler bug.
229 // Use early_error when handling -W help with no crate.
230 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
231 (Some(_), false) => bug!("{}", msg),
233 // A duplicate name from a plugin is a user error.
234 (Some(sess), true) => sess.err(&msg[..]),
238 if lint.default_level != Allow {
239 self.levels.insert(id, (lint.default_level, Default));
244 pub fn register_future_incompatible(&mut self,
245 sess: Option<&Session>,
246 lints: Vec<FutureIncompatibleInfo>) {
247 let ids = lints.iter().map(|f| f.id).collect();
248 self.register_group(sess, false, "future_incompatible", ids);
250 self.future_incompatible.insert(info.id, info);
254 pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
255 self.future_incompatible.get(&id)
258 pub fn register_group(&mut self, sess: Option<&Session>,
259 from_plugin: bool, name: &'static str,
261 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
264 let msg = format!("duplicate specification of lint group {}", name);
265 match (sess, from_plugin) {
266 // We load builtin lints first, so a duplicate is a compiler bug.
267 // Use early_error when handling -W help with no crate.
268 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
269 (Some(_), false) => bug!("{}", msg),
271 // A duplicate name from a plugin is a user error.
272 (Some(sess), true) => sess.err(&msg[..]),
277 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
278 let target = match self.by_name.get(new_name) {
279 Some(&Id(lint_id)) => lint_id.clone(),
280 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
282 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
285 pub fn register_removed(&mut self, name: &str, reason: &str) {
286 self.by_name.insert(name.into(), Removed(reason.into()));
289 #[allow(unused_variables)]
290 fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
291 -> Result<LintId, FindLintError>
293 match self.by_name.get(lint_name) {
294 Some(&Id(lint_id)) => Ok(lint_id),
295 Some(&Renamed(_, lint_id)) => {
298 Some(&Removed(ref reason)) => {
299 Err(FindLintError::Removed)
301 None => Err(FindLintError::NotFound)
305 pub fn process_command_line(&mut self, sess: &Session) {
306 for &(ref lint_name, level) in &sess.opts.lint_opts {
307 check_lint_name_cmdline(sess, self,
308 &lint_name[..], level);
310 let lint_flag_val = Symbol::intern(&lint_name);
311 match self.find_lint(&lint_name[..], sess, None) {
312 Ok(lint_id) => self.set_level(lint_id, (level, CommandLine(lint_flag_val))),
313 Err(FindLintError::Removed) => { }
315 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
316 .collect::<FxHashMap<&'static str,
318 .get(&lint_name[..]) {
321 .map(|lint_id: &LintId|
322 self.set_level(*lint_id, (level, CommandLine(lint_flag_val))))
323 .collect::<Vec<()>>();
326 // The lint or lint group doesn't exist.
327 // This is an error, but it was handled
328 // by check_lint_name_cmdline.
335 self.lint_cap = sess.opts.lint_cap;
336 if let Some(cap) = self.lint_cap {
337 for level in self.levels.iter_mut().map(|p| &mut (p.1).0) {
338 *level = cmp::min(*level, cap);
344 /// Context for lint checking after type checking.
345 pub struct LateContext<'a, 'tcx: 'a> {
346 /// Type context we're checking in.
347 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
349 /// Side-tables for the body we are in.
350 pub tables: &'a ty::TypeckTables<'tcx>,
352 /// The crate being checked.
353 pub krate: &'a hir::Crate,
355 /// Items accessible from the crate being checked.
356 pub access_levels: &'a AccessLevels,
358 /// The store of registered lints.
361 /// When recursing into an attributed node of the ast which modifies lint
362 /// levels, this stack keeps track of the previous lint levels of whatever
364 level_stack: Vec<(LintId, LevelSource)>,
367 /// Context for lint checking of the AST, after expansion, before lowering to
369 pub struct EarlyContext<'a> {
370 /// Type context we're checking in.
371 pub sess: &'a Session,
373 /// The crate being checked.
374 pub krate: &'a ast::Crate,
376 /// The store of registered lints.
379 /// When recursing into an attributed node of the ast which modifies lint
380 /// levels, this stack keeps track of the previous lint levels of whatever
382 level_stack: Vec<(LintId, LevelSource)>,
385 /// Convenience macro for calling a `LintPass` method on every pass in the context.
386 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
387 // Move the vector of passes out of `$cx` so that we can
388 // iterate over it mutably while passing `$cx` to the methods.
389 let mut passes = $cx.mut_lints().$ps.take().unwrap();
390 for obj in &mut passes {
391 obj.$f($cx, $($args),*);
393 $cx.mut_lints().$ps = Some(passes);
396 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
397 /// attributes. Writing this as an iterator is an enormous mess.
398 // See also the hir version just below.
399 pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec<Result<(ast::Name, Level, Span), Span>> {
400 let mut out = vec![];
402 let r = gather_attr(attr);
403 out.extend(r.into_iter());
408 pub fn gather_attr(attr: &ast::Attribute) -> Vec<Result<(ast::Name, Level, Span), Span>> {
409 let mut out = vec![];
411 let level = match attr.name().and_then(|name| Level::from_str(&name.as_str())) {
416 let meta = unwrap_or!(attr.meta(), return out);
417 attr::mark_used(attr);
419 let metas = if let Some(metas) = meta.meta_item_list() {
422 out.push(Err(meta.span));
427 out.push(li.word().map_or(Err(li.span), |word| Ok((word.name(), level, word.span))));
433 /// Emit a lint as a warning or an error (or not at all)
434 /// according to `level`.
436 /// This lives outside of `Context` so it can be used by checks
437 /// in trans that run after the main lint pass is finished. Most
438 /// lints elsewhere in the compiler should call
439 /// `Session::add_lint()` instead.
440 pub fn raw_emit_lint<S: Into<MultiSpan>>(sess: &Session,
446 raw_struct_lint(sess, lints, lint, lvlsrc, span, msg).emit();
449 pub fn raw_struct_lint<'a, S>(sess: &'a Session,
455 -> DiagnosticBuilder<'a>
456 where S: Into<MultiSpan>
458 let (level, source) = lvlsrc;
460 return sess.diagnostic().struct_dummy();
463 let name = lint.name_lower();
466 // Except for possible note details, forbid behaves like deny.
467 let effective_level = if level == Forbid { Deny } else { level };
469 let mut err = match (effective_level, span) {
470 (Warn, Some(sp)) => sess.struct_span_warn(sp, &msg[..]),
471 (Warn, None) => sess.struct_warn(&msg[..]),
472 (Deny, Some(sp)) => sess.struct_span_err(sp, &msg[..]),
473 (Deny, None) => sess.struct_err(&msg[..]),
474 _ => bug!("impossible level in raw_emit_lint"),
479 err.note(&format!("#[{}({})] on by default", level.as_str(), name));
481 CommandLine(lint_flag_val) => {
482 let flag = match level {
483 Warn => "-W", Deny => "-D", Forbid => "-F",
484 Allow => bug!("earlier conditional return should handle Allow case")
486 let hyphen_case_lint_name = name.replace("_", "-");
487 if lint_flag_val.as_str() == name {
488 err.note(&format!("requested on the command line with `{} {}`",
489 flag, hyphen_case_lint_name));
491 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
492 err.note(&format!("`{} {}` implied by `{} {}`",
493 flag, hyphen_case_lint_name, flag, hyphen_case_flag_val));
496 Node(lint_attr_name, src) => {
498 if lint_attr_name.as_str() != name {
499 let level_str = level.as_str();
500 err.note(&format!("#[{}({})] implied by #[{}({})]",
501 level_str, name, level_str, lint_attr_name));
506 // Check for future incompatibility lints and issue a stronger warning.
507 if let Some(future_incompatible) = lints.future_incompatible(LintId::of(lint)) {
508 let explanation = format!("this was previously accepted by the compiler \
509 but is being phased out; \
510 it will become a hard error in a future release!");
511 let citation = format!("for more information, see {}",
512 future_incompatible.reference);
513 err.warn(&explanation);
517 if let Some(span) = def {
518 sess.diag_span_note_once(&mut err, lint, span, "lint level defined here");
524 pub trait LintContext<'tcx>: Sized {
525 fn sess(&self) -> &Session;
526 fn lints(&self) -> &LintStore;
527 fn mut_lints(&mut self) -> &mut LintStore;
528 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>;
529 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
530 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
532 /// Get the level of `lint` at the current position of the lint
534 fn current_level(&self, lint: &'static Lint) -> Level {
535 self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
538 fn level_src(&self, lint: &'static Lint) -> Option<LevelSource> {
539 self.lints().levels.get(&LintId::of(lint)).map(|ls| match ls {
541 let lint_id = LintId::of(builtin::WARNINGS);
542 let warn_src = self.lints().get_level_source(lint_id);
543 if warn_src.0 != Warn {
553 fn lookup_and_emit<S: Into<MultiSpan>>(&self,
557 let (level, src) = match self.level_src(lint) {
562 raw_emit_lint(&self.sess(), self.lints(), lint, (level, src), span, msg);
565 fn lookup<S: Into<MultiSpan>>(&self,
569 -> DiagnosticBuilder {
570 let (level, src) = match self.level_src(lint) {
571 None => return self.sess().diagnostic().struct_dummy(),
575 raw_struct_lint(&self.sess(), self.lints(), lint, (level, src), span, msg)
578 /// Emit a lint at the appropriate level, for a particular span.
579 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
580 self.lookup_and_emit(lint, Some(span), msg);
583 fn early_lint(&self, early_lint: &EarlyLint) {
584 let span = early_lint.diagnostic.span.primary_span().expect("early lint w/o primary span");
585 let mut err = self.struct_span_lint(early_lint.id.lint,
587 &early_lint.diagnostic.message());
588 err.copy_details_not_message(&early_lint.diagnostic);
592 fn struct_span_lint<S: Into<MultiSpan>>(&self,
596 -> DiagnosticBuilder {
597 self.lookup(lint, Some(span), msg)
600 /// Emit a lint and note at the appropriate level, for a particular span.
601 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
602 note_span: Span, note: &str) {
603 let mut err = self.lookup(lint, Some(span), msg);
604 if self.current_level(lint) != Level::Allow {
605 if note_span == span {
608 err.span_note(note_span, note);
614 /// Emit a lint and help at the appropriate level, for a particular span.
615 fn span_lint_help(&self, lint: &'static Lint, span: Span,
616 msg: &str, help: &str) {
617 let mut err = self.lookup(lint, Some(span), msg);
618 self.span_lint(lint, span, msg);
619 if self.current_level(lint) != Level::Allow {
620 err.span_help(span, help);
625 /// Emit a lint at the appropriate level, with no associated span.
626 fn lint(&self, lint: &'static Lint, msg: &str) {
627 self.lookup_and_emit(lint, None as Option<Span>, msg);
630 /// Merge the lints specified by any lint attributes into the
631 /// current lint context, call the provided function, then reset the
632 /// lints in effect to their previous state.
633 fn with_lint_attrs<F>(&mut self,
634 attrs: &'tcx [ast::Attribute],
636 where F: FnOnce(&mut Self),
638 // Parse all of the lint attributes, and then add them all to the
639 // current dictionary of lint information. Along the way, keep a history
640 // of what we changed so we can roll everything back after invoking the
644 for result in gather_attrs(attrs) {
645 let v = match result {
647 span_err!(self.sess(), span, E0452,
648 "malformed lint attribute");
651 Ok((lint_name, level, span)) => {
652 match self.lints().find_lint(&lint_name.as_str(), &self.sess(), Some(span)) {
653 Ok(lint_id) => vec![(lint_id, level, span)],
654 Err(FindLintError::NotFound) => {
655 match self.lints().lint_groups.get(&*lint_name.as_str()) {
656 Some(&(ref v, _)) => v.iter()
657 .map(|lint_id: &LintId|
658 (*lint_id, level, span))
661 // The lint or lint group doesn't exist.
662 // This is an error, but it was handled
663 // by check_lint_name_attribute.
668 Err(FindLintError::Removed) => { continue; }
673 let lint_attr_name = result.expect("lint attribute should be well-formed").0;
675 for (lint_id, level, span) in v {
676 let (now, now_source) = self.lints().get_level_source(lint_id);
677 if now == Forbid && level != Forbid {
678 let lint_name = lint_id.to_string();
679 let mut diag_builder = struct_span_err!(self.sess(), span, E0453,
680 "{}({}) overruled by outer forbid({})",
681 level.as_str(), lint_name,
683 diag_builder.span_label(span, &format!("overruled by previous forbid"));
685 LintSource::Default => &mut diag_builder,
686 LintSource::Node(_, forbid_source_span) => {
687 diag_builder.span_label(forbid_source_span,
688 &format!("`forbid` level set here"))
690 LintSource::CommandLine(_) => {
691 diag_builder.note("`forbid` lint level was set on command line")
694 } else if now != level {
695 let src = self.lints().get_level_source(lint_id).1;
696 self.level_stack().push((lint_id, (now, src)));
698 self.mut_lints().set_level(lint_id, (level, Node(lint_attr_name, span)));
703 self.enter_attrs(attrs);
705 self.exit_attrs(attrs);
709 let (lint, lvlsrc) = self.level_stack().pop().unwrap();
710 self.mut_lints().set_level(lint, lvlsrc);
716 impl<'a> EarlyContext<'a> {
717 fn new(sess: &'a Session,
718 krate: &'a ast::Crate) -> EarlyContext<'a> {
719 // We want to own the lint store, so move it out of the session. Remember
720 // to put it back later...
721 let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
732 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
733 /// Get the overall compiler `Session` object.
734 fn sess(&self) -> &Session {
738 fn lints(&self) -> &LintStore {
742 fn mut_lints(&mut self) -> &mut LintStore {
746 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
747 &mut self.level_stack
750 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
751 debug!("late context: enter_attrs({:?})", attrs);
752 run_lints!(self, enter_lint_attrs, late_passes, attrs);
755 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
756 debug!("late context: exit_attrs({:?})", attrs);
757 run_lints!(self, exit_lint_attrs, late_passes, attrs);
761 impl<'a> LintContext<'a> for EarlyContext<'a> {
762 /// Get the overall compiler `Session` object.
763 fn sess(&self) -> &Session {
767 fn lints(&self) -> &LintStore {
771 fn mut_lints(&mut self) -> &mut LintStore {
775 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
776 &mut self.level_stack
779 fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
780 debug!("early context: enter_attrs({:?})", attrs);
781 run_lints!(self, enter_lint_attrs, early_passes, attrs);
784 fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
785 debug!("early context: exit_attrs({:?})", attrs);
786 run_lints!(self, exit_lint_attrs, early_passes, attrs);
790 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
791 /// Because lints are scoped lexically, we want to walk nested
792 /// items in the context of the outer item, so enable
794 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
795 hir_visit::NestedVisitorMap::All(&self.tcx.hir)
798 // Output any lints that were previously added to the session.
799 fn visit_id(&mut self, id: ast::NodeId) {
800 let lints = self.sess().lints.borrow_mut().take(id);
801 for early_lint in lints.iter().chain(self.tables.lints.get(id)) {
802 debug!("LateContext::visit_id: id={:?} early_lint={:?}", id, early_lint);
803 self.early_lint(early_lint);
807 fn visit_nested_body(&mut self, body: hir::BodyId) {
808 let old_tables = self.tables;
809 self.tables = self.tcx.body_tables(body);
810 let body = self.tcx.hir.body(body);
811 self.visit_body(body);
812 self.tables = old_tables;
815 fn visit_body(&mut self, body: &'tcx hir::Body) {
816 run_lints!(self, check_body, late_passes, body);
817 hir_visit::walk_body(self, body);
818 run_lints!(self, check_body_post, late_passes, body);
821 fn visit_item(&mut self, it: &'tcx hir::Item) {
822 self.with_lint_attrs(&it.attrs, |cx| {
823 run_lints!(cx, check_item, late_passes, it);
824 hir_visit::walk_item(cx, it);
825 run_lints!(cx, check_item_post, late_passes, it);
829 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
830 self.with_lint_attrs(&it.attrs, |cx| {
831 run_lints!(cx, check_foreign_item, late_passes, it);
832 hir_visit::walk_foreign_item(cx, it);
833 run_lints!(cx, check_foreign_item_post, late_passes, it);
837 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
838 run_lints!(self, check_pat, late_passes, p);
839 hir_visit::walk_pat(self, p);
842 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
843 self.with_lint_attrs(&e.attrs, |cx| {
844 run_lints!(cx, check_expr, late_passes, e);
845 hir_visit::walk_expr(cx, e);
846 run_lints!(cx, check_expr_post, late_passes, e);
850 fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
851 // statement attributes are actually just attributes on one of
855 // so we keep track of lint levels there
856 run_lints!(self, check_stmt, late_passes, s);
857 hir_visit::walk_stmt(self, s);
860 fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
861 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
862 // Wrap in tables here, not just in visit_nested_body,
863 // in order for `check_fn` to be able to use them.
864 let old_tables = self.tables;
865 self.tables = self.tcx.body_tables(body_id);
866 let body = self.tcx.hir.body(body_id);
867 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
868 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
869 run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
870 self.tables = old_tables;
873 fn visit_variant_data(&mut self,
874 s: &'tcx hir::VariantData,
876 g: &'tcx hir::Generics,
877 item_id: ast::NodeId,
879 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
880 hir_visit::walk_struct_def(self, s);
881 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
884 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
885 self.with_lint_attrs(&s.attrs, |cx| {
886 run_lints!(cx, check_struct_field, late_passes, s);
887 hir_visit::walk_struct_field(cx, s);
891 fn visit_variant(&mut self,
892 v: &'tcx hir::Variant,
893 g: &'tcx hir::Generics,
894 item_id: ast::NodeId) {
895 self.with_lint_attrs(&v.node.attrs, |cx| {
896 run_lints!(cx, check_variant, late_passes, v, g);
897 hir_visit::walk_variant(cx, v, g, item_id);
898 run_lints!(cx, check_variant_post, late_passes, v, g);
902 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
903 run_lints!(self, check_ty, late_passes, t);
904 hir_visit::walk_ty(self, t);
907 fn visit_name(&mut self, sp: Span, name: ast::Name) {
908 run_lints!(self, check_name, late_passes, sp, name);
911 fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
912 run_lints!(self, check_mod, late_passes, m, s, n);
913 hir_visit::walk_mod(self, m, n);
914 run_lints!(self, check_mod_post, late_passes, m, s, n);
917 fn visit_local(&mut self, l: &'tcx hir::Local) {
918 self.with_lint_attrs(&l.attrs, |cx| {
919 run_lints!(cx, check_local, late_passes, l);
920 hir_visit::walk_local(cx, l);
924 fn visit_block(&mut self, b: &'tcx hir::Block) {
925 run_lints!(self, check_block, late_passes, b);
926 hir_visit::walk_block(self, b);
927 run_lints!(self, check_block_post, late_passes, b);
930 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
931 run_lints!(self, check_arm, late_passes, a);
932 hir_visit::walk_arm(self, a);
935 fn visit_decl(&mut self, d: &'tcx hir::Decl) {
936 run_lints!(self, check_decl, late_passes, d);
937 hir_visit::walk_decl(self, d);
940 fn visit_generics(&mut self, g: &'tcx hir::Generics) {
941 run_lints!(self, check_generics, late_passes, g);
942 hir_visit::walk_generics(self, g);
945 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
946 self.with_lint_attrs(&trait_item.attrs, |cx| {
947 run_lints!(cx, check_trait_item, late_passes, trait_item);
948 hir_visit::walk_trait_item(cx, trait_item);
949 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
953 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
954 self.with_lint_attrs(&impl_item.attrs, |cx| {
955 run_lints!(cx, check_impl_item, late_passes, impl_item);
956 hir_visit::walk_impl_item(cx, impl_item);
957 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
961 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
962 run_lints!(self, check_lifetime, late_passes, lt);
963 hir_visit::walk_lifetime(self, lt);
966 fn visit_lifetime_def(&mut self, lt: &'tcx hir::LifetimeDef) {
967 run_lints!(self, check_lifetime_def, late_passes, lt);
968 hir_visit::walk_lifetime_def(self, lt);
971 fn visit_path(&mut self, p: &'tcx hir::Path, id: ast::NodeId) {
972 run_lints!(self, check_path, late_passes, p, id);
973 hir_visit::walk_path(self, p);
976 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
977 check_lint_name_attribute(self, attr);
978 run_lints!(self, check_attribute, late_passes, attr);
982 impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> {
983 fn visit_item(&mut self, it: &'a ast::Item) {
984 self.with_lint_attrs(&it.attrs, |cx| {
985 run_lints!(cx, check_item, early_passes, it);
986 ast_visit::walk_item(cx, it);
987 run_lints!(cx, check_item_post, early_passes, it);
991 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
992 self.with_lint_attrs(&it.attrs, |cx| {
993 run_lints!(cx, check_foreign_item, early_passes, it);
994 ast_visit::walk_foreign_item(cx, it);
995 run_lints!(cx, check_foreign_item_post, early_passes, it);
999 fn visit_pat(&mut self, p: &'a ast::Pat) {
1000 run_lints!(self, check_pat, early_passes, p);
1001 ast_visit::walk_pat(self, p);
1004 fn visit_expr(&mut self, e: &'a ast::Expr) {
1005 self.with_lint_attrs(&e.attrs, |cx| {
1006 run_lints!(cx, check_expr, early_passes, e);
1007 ast_visit::walk_expr(cx, e);
1011 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
1012 run_lints!(self, check_stmt, early_passes, s);
1013 ast_visit::walk_stmt(self, s);
1016 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
1017 span: Span, id: ast::NodeId) {
1018 run_lints!(self, check_fn, early_passes, fk, decl, span, id);
1019 ast_visit::walk_fn(self, fk, decl, span);
1020 run_lints!(self, check_fn_post, early_passes, fk, decl, span, id);
1023 fn visit_variant_data(&mut self,
1024 s: &'a ast::VariantData,
1026 g: &'a ast::Generics,
1027 item_id: ast::NodeId,
1029 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
1030 ast_visit::walk_struct_def(self, s);
1031 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
1034 fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1035 self.with_lint_attrs(&s.attrs, |cx| {
1036 run_lints!(cx, check_struct_field, early_passes, s);
1037 ast_visit::walk_struct_field(cx, s);
1041 fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1042 self.with_lint_attrs(&v.node.attrs, |cx| {
1043 run_lints!(cx, check_variant, early_passes, v, g);
1044 ast_visit::walk_variant(cx, v, g, item_id);
1045 run_lints!(cx, check_variant_post, early_passes, v, g);
1049 fn visit_ty(&mut self, t: &'a ast::Ty) {
1050 run_lints!(self, check_ty, early_passes, t);
1051 ast_visit::walk_ty(self, t);
1054 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
1055 run_lints!(self, check_ident, early_passes, sp, id);
1058 fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, n: ast::NodeId) {
1059 run_lints!(self, check_mod, early_passes, m, s, n);
1060 ast_visit::walk_mod(self, m);
1061 run_lints!(self, check_mod_post, early_passes, m, s, n);
1064 fn visit_local(&mut self, l: &'a ast::Local) {
1065 self.with_lint_attrs(&l.attrs, |cx| {
1066 run_lints!(cx, check_local, early_passes, l);
1067 ast_visit::walk_local(cx, l);
1071 fn visit_block(&mut self, b: &'a ast::Block) {
1072 run_lints!(self, check_block, early_passes, b);
1073 ast_visit::walk_block(self, b);
1074 run_lints!(self, check_block_post, early_passes, b);
1077 fn visit_arm(&mut self, a: &'a ast::Arm) {
1078 run_lints!(self, check_arm, early_passes, a);
1079 ast_visit::walk_arm(self, a);
1082 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1083 run_lints!(self, check_expr_post, early_passes, e);
1086 fn visit_generics(&mut self, g: &'a ast::Generics) {
1087 run_lints!(self, check_generics, early_passes, g);
1088 ast_visit::walk_generics(self, g);
1091 fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1092 self.with_lint_attrs(&trait_item.attrs, |cx| {
1093 run_lints!(cx, check_trait_item, early_passes, trait_item);
1094 ast_visit::walk_trait_item(cx, trait_item);
1095 run_lints!(cx, check_trait_item_post, early_passes, trait_item);
1099 fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1100 self.with_lint_attrs(&impl_item.attrs, |cx| {
1101 run_lints!(cx, check_impl_item, early_passes, impl_item);
1102 ast_visit::walk_impl_item(cx, impl_item);
1103 run_lints!(cx, check_impl_item_post, early_passes, impl_item);
1107 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1108 run_lints!(self, check_lifetime, early_passes, lt);
1111 fn visit_lifetime_def(&mut self, lt: &'a ast::LifetimeDef) {
1112 run_lints!(self, check_lifetime_def, early_passes, lt);
1115 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1116 run_lints!(self, check_path, early_passes, p, id);
1117 ast_visit::walk_path(self, p);
1120 fn visit_path_list_item(&mut self, prefix: &'a ast::Path, item: &'a ast::PathListItem) {
1121 run_lints!(self, check_path_list_item, early_passes, item);
1122 ast_visit::walk_path_list_item(self, prefix, item);
1125 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1126 run_lints!(self, check_attribute, early_passes, attr);
1130 enum CheckLintNameResult {
1132 // Lint doesn't exist
1134 // The lint is either renamed or removed. This is the warning
1139 /// Checks the name of a lint for its existence, and whether it was
1140 /// renamed or removed. Generates a DiagnosticBuilder containing a
1141 /// warning for renamed and removed lints. This is over both lint
1142 /// names from attributes and those passed on the command line. Since
1143 /// it emits non-fatal warnings and there are *two* lint passes that
1144 /// inspect attributes, this is only run from the late pass to avoid
1145 /// printing duplicate warnings.
1146 fn check_lint_name(lint_cx: &LintStore,
1147 lint_name: &str) -> CheckLintNameResult {
1148 match lint_cx.by_name.get(lint_name) {
1149 Some(&Renamed(ref new_name, _)) => {
1150 CheckLintNameResult::Warning(
1151 format!("lint {} has been renamed to {}", lint_name, new_name)
1154 Some(&Removed(ref reason)) => {
1155 CheckLintNameResult::Warning(
1156 format!("lint {} has been removed: {}", lint_name, reason)
1160 match lint_cx.lint_groups.get(lint_name) {
1162 CheckLintNameResult::NoLint
1165 /* lint group exists */
1166 CheckLintNameResult::Ok
1172 CheckLintNameResult::Ok
1177 // Checks the validity of lint names derived from attributes
1178 fn check_lint_name_attribute(cx: &LateContext, attr: &ast::Attribute) {
1179 for result in gather_attr(attr) {
1182 // Malformed lint attr. Reported by with_lint_attrs
1185 Ok((lint_name, _, span)) => {
1186 match check_lint_name(&cx.lints, &lint_name.as_str()) {
1187 CheckLintNameResult::Ok => (),
1188 CheckLintNameResult::Warning(ref msg) => {
1189 cx.span_lint(builtin::RENAMED_AND_REMOVED_LINTS,
1192 CheckLintNameResult::NoLint => {
1193 cx.span_lint(builtin::UNKNOWN_LINTS, span,
1194 &format!("unknown lint: `{}`",
1203 // Checks the validity of lint names derived from the command line
1204 fn check_lint_name_cmdline(sess: &Session, lint_cx: &LintStore,
1205 lint_name: &str, level: Level) {
1206 let db = match check_lint_name(lint_cx, lint_name) {
1207 CheckLintNameResult::Ok => None,
1208 CheckLintNameResult::Warning(ref msg) => {
1209 Some(sess.struct_warn(msg))
1211 CheckLintNameResult::NoLint => {
1212 Some(sess.struct_err(&format!("unknown lint: `{}`", lint_name)))
1216 if let Some(mut db) = db {
1217 let msg = format!("requested on the command line with `{} {}`",
1219 Level::Allow => "-A",
1220 Level::Warn => "-W",
1221 Level::Deny => "-D",
1222 Level::Forbid => "-F",
1231 /// Perform lint checking on a crate.
1233 /// Consumes the `lint_store` field of the `Session`.
1234 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1235 let _task = tcx.dep_graph.in_task(DepNode::LateLintCheck);
1237 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1239 let krate = tcx.hir.krate();
1241 // We want to own the lint store, so move it out of the session.
1242 let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), LintStore::new());
1243 let mut cx = LateContext {
1245 tables: &ty::TypeckTables::empty(),
1247 access_levels: access_levels,
1249 level_stack: vec![],
1252 // Visit the whole crate.
1253 cx.with_lint_attrs(&krate.attrs, |cx| {
1254 // since the root module isn't visited as an item (because it isn't an
1255 // item), warn for it here.
1256 run_lints!(cx, check_crate, late_passes, krate);
1258 hir_visit::walk_crate(cx, krate);
1260 run_lints!(cx, check_crate_post, late_passes, krate);
1263 // If we missed any lints added to the session, then there's a bug somewhere
1264 // in the iteration code.
1265 if let Some((id, v)) = tcx.sess.lints.borrow().get_any() {
1266 for early_lint in v {
1267 span_bug!(early_lint.diagnostic.span.clone(),
1268 "unprocessed lint {:?} at {}",
1269 early_lint, tcx.hir.node_to_string(*id));
1273 // Put the lint store back in the session.
1274 mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), cx.lints);
1277 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1278 let mut cx = EarlyContext::new(sess, krate);
1280 // Visit the whole crate.
1281 cx.with_lint_attrs(&krate.attrs, |cx| {
1282 // Lints may be assigned to the whole crate.
1283 let lints = cx.sess.lints.borrow_mut().take(ast::CRATE_NODE_ID);
1284 for early_lint in lints {
1285 cx.early_lint(&early_lint);
1288 // since the root module isn't visited as an item (because it isn't an
1289 // item), warn for it here.
1290 run_lints!(cx, check_crate, early_passes, krate);
1292 ast_visit::walk_crate(cx, krate);
1294 run_lints!(cx, check_crate_post, early_passes, krate);
1297 // Put the lint store back in the session.
1298 mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1300 // If we missed any lints added to the session, then there's a bug somewhere
1301 // in the iteration code.
1302 for (_, v) in sess.lints.borrow().get_any() {
1303 for early_lint in v {
1304 span_bug!(early_lint.diagnostic.span.clone(), "unprocessed lint {:?}", early_lint);
1309 impl Encodable for LintId {
1310 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1311 s.emit_str(&self.lint.name.to_lowercase())
1315 impl Decodable for LintId {
1317 fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1318 let s = d.read_str()?;
1319 ty::tls::with(|tcx| {
1320 match tcx.sess.lint_store.borrow().find_lint(&s, tcx.sess, None) {
1322 Err(_) => panic!("invalid lint-id `{}`", s),