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 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 fn find_lint(&self, lint_name: &str) -> Result<LintId, FindLintError> {
295 match self.by_name.get(lint_name) {
296 Some(&Id(lint_id)) => Ok(lint_id),
297 Some(&Renamed(_, lint_id)) => {
300 Some(&Removed(_)) => {
301 Err(FindLintError::Removed)
303 None => Err(FindLintError::NotFound)
307 pub fn process_command_line(&mut self, sess: &Session) {
308 for &(ref lint_name, level) in &sess.opts.lint_opts {
309 check_lint_name_cmdline(sess, self,
310 &lint_name[..], level);
312 let lint_flag_val = Symbol::intern(&lint_name);
313 match self.find_lint(&lint_name[..]) {
314 Ok(lint_id) => self.levels.set(lint_id, (level, CommandLine(lint_flag_val))),
315 Err(FindLintError::Removed) => { }
317 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
318 .collect::<FxHashMap<&'static str,
320 .get(&lint_name[..]) {
323 self.levels.set(*lint_id, (level, CommandLine(lint_flag_val)));
327 // The lint or lint group doesn't exist.
328 // This is an error, but it was handled
329 // by check_lint_name_cmdline.
336 self.levels.set_lint_cap(sess.opts.lint_cap);
342 fn get_source(&self, lint: LintId) -> LevelSource {
343 match self.levels.get(&lint) {
345 None => (Allow, Default),
349 fn set(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
350 if let Some(cap) = self.lint_cap {
351 lvlsrc.0 = cmp::min(lvlsrc.0, cap);
353 if lvlsrc.0 == Allow {
354 self.levels.remove(&lint);
356 self.levels.insert(lint, lvlsrc);
360 fn set_lint_cap(&mut self, lint_cap: Option<Level>) {
361 self.lint_cap = lint_cap;
362 if let Some(cap) = lint_cap {
363 for (_, level) in &mut self.levels {
364 level.0 = cmp::min(level.0, cap);
371 impl<'a, PassObject: LintPassObject> LintSession<'a, PassObject> {
372 /// Creates a new `LintSession`, by moving out the `LintStore`'s initial
373 /// lint levels and pass objects. These can be restored using the `restore`
375 fn new(store: &'a RefCell<LintStore>) -> LintSession<'a, PassObject> {
376 let mut s = store.borrow_mut();
377 let levels = mem::replace(&mut s.levels, LintLevels::default());
378 let passes = PassObject::take_passes(&mut *s);
381 lints: store.borrow(),
388 /// Restores the levels back to the original lint store.
389 fn restore(self, store: &RefCell<LintStore>) {
391 let mut s = store.borrow_mut();
392 s.levels = self.levels;
393 PassObject::restore_passes(&mut *s, self.passes);
396 fn get_source(&self, lint_id: LintId) -> LevelSource {
397 self.levels.get_source(lint_id)
403 /// Context for lint checking after type checking.
404 pub struct LateContext<'a, 'tcx: 'a> {
405 /// Type context we're checking in.
406 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
408 /// Side-tables for the body we are in.
409 pub tables: &'a ty::TypeckTables<'tcx>,
411 /// Parameter environment for the item we are in.
412 pub param_env: ty::ParamEnv<'tcx>,
414 /// Items accessible from the crate being checked.
415 pub access_levels: &'a AccessLevels,
417 /// The store of registered lints and the lint levels.
418 lint_sess: LintSession<'tcx, LateLintPassObject>,
421 /// Context for lint checking of the AST, after expansion, before lowering to
423 pub struct EarlyContext<'a> {
424 /// Type context we're checking in.
425 pub sess: &'a Session,
427 /// The crate being checked.
428 pub krate: &'a ast::Crate,
430 /// The store of registered lints and the lint levels.
431 lint_sess: LintSession<'a, EarlyLintPassObject>,
434 /// Convenience macro for calling a `LintPass` method on every pass in the context.
435 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
436 // Move the vector of passes out of `$cx` so that we can
437 // iterate over it mutably while passing `$cx` to the methods.
438 let mut passes = $cx.lint_sess_mut().passes.take().unwrap();
439 for obj in &mut passes {
440 obj.$f($cx, $($args),*);
442 $cx.lint_sess_mut().passes = Some(passes);
445 /// Parse the lint attributes into a vector, with `Err`s for malformed lint
446 /// attributes. Writing this as an iterator is an enormous mess.
447 // See also the hir version just below.
448 pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec<Result<(ast::Name, Level, Span), Span>> {
449 let mut out = vec![];
451 let r = gather_attr(attr);
452 out.extend(r.into_iter());
457 pub fn gather_attr(attr: &ast::Attribute) -> Vec<Result<(ast::Name, Level, Span), Span>> {
458 let mut out = vec![];
460 let level = match attr.name().and_then(|name| Level::from_str(&name.as_str())) {
465 let meta = unwrap_or!(attr.meta(), return out);
466 attr::mark_used(attr);
468 let metas = if let Some(metas) = meta.meta_item_list() {
471 out.push(Err(meta.span));
476 out.push(li.word().map_or(Err(li.span), |word| Ok((word.name(), level, word.span))));
482 /// Emit a lint as a warning or an error (or not at all)
483 /// according to `level`.
485 /// This lives outside of `Context` so it can be used by checks
486 /// in trans that run after the main lint pass is finished. Most
487 /// lints elsewhere in the compiler should call
488 /// `Session::add_lint()` instead.
489 pub fn raw_emit_lint<S: Into<MultiSpan>>(sess: &Session,
495 raw_struct_lint(sess, lints, lint, lvlsrc, span, msg).emit();
498 pub fn raw_struct_lint<'a, S>(sess: &'a Session,
504 -> DiagnosticBuilder<'a>
505 where S: Into<MultiSpan>
507 let (level, source) = lvlsrc;
509 return sess.diagnostic().struct_dummy();
512 let name = lint.name_lower();
514 // Except for possible note details, forbid behaves like deny.
515 let effective_level = if level == Forbid { Deny } else { level };
517 let mut err = match (effective_level, span) {
518 (Warn, Some(sp)) => sess.struct_span_warn(sp, &msg[..]),
519 (Warn, None) => sess.struct_warn(&msg[..]),
520 (Deny, Some(sp)) => sess.struct_span_err(sp, &msg[..]),
521 (Deny, None) => sess.struct_err(&msg[..]),
522 _ => bug!("impossible level in raw_emit_lint"),
527 sess.diag_note_once(&mut err, lint,
528 &format!("#[{}({})] on by default", level.as_str(), name));
530 CommandLine(lint_flag_val) => {
531 let flag = match level {
532 Warn => "-W", Deny => "-D", Forbid => "-F",
533 Allow => bug!("earlier conditional return should handle Allow case")
535 let hyphen_case_lint_name = name.replace("_", "-");
536 if lint_flag_val.as_str() == name {
537 sess.diag_note_once(&mut err, lint,
538 &format!("requested on the command line with `{} {}`",
539 flag, hyphen_case_lint_name));
541 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
542 sess.diag_note_once(&mut err, lint,
543 &format!("`{} {}` implied by `{} {}`",
544 flag, hyphen_case_lint_name, flag,
545 hyphen_case_flag_val));
548 Node(lint_attr_name, src) => {
549 sess.diag_span_note_once(&mut err, lint, src, "lint level defined here");
550 if lint_attr_name.as_str() != name {
551 let level_str = level.as_str();
552 sess.diag_note_once(&mut err, lint,
553 &format!("#[{}({})] implied by #[{}({})]",
554 level_str, name, level_str, lint_attr_name));
559 // Check for future incompatibility lints and issue a stronger warning.
560 if let Some(future_incompatible) = lints.future_incompatible(LintId::of(lint)) {
561 let explanation = format!("this was previously accepted by the compiler \
562 but is being phased out; \
563 it will become a hard error in a future release!");
564 let citation = format!("for more information, see {}",
565 future_incompatible.reference);
566 err.warn(&explanation);
574 pub trait LintPassObject: Sized {
575 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>>;
576 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>);
579 impl LintPassObject for EarlyLintPassObject {
580 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>> {
581 store.early_passes.take()
584 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>) {
585 store.early_passes = passes;
589 impl LintPassObject for LateLintPassObject {
590 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>> {
591 store.late_passes.take()
594 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>) {
595 store.late_passes = passes;
600 pub trait LintContext<'tcx>: Sized {
601 type PassObject: LintPassObject;
603 fn sess(&self) -> &Session;
604 fn lints(&self) -> &LintStore;
605 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject>;
606 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject>;
607 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
608 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
610 /// Get the level of `lint` at the current position of the lint
612 fn current_level(&self, lint: &'static Lint) -> Level {
613 self.lint_sess().get_source(LintId::of(lint)).0
616 fn level_src(&self, lint: &'static Lint) -> Option<LevelSource> {
617 let ref levels = self.lint_sess().levels;
618 levels.levels.get(&LintId::of(lint)).map(|ls| match ls {
620 let lint_id = LintId::of(builtin::WARNINGS);
621 let warn_src = levels.get_source(lint_id);
622 if warn_src.0 != Warn {
632 fn lookup_and_emit<S: Into<MultiSpan>>(&self,
636 let (level, src) = match self.level_src(lint) {
641 raw_emit_lint(&self.sess(), self.lints(), lint, (level, src), span, msg);
644 fn lookup<S: Into<MultiSpan>>(&self,
648 -> DiagnosticBuilder {
649 let (level, src) = match self.level_src(lint) {
650 None => return self.sess().diagnostic().struct_dummy(),
654 raw_struct_lint(&self.sess(), self.lints(), lint, (level, src), span, msg)
657 /// Emit a lint at the appropriate level, for a particular span.
658 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
659 self.lookup_and_emit(lint, Some(span), msg);
662 fn early_lint(&self, early_lint: &EarlyLint) {
663 let span = early_lint.diagnostic.span.primary_span().expect("early lint w/o primary span");
664 let mut err = self.struct_span_lint(early_lint.id.lint,
666 &early_lint.diagnostic.message());
667 err.copy_details_not_message(&early_lint.diagnostic);
671 fn struct_span_lint<S: Into<MultiSpan>>(&self,
675 -> DiagnosticBuilder {
676 self.lookup(lint, Some(span), msg)
679 /// Emit a lint and note at the appropriate level, for a particular span.
680 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
681 note_span: Span, note: &str) {
682 let mut err = self.lookup(lint, Some(span), msg);
683 if self.current_level(lint) != Level::Allow {
684 if note_span == span {
687 err.span_note(note_span, note);
693 /// Emit a lint and help at the appropriate level, for a particular span.
694 fn span_lint_help(&self, lint: &'static Lint, span: Span,
695 msg: &str, help: &str) {
696 let mut err = self.lookup(lint, Some(span), msg);
697 self.span_lint(lint, span, msg);
698 if self.current_level(lint) != Level::Allow {
699 err.span_help(span, help);
704 /// Emit a lint at the appropriate level, with no associated span.
705 fn lint(&self, lint: &'static Lint, msg: &str) {
706 self.lookup_and_emit(lint, None as Option<Span>, msg);
709 /// Merge the lints specified by any lint attributes into the
710 /// current lint context, call the provided function, then reset the
711 /// lints in effect to their previous state.
712 fn with_lint_attrs<F>(&mut self,
713 attrs: &'tcx [ast::Attribute],
715 where F: FnOnce(&mut Self),
717 // Parse all of the lint attributes, and then add them all to the
718 // current dictionary of lint information. Along the way, keep a history
719 // of what we changed so we can roll everything back after invoking the
723 for result in gather_attrs(attrs) {
724 let (is_group, lint_level_spans) = match result {
726 span_err!(self.sess(), span, E0452,
727 "malformed lint attribute");
730 Ok((lint_name, level, span)) => {
731 match self.lints().find_lint(&lint_name.as_str()) {
732 Ok(lint_id) => (false, vec![(lint_id, level, span)]),
733 Err(FindLintError::NotFound) => {
734 match self.lints().lint_groups.get(&*lint_name.as_str()) {
735 Some(&(ref v, _)) => (true,
737 .map(|lint_id: &LintId|
738 (*lint_id, level, span))
741 // The lint or lint group doesn't exist.
742 // This is an error, but it was handled
743 // by check_lint_name_attribute.
748 Err(FindLintError::Removed) => continue,
753 let lint_attr_name = result.expect("lint attribute should be well-formed").0;
755 for (lint_id, level, span) in lint_level_spans {
756 let (now, now_source) = self.lint_sess().get_source(lint_id);
757 if now == Forbid && level != Forbid {
758 let forbidden_lint_name = match now_source {
759 LintSource::Default => lint_id.to_string(),
760 LintSource::Node(name, _) => name.to_string(),
761 LintSource::CommandLine(name) => name.to_string(),
763 let mut diag_builder = struct_span_err!(self.sess(), span, E0453,
764 "{}({}) overruled by outer forbid({})",
765 level.as_str(), lint_attr_name,
766 forbidden_lint_name);
767 diag_builder.span_label(span, "overruled by previous forbid");
769 LintSource::Default => &mut diag_builder,
770 LintSource::Node(_, forbid_source_span) => {
771 diag_builder.span_label(forbid_source_span,
772 "`forbid` level set here")
774 LintSource::CommandLine(_) => {
775 diag_builder.note("`forbid` lint level was set on command line")
778 if is_group { // don't set a separate error for every lint in the group
781 } else if now != level {
782 let cx = self.lint_sess_mut();
783 cx.stack.push((lint_id, (now, now_source)));
785 cx.levels.set(lint_id, (level, Node(lint_attr_name, span)));
790 self.enter_attrs(attrs);
792 self.exit_attrs(attrs);
795 let cx = self.lint_sess_mut();
797 let (lint, lvlsrc) = cx.stack.pop().unwrap();
798 cx.levels.set(lint, lvlsrc);
804 impl<'a> EarlyContext<'a> {
805 fn new(sess: &'a Session,
806 krate: &'a ast::Crate) -> EarlyContext<'a> {
810 lint_sess: LintSession::new(&sess.lint_store),
815 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
816 type PassObject = LateLintPassObject;
818 /// Get the overall compiler `Session` object.
819 fn sess(&self) -> &Session {
823 fn lints(&self) -> &LintStore {
824 &*self.lint_sess.lints
827 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject> {
831 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject> {
835 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
836 debug!("late context: enter_attrs({:?})", attrs);
837 run_lints!(self, enter_lint_attrs, late_passes, attrs);
840 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
841 debug!("late context: exit_attrs({:?})", attrs);
842 run_lints!(self, exit_lint_attrs, late_passes, attrs);
846 impl<'a> LintContext<'a> for EarlyContext<'a> {
847 type PassObject = EarlyLintPassObject;
849 /// Get the overall compiler `Session` object.
850 fn sess(&self) -> &Session {
854 fn lints(&self) -> &LintStore {
855 &*self.lint_sess.lints
858 fn lint_sess(&self) -> &LintSession<'a, Self::PassObject> {
862 fn lint_sess_mut(&mut self) -> &mut LintSession<'a, Self::PassObject> {
866 fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
867 debug!("early context: enter_attrs({:?})", attrs);
868 run_lints!(self, enter_lint_attrs, early_passes, attrs);
871 fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
872 debug!("early context: exit_attrs({:?})", attrs);
873 run_lints!(self, exit_lint_attrs, early_passes, attrs);
877 impl<'a, 'tcx> LateContext<'a, 'tcx> {
878 fn with_param_env<F>(&mut self, id: ast::NodeId, f: F)
879 where F: FnOnce(&mut Self),
881 let old_param_env = self.param_env;
882 self.param_env = self.tcx.param_env(self.tcx.hir.local_def_id(id));
884 self.param_env = old_param_env;
888 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
889 /// Because lints are scoped lexically, we want to walk nested
890 /// items in the context of the outer item, so enable
892 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
893 hir_visit::NestedVisitorMap::All(&self.tcx.hir)
896 // Output any lints that were previously added to the session.
897 fn visit_id(&mut self, id: ast::NodeId) {
898 let lints = self.sess().lints.borrow_mut().take(id);
899 for early_lint in lints.iter().chain(self.tables.lints.get(id)) {
900 debug!("LateContext::visit_id: id={:?} early_lint={:?}", id, early_lint);
901 self.early_lint(early_lint);
905 fn visit_nested_body(&mut self, body: hir::BodyId) {
906 let old_tables = self.tables;
907 self.tables = self.tcx.body_tables(body);
908 let body = self.tcx.hir.body(body);
909 self.visit_body(body);
910 self.tables = old_tables;
913 fn visit_body(&mut self, body: &'tcx hir::Body) {
914 run_lints!(self, check_body, late_passes, body);
915 hir_visit::walk_body(self, body);
916 run_lints!(self, check_body_post, late_passes, body);
919 fn visit_item(&mut self, it: &'tcx hir::Item) {
920 self.with_lint_attrs(&it.attrs, |cx| {
921 cx.with_param_env(it.id, |cx| {
922 run_lints!(cx, check_item, late_passes, it);
923 hir_visit::walk_item(cx, it);
924 run_lints!(cx, check_item_post, late_passes, it);
929 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
930 self.with_lint_attrs(&it.attrs, |cx| {
931 cx.with_param_env(it.id, |cx| {
932 run_lints!(cx, check_foreign_item, late_passes, it);
933 hir_visit::walk_foreign_item(cx, it);
934 run_lints!(cx, check_foreign_item_post, late_passes, it);
939 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
940 run_lints!(self, check_pat, late_passes, p);
941 hir_visit::walk_pat(self, p);
944 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
945 self.with_lint_attrs(&e.attrs, |cx| {
946 run_lints!(cx, check_expr, late_passes, e);
947 hir_visit::walk_expr(cx, e);
948 run_lints!(cx, check_expr_post, late_passes, e);
952 fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
953 // statement attributes are actually just attributes on one of
957 // so we keep track of lint levels there
958 run_lints!(self, check_stmt, late_passes, s);
959 hir_visit::walk_stmt(self, s);
962 fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
963 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
964 // Wrap in tables here, not just in visit_nested_body,
965 // in order for `check_fn` to be able to use them.
966 let old_tables = self.tables;
967 self.tables = self.tcx.body_tables(body_id);
968 let body = self.tcx.hir.body(body_id);
969 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
970 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
971 run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
972 self.tables = old_tables;
975 fn visit_variant_data(&mut self,
976 s: &'tcx hir::VariantData,
978 g: &'tcx hir::Generics,
979 item_id: ast::NodeId,
981 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
982 hir_visit::walk_struct_def(self, s);
983 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
986 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
987 self.with_lint_attrs(&s.attrs, |cx| {
988 run_lints!(cx, check_struct_field, late_passes, s);
989 hir_visit::walk_struct_field(cx, s);
993 fn visit_variant(&mut self,
994 v: &'tcx hir::Variant,
995 g: &'tcx hir::Generics,
996 item_id: ast::NodeId) {
997 self.with_lint_attrs(&v.node.attrs, |cx| {
998 run_lints!(cx, check_variant, late_passes, v, g);
999 hir_visit::walk_variant(cx, v, g, item_id);
1000 run_lints!(cx, check_variant_post, late_passes, v, g);
1004 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1005 run_lints!(self, check_ty, late_passes, t);
1006 hir_visit::walk_ty(self, t);
1009 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1010 run_lints!(self, check_name, late_passes, sp, name);
1013 fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
1014 run_lints!(self, check_mod, late_passes, m, s, n);
1015 hir_visit::walk_mod(self, m, n);
1016 run_lints!(self, check_mod_post, late_passes, m, s, n);
1019 fn visit_local(&mut self, l: &'tcx hir::Local) {
1020 self.with_lint_attrs(&l.attrs, |cx| {
1021 run_lints!(cx, check_local, late_passes, l);
1022 hir_visit::walk_local(cx, l);
1026 fn visit_block(&mut self, b: &'tcx hir::Block) {
1027 run_lints!(self, check_block, late_passes, b);
1028 hir_visit::walk_block(self, b);
1029 run_lints!(self, check_block_post, late_passes, b);
1032 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
1033 run_lints!(self, check_arm, late_passes, a);
1034 hir_visit::walk_arm(self, a);
1037 fn visit_decl(&mut self, d: &'tcx hir::Decl) {
1038 run_lints!(self, check_decl, late_passes, d);
1039 hir_visit::walk_decl(self, d);
1042 fn visit_generics(&mut self, g: &'tcx hir::Generics) {
1043 run_lints!(self, check_generics, late_passes, g);
1044 hir_visit::walk_generics(self, g);
1047 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
1048 self.with_lint_attrs(&trait_item.attrs, |cx| {
1049 cx.with_param_env(trait_item.id, |cx| {
1050 run_lints!(cx, check_trait_item, late_passes, trait_item);
1051 hir_visit::walk_trait_item(cx, trait_item);
1052 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
1057 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
1058 self.with_lint_attrs(&impl_item.attrs, |cx| {
1059 cx.with_param_env(impl_item.id, |cx| {
1060 run_lints!(cx, check_impl_item, late_passes, impl_item);
1061 hir_visit::walk_impl_item(cx, impl_item);
1062 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
1067 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1068 run_lints!(self, check_lifetime, late_passes, lt);
1069 hir_visit::walk_lifetime(self, lt);
1072 fn visit_lifetime_def(&mut self, lt: &'tcx hir::LifetimeDef) {
1073 run_lints!(self, check_lifetime_def, late_passes, lt);
1074 hir_visit::walk_lifetime_def(self, lt);
1077 fn visit_path(&mut self, p: &'tcx hir::Path, id: ast::NodeId) {
1078 run_lints!(self, check_path, late_passes, p, id);
1079 hir_visit::walk_path(self, p);
1082 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
1083 check_lint_name_attribute(self, attr);
1084 run_lints!(self, check_attribute, late_passes, attr);
1088 impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> {
1089 fn visit_item(&mut self, it: &'a ast::Item) {
1090 self.with_lint_attrs(&it.attrs, |cx| {
1091 run_lints!(cx, check_item, early_passes, it);
1092 ast_visit::walk_item(cx, it);
1093 run_lints!(cx, check_item_post, early_passes, it);
1097 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
1098 self.with_lint_attrs(&it.attrs, |cx| {
1099 run_lints!(cx, check_foreign_item, early_passes, it);
1100 ast_visit::walk_foreign_item(cx, it);
1101 run_lints!(cx, check_foreign_item_post, early_passes, it);
1105 fn visit_pat(&mut self, p: &'a ast::Pat) {
1106 run_lints!(self, check_pat, early_passes, p);
1107 ast_visit::walk_pat(self, p);
1110 fn visit_expr(&mut self, e: &'a ast::Expr) {
1111 self.with_lint_attrs(&e.attrs, |cx| {
1112 run_lints!(cx, check_expr, early_passes, e);
1113 ast_visit::walk_expr(cx, e);
1117 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
1118 run_lints!(self, check_stmt, early_passes, s);
1119 ast_visit::walk_stmt(self, s);
1122 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
1123 span: Span, id: ast::NodeId) {
1124 run_lints!(self, check_fn, early_passes, fk, decl, span, id);
1125 ast_visit::walk_fn(self, fk, decl, span);
1126 run_lints!(self, check_fn_post, early_passes, fk, decl, span, id);
1129 fn visit_variant_data(&mut self,
1130 s: &'a ast::VariantData,
1132 g: &'a ast::Generics,
1133 item_id: ast::NodeId,
1135 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
1136 ast_visit::walk_struct_def(self, s);
1137 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
1140 fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1141 self.with_lint_attrs(&s.attrs, |cx| {
1142 run_lints!(cx, check_struct_field, early_passes, s);
1143 ast_visit::walk_struct_field(cx, s);
1147 fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1148 self.with_lint_attrs(&v.node.attrs, |cx| {
1149 run_lints!(cx, check_variant, early_passes, v, g);
1150 ast_visit::walk_variant(cx, v, g, item_id);
1151 run_lints!(cx, check_variant_post, early_passes, v, g);
1155 fn visit_ty(&mut self, t: &'a ast::Ty) {
1156 run_lints!(self, check_ty, early_passes, t);
1157 ast_visit::walk_ty(self, t);
1160 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
1161 run_lints!(self, check_ident, early_passes, sp, id);
1164 fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
1165 run_lints!(self, check_mod, early_passes, m, s, n);
1166 ast_visit::walk_mod(self, m);
1167 run_lints!(self, check_mod_post, early_passes, m, s, n);
1170 fn visit_local(&mut self, l: &'a ast::Local) {
1171 self.with_lint_attrs(&l.attrs, |cx| {
1172 run_lints!(cx, check_local, early_passes, l);
1173 ast_visit::walk_local(cx, l);
1177 fn visit_block(&mut self, b: &'a ast::Block) {
1178 run_lints!(self, check_block, early_passes, b);
1179 ast_visit::walk_block(self, b);
1180 run_lints!(self, check_block_post, early_passes, b);
1183 fn visit_arm(&mut self, a: &'a ast::Arm) {
1184 run_lints!(self, check_arm, early_passes, a);
1185 ast_visit::walk_arm(self, a);
1188 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1189 run_lints!(self, check_expr_post, early_passes, e);
1192 fn visit_generics(&mut self, g: &'a ast::Generics) {
1193 run_lints!(self, check_generics, early_passes, g);
1194 ast_visit::walk_generics(self, g);
1197 fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1198 self.with_lint_attrs(&trait_item.attrs, |cx| {
1199 run_lints!(cx, check_trait_item, early_passes, trait_item);
1200 ast_visit::walk_trait_item(cx, trait_item);
1201 run_lints!(cx, check_trait_item_post, early_passes, trait_item);
1205 fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1206 self.with_lint_attrs(&impl_item.attrs, |cx| {
1207 run_lints!(cx, check_impl_item, early_passes, impl_item);
1208 ast_visit::walk_impl_item(cx, impl_item);
1209 run_lints!(cx, check_impl_item_post, early_passes, impl_item);
1213 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1214 run_lints!(self, check_lifetime, early_passes, lt);
1217 fn visit_lifetime_def(&mut self, lt: &'a ast::LifetimeDef) {
1218 run_lints!(self, check_lifetime_def, early_passes, lt);
1221 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1222 run_lints!(self, check_path, early_passes, p, id);
1223 ast_visit::walk_path(self, p);
1226 fn visit_path_list_item(&mut self, prefix: &'a ast::Path, item: &'a ast::PathListItem) {
1227 run_lints!(self, check_path_list_item, early_passes, item);
1228 ast_visit::walk_path_list_item(self, prefix, item);
1231 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1232 run_lints!(self, check_attribute, early_passes, attr);
1235 fn visit_mac_def(&mut self, _mac: &'a ast::MacroDef, id: ast::NodeId) {
1236 let lints = self.sess.lints.borrow_mut().take(id);
1237 for early_lint in lints {
1238 self.early_lint(&early_lint);
1243 enum CheckLintNameResult {
1245 // Lint doesn't exist
1247 // The lint is either renamed or removed. This is the warning
1252 /// Checks the name of a lint for its existence, and whether it was
1253 /// renamed or removed. Generates a DiagnosticBuilder containing a
1254 /// warning for renamed and removed lints. This is over both lint
1255 /// names from attributes and those passed on the command line. Since
1256 /// it emits non-fatal warnings and there are *two* lint passes that
1257 /// inspect attributes, this is only run from the late pass to avoid
1258 /// printing duplicate warnings.
1259 fn check_lint_name(lint_cx: &LintStore,
1260 lint_name: &str) -> CheckLintNameResult {
1261 match lint_cx.by_name.get(lint_name) {
1262 Some(&Renamed(ref new_name, _)) => {
1263 CheckLintNameResult::Warning(
1264 format!("lint {} has been renamed to {}", lint_name, new_name)
1267 Some(&Removed(ref reason)) => {
1268 CheckLintNameResult::Warning(
1269 format!("lint {} has been removed: {}", lint_name, reason)
1273 match lint_cx.lint_groups.get(lint_name) {
1275 CheckLintNameResult::NoLint
1278 /* lint group exists */
1279 CheckLintNameResult::Ok
1285 CheckLintNameResult::Ok
1290 // Checks the validity of lint names derived from attributes
1291 fn check_lint_name_attribute(cx: &LateContext, attr: &ast::Attribute) {
1292 for result in gather_attr(attr) {
1295 // Malformed lint attr. Reported by with_lint_attrs
1298 Ok((lint_name, _, span)) => {
1299 match check_lint_name(&cx.lint_sess.lints, &lint_name.as_str()) {
1300 CheckLintNameResult::Ok => (),
1301 CheckLintNameResult::Warning(ref msg) => {
1302 cx.span_lint(builtin::RENAMED_AND_REMOVED_LINTS,
1305 CheckLintNameResult::NoLint => {
1306 cx.span_lint(builtin::UNKNOWN_LINTS, span,
1307 &format!("unknown lint: `{}`",
1316 // Checks the validity of lint names derived from the command line
1317 fn check_lint_name_cmdline(sess: &Session, lint_cx: &LintStore,
1318 lint_name: &str, level: Level) {
1319 let db = match check_lint_name(lint_cx, lint_name) {
1320 CheckLintNameResult::Ok => None,
1321 CheckLintNameResult::Warning(ref msg) => {
1322 Some(sess.struct_warn(msg))
1324 CheckLintNameResult::NoLint => {
1325 Some(struct_err!(sess, E0602, "unknown lint: `{}`", lint_name))
1329 if let Some(mut db) = db {
1330 let msg = format!("requested on the command line with `{} {}`",
1332 Level::Allow => "-A",
1333 Level::Warn => "-W",
1334 Level::Deny => "-D",
1335 Level::Forbid => "-F",
1344 /// Perform lint checking on a crate.
1346 /// Consumes the `lint_store` field of the `Session`.
1347 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1348 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1350 let krate = tcx.hir.krate();
1352 let mut cx = LateContext {
1354 tables: &ty::TypeckTables::empty(),
1355 param_env: ty::ParamEnv::empty(Reveal::UserFacing),
1356 access_levels: access_levels,
1357 lint_sess: LintSession::new(&tcx.sess.lint_store),
1360 // Visit the whole crate.
1361 cx.with_lint_attrs(&krate.attrs, |cx| {
1362 // since the root module isn't visited as an item (because it isn't an
1363 // item), warn for it here.
1364 run_lints!(cx, check_crate, late_passes, krate);
1366 hir_visit::walk_crate(cx, krate);
1368 run_lints!(cx, check_crate_post, late_passes, krate);
1371 // If we missed any lints added to the session, then there's a bug somewhere
1372 // in the iteration code.
1373 if let Some((id, v)) = tcx.sess.lints.borrow().get_any() {
1374 for early_lint in v {
1375 span_bug!(early_lint.diagnostic.span.clone(),
1376 "unprocessed lint {:?} at {}",
1377 early_lint, tcx.hir.node_to_string(*id));
1381 // Put the lint store levels and passes back in the session.
1382 cx.lint_sess.restore(&tcx.sess.lint_store);
1385 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1386 let mut cx = EarlyContext::new(sess, krate);
1388 // Visit the whole crate.
1389 cx.with_lint_attrs(&krate.attrs, |cx| {
1390 // Lints may be assigned to the whole crate.
1391 let lints = cx.sess.lints.borrow_mut().take(ast::CRATE_NODE_ID);
1392 for early_lint in lints {
1393 cx.early_lint(&early_lint);
1396 // since the root module isn't visited as an item (because it isn't an
1397 // item), warn for it here.
1398 run_lints!(cx, check_crate, early_passes, krate);
1400 ast_visit::walk_crate(cx, krate);
1402 run_lints!(cx, check_crate_post, early_passes, krate);
1405 // Put the lint store levels and passes back in the session.
1406 cx.lint_sess.restore(&sess.lint_store);
1408 // If we missed any lints added to the session, then there's a bug somewhere
1409 // in the iteration code.
1410 for (_, v) in sess.lints.borrow().get_any() {
1411 for early_lint in v {
1412 span_bug!(early_lint.diagnostic.span.clone(), "unprocessed lint {:?}", early_lint);
1417 impl Encodable for LintId {
1418 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1419 s.emit_str(&self.lint.name.to_lowercase())
1423 impl Decodable for LintId {
1425 fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1426 let s = d.read_str()?;
1427 ty::tls::with(|tcx| {
1428 match tcx.sess.lint_store.borrow().find_lint(&s) {
1430 Err(_) => panic!("invalid lint-id `{}`", s),