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;
43 use std::cell::{Ref, RefCell};
46 use syntax::symbol::Symbol;
47 use syntax_pos::{MultiSpan, Span};
48 use errors::{self, Diagnostic, DiagnosticBuilder};
50 use hir::def_id::LOCAL_CRATE;
51 use hir::intravisit as hir_visit;
52 use syntax::visit as ast_visit;
54 /// Information about the registered lints.
56 /// This is basically the subset of `Context` that we can
57 /// build early in the compile pipeline.
58 pub struct LintStore {
59 /// Registered lints. The bool is true if the lint was
60 /// added by a plugin.
61 lints: Vec<(&'static Lint, bool)>,
63 /// Trait objects for each lint pass.
64 /// This is only `None` while performing a lint pass. See the definition
65 /// of `LintSession::new`.
66 early_passes: Option<Vec<EarlyLintPassObject>>,
67 late_passes: Option<Vec<LateLintPassObject>>,
69 /// Lints indexed by name.
70 by_name: FxHashMap<String, TargetLint>,
72 /// Current levels of each lint, and where they were set.
75 /// Map of registered lint groups to what lints they expand to. The bool
76 /// is true if the lint group was added by a plugin.
77 lint_groups: FxHashMap<&'static str, (Vec<LintId>, bool)>,
79 /// Extra info for future incompatibility lints, descibing the
80 /// issue or RFC that caused the incompatibility.
81 future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
87 /// Current levels of each lint, and where they were set.
88 levels: FxHashMap<LintId, LevelSource>,
90 /// Maximum level a lint can be
91 lint_cap: Option<Level>,
95 pub struct LintSession<'a, PassObject> {
96 /// Reference to the store of registered lints.
97 lints: Ref<'a, LintStore>,
99 /// The current lint levels.
102 /// When recursing into an attributed node of the ast which modifies lint
103 /// levels, this stack keeps track of the previous lint levels of whatever
105 stack: Vec<(LintId, LevelSource)>,
107 /// Trait objects for each lint pass.
108 passes: Option<Vec<PassObject>>,
112 /// When you call `add_lint` on the session, you wind up storing one
113 /// of these, which records a "potential lint" at a particular point.
114 #[derive(PartialEq, RustcEncodable, RustcDecodable)]
115 pub struct EarlyLint {
116 /// what lint is this? (e.g., `dead_code`)
120 pub diagnostic: Diagnostic,
123 impl fmt::Debug for EarlyLint {
124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125 f.debug_struct("EarlyLint")
126 .field("id", &self.id)
127 .field("span", &self.diagnostic.span)
128 .field("diagnostic", &self.diagnostic)
133 pub trait IntoEarlyLint {
134 fn into_early_lint(self, id: LintId) -> EarlyLint;
137 impl<'a, S: Into<MultiSpan>> IntoEarlyLint for (S, &'a str) {
138 fn into_early_lint(self, id: LintId) -> EarlyLint {
139 let (span, msg) = self;
140 let mut diagnostic = Diagnostic::new(errors::Level::Warning, msg);
141 diagnostic.set_span(span);
144 diagnostic: diagnostic,
149 impl IntoEarlyLint for Diagnostic {
150 fn into_early_lint(self, id: LintId) -> EarlyLint {
158 /// Extra information for a future incompatibility lint. See the call
159 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
161 pub struct FutureIncompatibleInfo {
163 pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
166 /// The targed of the `by_name` map, which accounts for renaming/deprecation.
168 /// A direct lint target
171 /// Temporary renaming, used for easing migration pain; see #16545
172 Renamed(String, LintId),
174 /// Lint with this name existed previously, but has been removed/deprecated.
175 /// The string argument is the reason for removal.
185 pub fn new() -> LintStore {
188 early_passes: Some(vec![]),
189 late_passes: Some(vec![]),
190 by_name: FxHashMap(),
191 levels: LintLevels::default(),
192 future_incompatible: FxHashMap(),
193 lint_groups: FxHashMap(),
197 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
201 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
202 self.lint_groups.iter().map(|(k, v)| (*k,
207 pub fn register_early_pass(&mut self,
208 sess: Option<&Session>,
210 pass: EarlyLintPassObject) {
211 self.push_pass(sess, from_plugin, &pass);
212 self.early_passes.as_mut().unwrap().push(pass);
215 pub fn register_late_pass(&mut self,
216 sess: Option<&Session>,
218 pass: LateLintPassObject) {
219 self.push_pass(sess, from_plugin, &pass);
220 self.late_passes.as_mut().unwrap().push(pass);
223 // Helper method for register_early/late_pass
224 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
225 sess: Option<&Session>,
228 for &lint in pass.get_lints() {
229 self.lints.push((*lint, from_plugin));
231 let id = LintId::of(*lint);
232 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
233 let msg = format!("duplicate specification of lint {}", lint.name_lower());
234 match (sess, from_plugin) {
235 // We load builtin lints first, so a duplicate is a compiler bug.
236 // Use early_error when handling -W help with no crate.
237 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
238 (Some(_), false) => bug!("{}", msg),
240 // A duplicate name from a plugin is a user error.
241 (Some(sess), true) => sess.err(&msg[..]),
245 self.levels.set(id, (lint.default_level, Default));
249 pub fn register_future_incompatible(&mut self,
250 sess: Option<&Session>,
251 lints: Vec<FutureIncompatibleInfo>) {
252 let ids = lints.iter().map(|f| f.id).collect();
253 self.register_group(sess, false, "future_incompatible", ids);
255 self.future_incompatible.insert(info.id, info);
259 pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
260 self.future_incompatible.get(&id)
263 pub fn register_group(&mut self, sess: Option<&Session>,
264 from_plugin: bool, name: &'static str,
266 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
269 let msg = format!("duplicate specification of lint group {}", name);
270 match (sess, from_plugin) {
271 // We load builtin lints first, so a duplicate is a compiler bug.
272 // Use early_error when handling -W help with no crate.
273 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
274 (Some(_), false) => bug!("{}", msg),
276 // A duplicate name from a plugin is a user error.
277 (Some(sess), true) => sess.err(&msg[..]),
282 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
283 let target = match self.by_name.get(new_name) {
284 Some(&Id(lint_id)) => lint_id.clone(),
285 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
287 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
290 pub fn register_removed(&mut self, name: &str, reason: &str) {
291 self.by_name.insert(name.into(), Removed(reason.into()));
294 #[allow(unused_variables)]
295 fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
296 -> Result<LintId, FindLintError>
298 match self.by_name.get(lint_name) {
299 Some(&Id(lint_id)) => Ok(lint_id),
300 Some(&Renamed(_, lint_id)) => {
303 Some(&Removed(ref reason)) => {
304 Err(FindLintError::Removed)
306 None => Err(FindLintError::NotFound)
310 pub fn process_command_line(&mut self, sess: &Session) {
311 for &(ref lint_name, level) in &sess.opts.lint_opts {
312 check_lint_name_cmdline(sess, self,
313 &lint_name[..], level);
315 let lint_flag_val = Symbol::intern(&lint_name);
316 match self.find_lint(&lint_name[..], sess, None) {
317 Ok(lint_id) => self.levels.set(lint_id, (level, CommandLine(lint_flag_val))),
318 Err(FindLintError::Removed) => { }
320 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
321 .collect::<FxHashMap<&'static str,
323 .get(&lint_name[..]) {
326 self.levels.set(*lint_id, (level, CommandLine(lint_flag_val)));
330 // The lint or lint group doesn't exist.
331 // This is an error, but it was handled
332 // by check_lint_name_cmdline.
339 self.levels.set_lint_cap(sess.opts.lint_cap);
345 fn get_source(&self, lint: LintId) -> LevelSource {
346 match self.levels.get(&lint) {
348 None => (Allow, Default),
352 fn set(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
353 if let Some(cap) = self.lint_cap {
354 lvlsrc.0 = cmp::min(lvlsrc.0, cap);
356 if lvlsrc.0 == Allow {
357 self.levels.remove(&lint);
359 self.levels.insert(lint, lvlsrc);
363 fn set_lint_cap(&mut self, lint_cap: Option<Level>) {
364 self.lint_cap = lint_cap;
365 if let Some(cap) = lint_cap {
366 for (_, level) in &mut self.levels {
367 level.0 = cmp::min(level.0, cap);
374 impl<'a, PassObject: LintPassObject> LintSession<'a, PassObject> {
375 /// Creates a new `LintSession`, by moving out the `LintStore`'s initial
376 /// lint levels and pass objects. These can be restored using the `restore`
378 fn new(store: &'a RefCell<LintStore>) -> LintSession<'a, PassObject> {
379 let mut s = store.borrow_mut();
380 let levels = mem::replace(&mut s.levels, LintLevels::default());
381 let passes = PassObject::take_passes(&mut *s);
384 lints: store.borrow(),
391 /// Restores the levels back to the original lint store.
392 fn restore(self, store: &RefCell<LintStore>) {
394 let mut s = store.borrow_mut();
395 s.levels = self.levels;
396 PassObject::restore_passes(&mut *s, self.passes);
399 fn get_source(&self, lint_id: LintId) -> LevelSource {
400 self.levels.get_source(lint_id)
406 /// Context for lint checking after type checking.
407 pub struct LateContext<'a, 'tcx: 'a> {
408 /// Type context we're checking in.
409 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
411 /// Side-tables for the body we are in.
412 pub tables: &'a ty::TypeckTables<'tcx>,
414 /// The crate being checked.
415 pub krate: &'a hir::Crate,
417 /// Items accessible from the crate being checked.
418 pub access_levels: &'a AccessLevels,
420 /// The store of registered lints and the lint levels.
421 lint_sess: LintSession<'tcx, LateLintPassObject>,
424 /// Context for lint checking of the AST, after expansion, before lowering to
426 pub struct EarlyContext<'a> {
427 /// Type context we're checking in.
428 pub sess: &'a Session,
430 /// The crate being checked.
431 pub krate: &'a ast::Crate,
433 /// The store of registered lints and the lint levels.
434 lint_sess: LintSession<'a, EarlyLintPassObject>,
437 /// Convenience macro for calling a `LintPass` method on every pass in the context.
438 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
439 // Move the vector of passes out of `$cx` so that we can
440 // iterate over it mutably while passing `$cx` to the methods.
441 let mut passes = $cx.lint_sess_mut().passes.take().unwrap();
442 for obj in &mut passes {
443 obj.$f($cx, $($args),*);
445 $cx.lint_sess_mut().passes = Some(passes);
448 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
449 /// attributes. Writing this as an iterator is an enormous mess.
450 // See also the hir version just below.
451 pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec<Result<(ast::Name, Level, Span), Span>> {
452 let mut out = vec![];
454 let r = gather_attr(attr);
455 out.extend(r.into_iter());
460 pub fn gather_attr(attr: &ast::Attribute) -> Vec<Result<(ast::Name, Level, Span), Span>> {
461 let mut out = vec![];
463 let level = match attr.name().and_then(|name| Level::from_str(&name.as_str())) {
468 let meta = unwrap_or!(attr.meta(), return out);
469 attr::mark_used(attr);
471 let metas = if let Some(metas) = meta.meta_item_list() {
474 out.push(Err(meta.span));
479 out.push(li.word().map_or(Err(li.span), |word| Ok((word.name(), level, word.span))));
485 /// Emit a lint as a warning or an error (or not at all)
486 /// according to `level`.
488 /// This lives outside of `Context` so it can be used by checks
489 /// in trans that run after the main lint pass is finished. Most
490 /// lints elsewhere in the compiler should call
491 /// `Session::add_lint()` instead.
492 pub fn raw_emit_lint<S: Into<MultiSpan>>(sess: &Session,
498 raw_struct_lint(sess, lints, lint, lvlsrc, span, msg).emit();
501 pub fn raw_struct_lint<'a, S>(sess: &'a Session,
507 -> DiagnosticBuilder<'a>
508 where S: Into<MultiSpan>
510 let (level, source) = lvlsrc;
512 return sess.diagnostic().struct_dummy();
515 let name = lint.name_lower();
518 // Except for possible note details, forbid behaves like deny.
519 let effective_level = if level == Forbid { Deny } else { level };
521 let mut err = match (effective_level, span) {
522 (Warn, Some(sp)) => sess.struct_span_warn(sp, &msg[..]),
523 (Warn, None) => sess.struct_warn(&msg[..]),
524 (Deny, Some(sp)) => sess.struct_span_err(sp, &msg[..]),
525 (Deny, None) => sess.struct_err(&msg[..]),
526 _ => bug!("impossible level in raw_emit_lint"),
531 err.note(&format!("#[{}({})] on by default", level.as_str(), name));
533 CommandLine(lint_flag_val) => {
534 let flag = match level {
535 Warn => "-W", Deny => "-D", Forbid => "-F",
536 Allow => bug!("earlier conditional return should handle Allow case")
538 let hyphen_case_lint_name = name.replace("_", "-");
539 if lint_flag_val.as_str() == name {
540 err.note(&format!("requested on the command line with `{} {}`",
541 flag, hyphen_case_lint_name));
543 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
544 err.note(&format!("`{} {}` implied by `{} {}`",
545 flag, hyphen_case_lint_name, flag, hyphen_case_flag_val));
548 Node(lint_attr_name, src) => {
550 if lint_attr_name.as_str() != name {
551 let level_str = level.as_str();
552 err.note(&format!("#[{}({})] implied by #[{}({})]",
553 level_str, name, level_str, lint_attr_name));
558 // Check for future incompatibility lints and issue a stronger warning.
559 if let Some(future_incompatible) = lints.future_incompatible(LintId::of(lint)) {
560 let explanation = format!("this was previously accepted by the compiler \
561 but is being phased out; \
562 it will become a hard error in a future release!");
563 let citation = format!("for more information, see {}",
564 future_incompatible.reference);
565 err.warn(&explanation);
569 if let Some(span) = def {
570 sess.diag_span_note_once(&mut err, lint, span, "lint level defined here");
577 pub trait LintPassObject: Sized {
578 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>>;
579 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>);
582 impl LintPassObject for EarlyLintPassObject {
583 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>> {
584 store.early_passes.take()
587 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>) {
588 store.early_passes = passes;
592 impl LintPassObject for LateLintPassObject {
593 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>> {
594 store.late_passes.take()
597 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>) {
598 store.late_passes = passes;
603 pub trait LintContext<'tcx>: Sized {
604 type PassObject: LintPassObject;
606 fn sess(&self) -> &Session;
607 fn lints(&self) -> &LintStore;
608 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject>;
609 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject>;
610 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
611 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
613 /// Get the level of `lint` at the current position of the lint
615 fn current_level(&self, lint: &'static Lint) -> Level {
616 self.lint_sess().get_source(LintId::of(lint)).0
619 fn level_src(&self, lint: &'static Lint) -> Option<LevelSource> {
620 let ref levels = self.lint_sess().levels;
621 levels.levels.get(&LintId::of(lint)).map(|ls| match ls {
623 let lint_id = LintId::of(builtin::WARNINGS);
624 let warn_src = levels.get_source(lint_id);
625 if warn_src.0 != Warn {
635 fn lookup_and_emit<S: Into<MultiSpan>>(&self,
639 let (level, src) = match self.level_src(lint) {
644 raw_emit_lint(&self.sess(), self.lints(), lint, (level, src), span, msg);
647 fn lookup<S: Into<MultiSpan>>(&self,
651 -> DiagnosticBuilder {
652 let (level, src) = match self.level_src(lint) {
653 None => return self.sess().diagnostic().struct_dummy(),
657 raw_struct_lint(&self.sess(), self.lints(), lint, (level, src), span, msg)
660 /// Emit a lint at the appropriate level, for a particular span.
661 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
662 self.lookup_and_emit(lint, Some(span), msg);
665 fn early_lint(&self, early_lint: &EarlyLint) {
666 let span = early_lint.diagnostic.span.primary_span().expect("early lint w/o primary span");
667 let mut err = self.struct_span_lint(early_lint.id.lint,
669 &early_lint.diagnostic.message());
670 err.copy_details_not_message(&early_lint.diagnostic);
674 fn struct_span_lint<S: Into<MultiSpan>>(&self,
678 -> DiagnosticBuilder {
679 self.lookup(lint, Some(span), msg)
682 /// Emit a lint and note at the appropriate level, for a particular span.
683 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
684 note_span: Span, note: &str) {
685 let mut err = self.lookup(lint, Some(span), msg);
686 if self.current_level(lint) != Level::Allow {
687 if note_span == span {
690 err.span_note(note_span, note);
696 /// Emit a lint and help at the appropriate level, for a particular span.
697 fn span_lint_help(&self, lint: &'static Lint, span: Span,
698 msg: &str, help: &str) {
699 let mut err = self.lookup(lint, Some(span), msg);
700 self.span_lint(lint, span, msg);
701 if self.current_level(lint) != Level::Allow {
702 err.span_help(span, help);
707 /// Emit a lint at the appropriate level, with no associated span.
708 fn lint(&self, lint: &'static Lint, msg: &str) {
709 self.lookup_and_emit(lint, None as Option<Span>, msg);
712 /// Merge the lints specified by any lint attributes into the
713 /// current lint context, call the provided function, then reset the
714 /// lints in effect to their previous state.
715 fn with_lint_attrs<F>(&mut self,
716 attrs: &'tcx [ast::Attribute],
718 where F: FnOnce(&mut Self),
720 // Parse all of the lint attributes, and then add them all to the
721 // current dictionary of lint information. Along the way, keep a history
722 // of what we changed so we can roll everything back after invoking the
726 for result in gather_attrs(attrs) {
727 let v = match result {
729 span_err!(self.sess(), span, E0452,
730 "malformed lint attribute");
733 Ok((lint_name, level, span)) => {
734 match self.lints().find_lint(&lint_name.as_str(), &self.sess(), Some(span)) {
735 Ok(lint_id) => vec![(lint_id, level, span)],
736 Err(FindLintError::NotFound) => {
737 match self.lints().lint_groups.get(&*lint_name.as_str()) {
738 Some(&(ref v, _)) => v.iter()
739 .map(|lint_id: &LintId|
740 (*lint_id, level, span))
743 // The lint or lint group doesn't exist.
744 // This is an error, but it was handled
745 // by check_lint_name_attribute.
750 Err(FindLintError::Removed) => { continue; }
755 let lint_attr_name = result.expect("lint attribute should be well-formed").0;
757 for (lint_id, level, span) in v {
758 let (now, now_source) = self.lint_sess().get_source(lint_id);
759 if now == Forbid && level != Forbid {
760 let lint_name = lint_id.to_string();
761 let mut diag_builder = struct_span_err!(self.sess(), span, E0453,
762 "{}({}) overruled by outer forbid({})",
763 level.as_str(), lint_name,
765 diag_builder.span_label(span, "overruled by previous forbid");
767 LintSource::Default => &mut diag_builder,
768 LintSource::Node(_, forbid_source_span) => {
769 diag_builder.span_label(forbid_source_span,
770 "`forbid` level set here")
772 LintSource::CommandLine(_) => {
773 diag_builder.note("`forbid` lint level was set on command line")
776 } else if now != level {
777 let cx = self.lint_sess_mut();
778 cx.stack.push((lint_id, (now, now_source)));
780 cx.levels.set(lint_id, (level, Node(lint_attr_name, span)));
785 self.enter_attrs(attrs);
787 self.exit_attrs(attrs);
790 let cx = self.lint_sess_mut();
792 let (lint, lvlsrc) = cx.stack.pop().unwrap();
793 cx.levels.set(lint, lvlsrc);
799 impl<'a> EarlyContext<'a> {
800 fn new(sess: &'a Session,
801 krate: &'a ast::Crate) -> EarlyContext<'a> {
805 lint_sess: LintSession::new(&sess.lint_store),
810 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
811 type PassObject = LateLintPassObject;
813 /// Get the overall compiler `Session` object.
814 fn sess(&self) -> &Session {
818 fn lints(&self) -> &LintStore {
819 &*self.lint_sess.lints
822 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject> {
826 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject> {
830 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
831 debug!("late context: enter_attrs({:?})", attrs);
832 run_lints!(self, enter_lint_attrs, late_passes, attrs);
835 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
836 debug!("late context: exit_attrs({:?})", attrs);
837 run_lints!(self, exit_lint_attrs, late_passes, attrs);
841 impl<'a> LintContext<'a> for EarlyContext<'a> {
842 type PassObject = EarlyLintPassObject;
844 /// Get the overall compiler `Session` object.
845 fn sess(&self) -> &Session {
849 fn lints(&self) -> &LintStore {
850 &*self.lint_sess.lints
853 fn lint_sess(&self) -> &LintSession<'a, Self::PassObject> {
857 fn lint_sess_mut(&mut self) -> &mut LintSession<'a, Self::PassObject> {
861 fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
862 debug!("early context: enter_attrs({:?})", attrs);
863 run_lints!(self, enter_lint_attrs, early_passes, attrs);
866 fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
867 debug!("early context: exit_attrs({:?})", attrs);
868 run_lints!(self, exit_lint_attrs, early_passes, attrs);
872 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
873 /// Because lints are scoped lexically, we want to walk nested
874 /// items in the context of the outer item, so enable
876 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
877 hir_visit::NestedVisitorMap::All(&self.tcx.hir)
880 // Output any lints that were previously added to the session.
881 fn visit_id(&mut self, id: ast::NodeId) {
882 let lints = self.sess().lints.borrow_mut().take(id);
883 for early_lint in lints.iter().chain(self.tables.lints.get(id)) {
884 debug!("LateContext::visit_id: id={:?} early_lint={:?}", id, early_lint);
885 self.early_lint(early_lint);
889 fn visit_nested_body(&mut self, body: hir::BodyId) {
890 let old_tables = self.tables;
891 self.tables = self.tcx.body_tables(body);
892 let body = self.tcx.hir.body(body);
893 self.visit_body(body);
894 self.tables = old_tables;
897 fn visit_body(&mut self, body: &'tcx hir::Body) {
898 run_lints!(self, check_body, late_passes, body);
899 hir_visit::walk_body(self, body);
900 run_lints!(self, check_body_post, late_passes, body);
903 fn visit_item(&mut self, it: &'tcx hir::Item) {
904 self.with_lint_attrs(&it.attrs, |cx| {
905 run_lints!(cx, check_item, late_passes, it);
906 hir_visit::walk_item(cx, it);
907 run_lints!(cx, check_item_post, late_passes, it);
911 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
912 self.with_lint_attrs(&it.attrs, |cx| {
913 run_lints!(cx, check_foreign_item, late_passes, it);
914 hir_visit::walk_foreign_item(cx, it);
915 run_lints!(cx, check_foreign_item_post, late_passes, it);
919 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
920 run_lints!(self, check_pat, late_passes, p);
921 hir_visit::walk_pat(self, p);
924 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
925 self.with_lint_attrs(&e.attrs, |cx| {
926 run_lints!(cx, check_expr, late_passes, e);
927 hir_visit::walk_expr(cx, e);
928 run_lints!(cx, check_expr_post, late_passes, e);
932 fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
933 // statement attributes are actually just attributes on one of
937 // so we keep track of lint levels there
938 run_lints!(self, check_stmt, late_passes, s);
939 hir_visit::walk_stmt(self, s);
942 fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
943 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
944 // Wrap in tables here, not just in visit_nested_body,
945 // in order for `check_fn` to be able to use them.
946 let old_tables = self.tables;
947 self.tables = self.tcx.body_tables(body_id);
948 let body = self.tcx.hir.body(body_id);
949 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
950 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
951 run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
952 self.tables = old_tables;
955 fn visit_variant_data(&mut self,
956 s: &'tcx hir::VariantData,
958 g: &'tcx hir::Generics,
959 item_id: ast::NodeId,
961 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
962 hir_visit::walk_struct_def(self, s);
963 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
966 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
967 self.with_lint_attrs(&s.attrs, |cx| {
968 run_lints!(cx, check_struct_field, late_passes, s);
969 hir_visit::walk_struct_field(cx, s);
973 fn visit_variant(&mut self,
974 v: &'tcx hir::Variant,
975 g: &'tcx hir::Generics,
976 item_id: ast::NodeId) {
977 self.with_lint_attrs(&v.node.attrs, |cx| {
978 run_lints!(cx, check_variant, late_passes, v, g);
979 hir_visit::walk_variant(cx, v, g, item_id);
980 run_lints!(cx, check_variant_post, late_passes, v, g);
984 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
985 run_lints!(self, check_ty, late_passes, t);
986 hir_visit::walk_ty(self, t);
989 fn visit_name(&mut self, sp: Span, name: ast::Name) {
990 run_lints!(self, check_name, late_passes, sp, name);
993 fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
994 run_lints!(self, check_mod, late_passes, m, s, n);
995 hir_visit::walk_mod(self, m, n);
996 run_lints!(self, check_mod_post, late_passes, m, s, n);
999 fn visit_local(&mut self, l: &'tcx hir::Local) {
1000 self.with_lint_attrs(&l.attrs, |cx| {
1001 run_lints!(cx, check_local, late_passes, l);
1002 hir_visit::walk_local(cx, l);
1006 fn visit_block(&mut self, b: &'tcx hir::Block) {
1007 run_lints!(self, check_block, late_passes, b);
1008 hir_visit::walk_block(self, b);
1009 run_lints!(self, check_block_post, late_passes, b);
1012 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
1013 run_lints!(self, check_arm, late_passes, a);
1014 hir_visit::walk_arm(self, a);
1017 fn visit_decl(&mut self, d: &'tcx hir::Decl) {
1018 run_lints!(self, check_decl, late_passes, d);
1019 hir_visit::walk_decl(self, d);
1022 fn visit_generics(&mut self, g: &'tcx hir::Generics) {
1023 run_lints!(self, check_generics, late_passes, g);
1024 hir_visit::walk_generics(self, g);
1027 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
1028 self.with_lint_attrs(&trait_item.attrs, |cx| {
1029 run_lints!(cx, check_trait_item, late_passes, trait_item);
1030 hir_visit::walk_trait_item(cx, trait_item);
1031 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
1035 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
1036 self.with_lint_attrs(&impl_item.attrs, |cx| {
1037 run_lints!(cx, check_impl_item, late_passes, impl_item);
1038 hir_visit::walk_impl_item(cx, impl_item);
1039 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
1043 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1044 run_lints!(self, check_lifetime, late_passes, lt);
1045 hir_visit::walk_lifetime(self, lt);
1048 fn visit_lifetime_def(&mut self, lt: &'tcx hir::LifetimeDef) {
1049 run_lints!(self, check_lifetime_def, late_passes, lt);
1050 hir_visit::walk_lifetime_def(self, lt);
1053 fn visit_path(&mut self, p: &'tcx hir::Path, id: ast::NodeId) {
1054 run_lints!(self, check_path, late_passes, p, id);
1055 hir_visit::walk_path(self, p);
1058 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
1059 check_lint_name_attribute(self, attr);
1060 run_lints!(self, check_attribute, late_passes, attr);
1064 impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> {
1065 fn visit_item(&mut self, it: &'a ast::Item) {
1066 self.with_lint_attrs(&it.attrs, |cx| {
1067 run_lints!(cx, check_item, early_passes, it);
1068 ast_visit::walk_item(cx, it);
1069 run_lints!(cx, check_item_post, early_passes, it);
1073 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
1074 self.with_lint_attrs(&it.attrs, |cx| {
1075 run_lints!(cx, check_foreign_item, early_passes, it);
1076 ast_visit::walk_foreign_item(cx, it);
1077 run_lints!(cx, check_foreign_item_post, early_passes, it);
1081 fn visit_pat(&mut self, p: &'a ast::Pat) {
1082 run_lints!(self, check_pat, early_passes, p);
1083 ast_visit::walk_pat(self, p);
1086 fn visit_expr(&mut self, e: &'a ast::Expr) {
1087 self.with_lint_attrs(&e.attrs, |cx| {
1088 run_lints!(cx, check_expr, early_passes, e);
1089 ast_visit::walk_expr(cx, e);
1093 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
1094 run_lints!(self, check_stmt, early_passes, s);
1095 ast_visit::walk_stmt(self, s);
1098 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
1099 span: Span, id: ast::NodeId) {
1100 run_lints!(self, check_fn, early_passes, fk, decl, span, id);
1101 ast_visit::walk_fn(self, fk, decl, span);
1102 run_lints!(self, check_fn_post, early_passes, fk, decl, span, id);
1105 fn visit_variant_data(&mut self,
1106 s: &'a ast::VariantData,
1108 g: &'a ast::Generics,
1109 item_id: ast::NodeId,
1111 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
1112 ast_visit::walk_struct_def(self, s);
1113 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
1116 fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1117 self.with_lint_attrs(&s.attrs, |cx| {
1118 run_lints!(cx, check_struct_field, early_passes, s);
1119 ast_visit::walk_struct_field(cx, s);
1123 fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1124 self.with_lint_attrs(&v.node.attrs, |cx| {
1125 run_lints!(cx, check_variant, early_passes, v, g);
1126 ast_visit::walk_variant(cx, v, g, item_id);
1127 run_lints!(cx, check_variant_post, early_passes, v, g);
1131 fn visit_ty(&mut self, t: &'a ast::Ty) {
1132 run_lints!(self, check_ty, early_passes, t);
1133 ast_visit::walk_ty(self, t);
1136 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
1137 run_lints!(self, check_ident, early_passes, sp, id);
1140 fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
1141 run_lints!(self, check_mod, early_passes, m, s, n);
1142 ast_visit::walk_mod(self, m);
1143 run_lints!(self, check_mod_post, early_passes, m, s, n);
1146 fn visit_local(&mut self, l: &'a ast::Local) {
1147 self.with_lint_attrs(&l.attrs, |cx| {
1148 run_lints!(cx, check_local, early_passes, l);
1149 ast_visit::walk_local(cx, l);
1153 fn visit_block(&mut self, b: &'a ast::Block) {
1154 run_lints!(self, check_block, early_passes, b);
1155 ast_visit::walk_block(self, b);
1156 run_lints!(self, check_block_post, early_passes, b);
1159 fn visit_arm(&mut self, a: &'a ast::Arm) {
1160 run_lints!(self, check_arm, early_passes, a);
1161 ast_visit::walk_arm(self, a);
1164 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1165 run_lints!(self, check_expr_post, early_passes, e);
1168 fn visit_generics(&mut self, g: &'a ast::Generics) {
1169 run_lints!(self, check_generics, early_passes, g);
1170 ast_visit::walk_generics(self, g);
1173 fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1174 self.with_lint_attrs(&trait_item.attrs, |cx| {
1175 run_lints!(cx, check_trait_item, early_passes, trait_item);
1176 ast_visit::walk_trait_item(cx, trait_item);
1177 run_lints!(cx, check_trait_item_post, early_passes, trait_item);
1181 fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1182 self.with_lint_attrs(&impl_item.attrs, |cx| {
1183 run_lints!(cx, check_impl_item, early_passes, impl_item);
1184 ast_visit::walk_impl_item(cx, impl_item);
1185 run_lints!(cx, check_impl_item_post, early_passes, impl_item);
1189 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1190 run_lints!(self, check_lifetime, early_passes, lt);
1193 fn visit_lifetime_def(&mut self, lt: &'a ast::LifetimeDef) {
1194 run_lints!(self, check_lifetime_def, early_passes, lt);
1197 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1198 run_lints!(self, check_path, early_passes, p, id);
1199 ast_visit::walk_path(self, p);
1202 fn visit_path_list_item(&mut self, prefix: &'a ast::Path, item: &'a ast::PathListItem) {
1203 run_lints!(self, check_path_list_item, early_passes, item);
1204 ast_visit::walk_path_list_item(self, prefix, item);
1207 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1208 run_lints!(self, check_attribute, early_passes, attr);
1211 fn visit_mac_def(&mut self, _mac: &'a ast::MacroDef, id: ast::NodeId) {
1212 let lints = self.sess.lints.borrow_mut().take(id);
1213 for early_lint in lints {
1214 self.early_lint(&early_lint);
1219 enum CheckLintNameResult {
1221 // Lint doesn't exist
1223 // The lint is either renamed or removed. This is the warning
1228 /// Checks the name of a lint for its existence, and whether it was
1229 /// renamed or removed. Generates a DiagnosticBuilder containing a
1230 /// warning for renamed and removed lints. This is over both lint
1231 /// names from attributes and those passed on the command line. Since
1232 /// it emits non-fatal warnings and there are *two* lint passes that
1233 /// inspect attributes, this is only run from the late pass to avoid
1234 /// printing duplicate warnings.
1235 fn check_lint_name(lint_cx: &LintStore,
1236 lint_name: &str) -> CheckLintNameResult {
1237 match lint_cx.by_name.get(lint_name) {
1238 Some(&Renamed(ref new_name, _)) => {
1239 CheckLintNameResult::Warning(
1240 format!("lint {} has been renamed to {}", lint_name, new_name)
1243 Some(&Removed(ref reason)) => {
1244 CheckLintNameResult::Warning(
1245 format!("lint {} has been removed: {}", lint_name, reason)
1249 match lint_cx.lint_groups.get(lint_name) {
1251 CheckLintNameResult::NoLint
1254 /* lint group exists */
1255 CheckLintNameResult::Ok
1261 CheckLintNameResult::Ok
1266 // Checks the validity of lint names derived from attributes
1267 fn check_lint_name_attribute(cx: &LateContext, attr: &ast::Attribute) {
1268 for result in gather_attr(attr) {
1271 // Malformed lint attr. Reported by with_lint_attrs
1274 Ok((lint_name, _, span)) => {
1275 match check_lint_name(&cx.lint_sess.lints, &lint_name.as_str()) {
1276 CheckLintNameResult::Ok => (),
1277 CheckLintNameResult::Warning(ref msg) => {
1278 cx.span_lint(builtin::RENAMED_AND_REMOVED_LINTS,
1281 CheckLintNameResult::NoLint => {
1282 cx.span_lint(builtin::UNKNOWN_LINTS, span,
1283 &format!("unknown lint: `{}`",
1292 // Checks the validity of lint names derived from the command line
1293 fn check_lint_name_cmdline(sess: &Session, lint_cx: &LintStore,
1294 lint_name: &str, level: Level) {
1295 let db = match check_lint_name(lint_cx, lint_name) {
1296 CheckLintNameResult::Ok => None,
1297 CheckLintNameResult::Warning(ref msg) => {
1298 Some(sess.struct_warn(msg))
1300 CheckLintNameResult::NoLint => {
1301 Some(sess.struct_err(&format!("unknown lint: `{}`", lint_name)))
1305 if let Some(mut db) = db {
1306 let msg = format!("requested on the command line with `{} {}`",
1308 Level::Allow => "-A",
1309 Level::Warn => "-W",
1310 Level::Deny => "-D",
1311 Level::Forbid => "-F",
1320 /// Perform lint checking on a crate.
1322 /// Consumes the `lint_store` field of the `Session`.
1323 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1324 let _task = tcx.dep_graph.in_task(DepNode::LateLintCheck);
1326 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1328 let krate = tcx.hir.krate();
1330 let mut cx = LateContext {
1332 tables: &ty::TypeckTables::empty(),
1334 access_levels: access_levels,
1335 lint_sess: LintSession::new(&tcx.sess.lint_store),
1338 // Visit the whole crate.
1339 cx.with_lint_attrs(&krate.attrs, |cx| {
1340 // since the root module isn't visited as an item (because it isn't an
1341 // item), warn for it here.
1342 run_lints!(cx, check_crate, late_passes, krate);
1344 hir_visit::walk_crate(cx, krate);
1346 run_lints!(cx, check_crate_post, late_passes, krate);
1349 // If we missed any lints added to the session, then there's a bug somewhere
1350 // in the iteration code.
1351 if let Some((id, v)) = tcx.sess.lints.borrow().get_any() {
1352 for early_lint in v {
1353 span_bug!(early_lint.diagnostic.span.clone(),
1354 "unprocessed lint {:?} at {}",
1355 early_lint, tcx.hir.node_to_string(*id));
1359 // Put the lint store levels and passes back in the session.
1360 cx.lint_sess.restore(&tcx.sess.lint_store);
1363 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1364 let mut cx = EarlyContext::new(sess, krate);
1366 // Visit the whole crate.
1367 cx.with_lint_attrs(&krate.attrs, |cx| {
1368 // Lints may be assigned to the whole crate.
1369 let lints = cx.sess.lints.borrow_mut().take(ast::CRATE_NODE_ID);
1370 for early_lint in lints {
1371 cx.early_lint(&early_lint);
1374 // since the root module isn't visited as an item (because it isn't an
1375 // item), warn for it here.
1376 run_lints!(cx, check_crate, early_passes, krate);
1378 ast_visit::walk_crate(cx, krate);
1380 run_lints!(cx, check_crate_post, early_passes, krate);
1383 // Put the lint store levels and passes back in the session.
1384 cx.lint_sess.restore(&sess.lint_store);
1386 // If we missed any lints added to the session, then there's a bug somewhere
1387 // in the iteration code.
1388 for (_, v) in sess.lints.borrow().get_any() {
1389 for early_lint in v {
1390 span_bug!(early_lint.diagnostic.span.clone(), "unprocessed lint {:?}", early_lint);
1395 impl Encodable for LintId {
1396 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1397 s.emit_str(&self.lint.name.to_lowercase())
1401 impl Decodable for LintId {
1403 fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1404 let s = d.read_str()?;
1405 ty::tls::with(|tcx| {
1406 match tcx.sess.lint_store.borrow().find_lint(&s, tcx.sess, None) {
1408 Err(_) => panic!("invalid lint-id `{}`", s),