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.
27 use self::TargetLint::*;
30 use lint::{EarlyLintPassObject, LateLintPassObject};
31 use lint::{Level, Lint, LintId, LintPass, LintBuffer};
32 use lint::levels::{LintLevelSets, LintLevelsBuilder};
33 use middle::privacy::AccessLevels;
34 use rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
35 use session::{config, early_error, Session};
37 use ty::{self, TyCtxt, Ty};
38 use ty::layout::{LayoutError, LayoutOf, TyLayout};
39 use util::nodemap::FxHashMap;
41 use std::default::Default as StdDefault;
42 use std::cell::{Ref, RefCell};
44 use syntax_pos::{MultiSpan, Span};
45 use errors::DiagnosticBuilder;
47 use hir::def_id::LOCAL_CRATE;
48 use hir::intravisit as hir_visit;
49 use syntax::visit as ast_visit;
51 /// Information about the registered lints.
53 /// This is basically the subset of `Context` that we can
54 /// build early in the compile pipeline.
55 pub struct LintStore {
56 /// Registered lints. The bool is true if the lint was
57 /// added by a plugin.
58 lints: Vec<(&'static Lint, bool)>,
60 /// Trait objects for each lint pass.
61 /// This is only `None` while performing a lint pass. See the definition
62 /// of `LintSession::new`.
63 early_passes: Option<Vec<EarlyLintPassObject>>,
64 late_passes: Option<Vec<LateLintPassObject>>,
66 /// Lints indexed by name.
67 by_name: FxHashMap<String, TargetLint>,
69 /// Map of registered lint groups to what lints they expand to. The bool
70 /// is true if the lint group was added by a plugin.
71 lint_groups: FxHashMap<&'static str, (Vec<LintId>, bool)>,
73 /// Extra info for future incompatibility lints, describing the
74 /// issue or RFC that caused the incompatibility.
75 future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
78 pub struct LintSession<'a, PassObject> {
79 /// Reference to the store of registered lints.
80 lints: Ref<'a, LintStore>,
82 /// Trait objects for each lint pass.
83 passes: Option<Vec<PassObject>>,
87 /// Lints that are buffered up early on in the `Session` before the
88 /// `LintLevels` is calculated
89 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
90 pub struct BufferedEarlyLint {
92 pub ast_id: ast::NodeId,
97 /// Extra information for a future incompatibility lint. See the call
98 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
100 pub struct FutureIncompatibleInfo {
102 pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
105 /// The target of the `by_name` map, which accounts for renaming/deprecation.
107 /// A direct lint target
110 /// Temporary renaming, used for easing migration pain; see #16545
111 Renamed(String, LintId),
113 /// Lint with this name existed previously, but has been removed/deprecated.
114 /// The string argument is the reason for removal.
118 pub enum FindLintError {
123 pub enum CheckLintNameResult<'a> {
125 /// Lint doesn't exist
127 /// The lint is either renamed or removed. This is the warning
133 pub fn new() -> LintStore {
136 early_passes: Some(vec![]),
137 late_passes: Some(vec![]),
138 by_name: FxHashMap(),
139 future_incompatible: FxHashMap(),
140 lint_groups: FxHashMap(),
144 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
148 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
149 self.lint_groups.iter().map(|(k, v)| (*k,
154 pub fn register_early_pass(&mut self,
155 sess: Option<&Session>,
157 pass: EarlyLintPassObject) {
158 self.push_pass(sess, from_plugin, &pass);
159 self.early_passes.as_mut().unwrap().push(pass);
162 pub fn register_late_pass(&mut self,
163 sess: Option<&Session>,
165 pass: LateLintPassObject) {
166 self.push_pass(sess, from_plugin, &pass);
167 self.late_passes.as_mut().unwrap().push(pass);
170 // Helper method for register_early/late_pass
171 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
172 sess: Option<&Session>,
175 for &lint in pass.get_lints() {
176 self.lints.push((*lint, from_plugin));
178 let id = LintId::of(*lint);
179 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
180 let msg = format!("duplicate specification of lint {}", lint.name_lower());
181 match (sess, from_plugin) {
182 // We load builtin lints first, so a duplicate is a compiler bug.
183 // Use early_error when handling -W help with no crate.
184 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
185 (Some(_), false) => bug!("{}", msg),
187 // A duplicate name from a plugin is a user error.
188 (Some(sess), true) => sess.err(&msg[..]),
194 pub fn register_future_incompatible(&mut self,
195 sess: Option<&Session>,
196 lints: Vec<FutureIncompatibleInfo>) {
197 let ids = lints.iter().map(|f| f.id).collect();
198 self.register_group(sess, false, "future_incompatible", ids);
200 self.future_incompatible.insert(info.id, info);
204 pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
205 self.future_incompatible.get(&id)
208 pub fn register_group(&mut self, sess: Option<&Session>,
209 from_plugin: bool, name: &'static str,
211 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
214 let msg = format!("duplicate specification of lint group {}", name);
215 match (sess, from_plugin) {
216 // We load builtin lints first, so a duplicate is a compiler bug.
217 // Use early_error when handling -W help with no crate.
218 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
219 (Some(_), false) => bug!("{}", msg),
221 // A duplicate name from a plugin is a user error.
222 (Some(sess), true) => sess.err(&msg[..]),
227 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
228 let target = match self.by_name.get(new_name) {
229 Some(&Id(lint_id)) => lint_id.clone(),
230 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
232 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
235 pub fn register_removed(&mut self, name: &str, reason: &str) {
236 self.by_name.insert(name.into(), Removed(reason.into()));
239 pub fn find_lints(&self, lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
240 match self.by_name.get(lint_name) {
241 Some(&Id(lint_id)) => Ok(vec![lint_id]),
242 Some(&Renamed(_, lint_id)) => {
245 Some(&Removed(_)) => {
246 Err(FindLintError::Removed)
249 match self.lint_groups.get(lint_name) {
250 Some(v) => Ok(v.0.clone()),
251 None => Err(FindLintError::Removed)
257 /// Checks the validity of lint names derived from the command line
258 pub fn check_lint_name_cmdline(&self,
262 let db = match self.check_lint_name(lint_name) {
263 CheckLintNameResult::Ok(_) => None,
264 CheckLintNameResult::Warning(ref msg) => {
265 Some(sess.struct_warn(msg))
267 CheckLintNameResult::NoLint => {
268 Some(struct_err!(sess, E0602, "unknown lint: `{}`", lint_name))
272 if let Some(mut db) = db {
273 let msg = format!("requested on the command line with `{} {}`",
275 Level::Allow => "-A",
278 Level::Forbid => "-F",
286 /// Checks the name of a lint for its existence, and whether it was
287 /// renamed or removed. Generates a DiagnosticBuilder containing a
288 /// warning for renamed and removed lints. This is over both lint
289 /// names from attributes and those passed on the command line. Since
290 /// it emits non-fatal warnings and there are *two* lint passes that
291 /// inspect attributes, this is only run from the late pass to avoid
292 /// printing duplicate warnings.
293 pub fn check_lint_name(&self, lint_name: &str) -> CheckLintNameResult {
294 match self.by_name.get(lint_name) {
295 Some(&Renamed(ref new_name, _)) => {
296 CheckLintNameResult::Warning(
297 format!("lint {} has been renamed to {}", lint_name, new_name)
300 Some(&Removed(ref reason)) => {
301 CheckLintNameResult::Warning(
302 format!("lint {} has been removed: {}", lint_name, reason)
306 match self.lint_groups.get(lint_name) {
307 None => CheckLintNameResult::NoLint,
308 Some(ids) => CheckLintNameResult::Ok(&ids.0),
311 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
316 impl<'a, PassObject: LintPassObject> LintSession<'a, PassObject> {
317 /// Creates a new `LintSession`, by moving out the `LintStore`'s initial
318 /// lint levels and pass objects. These can be restored using the `restore`
320 fn new(store: &'a RefCell<LintStore>) -> LintSession<'a, PassObject> {
321 let mut s = store.borrow_mut();
322 let passes = PassObject::take_passes(&mut *s);
325 lints: store.borrow(),
330 /// Restores the levels back to the original lint store.
331 fn restore(self, store: &RefCell<LintStore>) {
333 let mut s = store.borrow_mut();
334 PassObject::restore_passes(&mut *s, self.passes);
338 /// Context for lint checking after type checking.
339 pub struct LateContext<'a, 'tcx: 'a> {
340 /// Type context we're checking in.
341 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
343 /// Side-tables for the body we are in.
344 pub tables: &'a ty::TypeckTables<'tcx>,
346 /// Parameter environment for the item we are in.
347 pub param_env: ty::ParamEnv<'tcx>,
349 /// Items accessible from the crate being checked.
350 pub access_levels: &'a AccessLevels,
352 /// The store of registered lints and the lint levels.
353 lint_sess: LintSession<'tcx, LateLintPassObject>,
355 last_ast_node_with_lint_attrs: ast::NodeId,
357 /// Generic type parameters in scope for the item we are in.
358 pub generics: Option<&'tcx hir::Generics>,
361 /// Context for lint checking of the AST, after expansion, before lowering to
363 pub struct EarlyContext<'a> {
364 /// Type context we're checking in.
365 pub sess: &'a Session,
367 /// The crate being checked.
368 pub krate: &'a ast::Crate,
370 builder: LintLevelsBuilder<'a>,
372 /// The store of registered lints and the lint levels.
373 lint_sess: LintSession<'a, EarlyLintPassObject>,
375 buffered: LintBuffer,
378 /// Convenience macro for calling a `LintPass` method on every pass in the context.
379 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
380 // Move the vector of passes out of `$cx` so that we can
381 // iterate over it mutably while passing `$cx` to the methods.
382 let mut passes = $cx.lint_sess_mut().passes.take().unwrap();
383 for obj in &mut passes {
384 obj.$f($cx, $($args),*);
386 $cx.lint_sess_mut().passes = Some(passes);
389 pub trait LintPassObject: Sized {
390 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>>;
391 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>);
394 impl LintPassObject for EarlyLintPassObject {
395 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>> {
396 store.early_passes.take()
399 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>) {
400 store.early_passes = passes;
404 impl LintPassObject for LateLintPassObject {
405 fn take_passes(store: &mut LintStore) -> Option<Vec<Self>> {
406 store.late_passes.take()
409 fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>) {
410 store.late_passes = passes;
415 pub trait LintContext<'tcx>: Sized {
416 type PassObject: LintPassObject;
418 fn sess(&self) -> &Session;
419 fn lints(&self) -> &LintStore;
420 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject>;
421 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject>;
422 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
423 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
425 fn lookup_and_emit<S: Into<MultiSpan>>(&self,
429 self.lookup(lint, span, msg).emit();
432 fn lookup<S: Into<MultiSpan>>(&self,
436 -> DiagnosticBuilder;
438 /// Emit a lint at the appropriate level, for a particular span.
439 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
440 self.lookup_and_emit(lint, Some(span), msg);
443 fn struct_span_lint<S: Into<MultiSpan>>(&self,
447 -> DiagnosticBuilder {
448 self.lookup(lint, Some(span), msg)
451 /// Emit a lint and note at the appropriate level, for a particular span.
452 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
453 note_span: Span, note: &str) {
454 let mut err = self.lookup(lint, Some(span), msg);
455 if note_span == span {
458 err.span_note(note_span, note);
463 /// Emit a lint and help at the appropriate level, for a particular span.
464 fn span_lint_help(&self, lint: &'static Lint, span: Span,
465 msg: &str, help: &str) {
466 let mut err = self.lookup(lint, Some(span), msg);
467 self.span_lint(lint, span, msg);
468 err.span_help(span, help);
472 /// Emit a lint at the appropriate level, with no associated span.
473 fn lint(&self, lint: &'static Lint, msg: &str) {
474 self.lookup_and_emit(lint, None as Option<Span>, msg);
477 /// Merge the lints specified by any lint attributes into the
478 /// current lint context, call the provided function, then reset the
479 /// lints in effect to their previous state.
480 fn with_lint_attrs<F>(&mut self,
482 attrs: &'tcx [ast::Attribute],
484 where F: FnOnce(&mut Self);
488 impl<'a> EarlyContext<'a> {
489 fn new(sess: &'a Session,
490 krate: &'a ast::Crate) -> EarlyContext<'a> {
494 lint_sess: LintSession::new(&sess.lint_store),
495 builder: LintLevelSets::builder(sess),
496 buffered: sess.buffered_lints.borrow_mut().take().unwrap(),
500 fn check_id(&mut self, id: ast::NodeId) {
501 for early_lint in self.buffered.take(id) {
502 self.lookup_and_emit(early_lint.lint_id.lint,
503 Some(early_lint.span.clone()),
509 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
510 type PassObject = LateLintPassObject;
512 /// Get the overall compiler `Session` object.
513 fn sess(&self) -> &Session {
517 fn lints(&self) -> &LintStore {
518 &*self.lint_sess.lints
521 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject> {
525 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject> {
529 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
530 debug!("late context: enter_attrs({:?})", attrs);
531 run_lints!(self, enter_lint_attrs, late_passes, attrs);
534 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
535 debug!("late context: exit_attrs({:?})", attrs);
536 run_lints!(self, exit_lint_attrs, late_passes, attrs);
539 fn lookup<S: Into<MultiSpan>>(&self,
543 -> DiagnosticBuilder {
544 let id = self.last_ast_node_with_lint_attrs;
546 Some(s) => self.tcx.struct_span_lint_node(lint, id, s, msg),
547 None => self.tcx.struct_lint_node(lint, id, msg),
551 fn with_lint_attrs<F>(&mut self,
553 attrs: &'tcx [ast::Attribute],
555 where F: FnOnce(&mut Self)
557 let prev = self.last_ast_node_with_lint_attrs;
558 self.last_ast_node_with_lint_attrs = id;
559 self.enter_attrs(attrs);
561 self.exit_attrs(attrs);
562 self.last_ast_node_with_lint_attrs = prev;
566 impl<'a> LintContext<'a> for EarlyContext<'a> {
567 type PassObject = EarlyLintPassObject;
569 /// Get the overall compiler `Session` object.
570 fn sess(&self) -> &Session {
574 fn lints(&self) -> &LintStore {
575 &*self.lint_sess.lints
578 fn lint_sess(&self) -> &LintSession<'a, Self::PassObject> {
582 fn lint_sess_mut(&mut self) -> &mut LintSession<'a, Self::PassObject> {
586 fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
587 debug!("early context: enter_attrs({:?})", attrs);
588 run_lints!(self, enter_lint_attrs, early_passes, attrs);
591 fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
592 debug!("early context: exit_attrs({:?})", attrs);
593 run_lints!(self, exit_lint_attrs, early_passes, attrs);
596 fn lookup<S: Into<MultiSpan>>(&self,
600 -> DiagnosticBuilder {
601 self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
604 fn with_lint_attrs<F>(&mut self,
606 attrs: &'a [ast::Attribute],
608 where F: FnOnce(&mut Self)
610 let push = self.builder.push(attrs);
612 self.enter_attrs(attrs);
614 self.exit_attrs(attrs);
615 self.builder.pop(push);
619 impl<'a, 'tcx> LateContext<'a, 'tcx> {
620 fn with_param_env<F>(&mut self, id: ast::NodeId, f: F)
621 where F: FnOnce(&mut Self),
623 let old_param_env = self.param_env;
624 self.param_env = self.tcx.param_env(self.tcx.hir.local_def_id(id));
626 self.param_env = old_param_env;
630 impl<'a, 'tcx> LayoutOf<Ty<'tcx>> for &'a LateContext<'a, 'tcx> {
631 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
633 fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
634 (self.tcx, self.param_env.reveal_all()).layout_of(ty)
638 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
639 /// Because lints are scoped lexically, we want to walk nested
640 /// items in the context of the outer item, so enable
642 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
643 hir_visit::NestedVisitorMap::All(&self.tcx.hir)
646 fn visit_nested_body(&mut self, body: hir::BodyId) {
647 let old_tables = self.tables;
648 self.tables = self.tcx.body_tables(body);
649 let body = self.tcx.hir.body(body);
650 self.visit_body(body);
651 self.tables = old_tables;
654 fn visit_body(&mut self, body: &'tcx hir::Body) {
655 run_lints!(self, check_body, late_passes, body);
656 hir_visit::walk_body(self, body);
657 run_lints!(self, check_body_post, late_passes, body);
660 fn visit_item(&mut self, it: &'tcx hir::Item) {
661 let generics = self.generics.take();
662 self.generics = it.node.generics();
663 self.with_lint_attrs(it.id, &it.attrs, |cx| {
664 cx.with_param_env(it.id, |cx| {
665 run_lints!(cx, check_item, late_passes, it);
666 hir_visit::walk_item(cx, it);
667 run_lints!(cx, check_item_post, late_passes, it);
670 self.generics = generics;
673 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
674 self.with_lint_attrs(it.id, &it.attrs, |cx| {
675 cx.with_param_env(it.id, |cx| {
676 run_lints!(cx, check_foreign_item, late_passes, it);
677 hir_visit::walk_foreign_item(cx, it);
678 run_lints!(cx, check_foreign_item_post, late_passes, it);
683 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
684 run_lints!(self, check_pat, late_passes, p);
685 hir_visit::walk_pat(self, p);
688 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
689 self.with_lint_attrs(e.id, &e.attrs, |cx| {
690 run_lints!(cx, check_expr, late_passes, e);
691 hir_visit::walk_expr(cx, e);
692 run_lints!(cx, check_expr_post, late_passes, e);
696 fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
697 // statement attributes are actually just attributes on one of
701 // so we keep track of lint levels there
702 run_lints!(self, check_stmt, late_passes, s);
703 hir_visit::walk_stmt(self, s);
706 fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
707 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
708 // Wrap in tables here, not just in visit_nested_body,
709 // in order for `check_fn` to be able to use them.
710 let old_tables = self.tables;
711 self.tables = self.tcx.body_tables(body_id);
712 let body = self.tcx.hir.body(body_id);
713 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
714 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
715 run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
716 self.tables = old_tables;
719 fn visit_variant_data(&mut self,
720 s: &'tcx hir::VariantData,
722 g: &'tcx hir::Generics,
723 item_id: ast::NodeId,
725 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
726 hir_visit::walk_struct_def(self, s);
727 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
730 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
731 self.with_lint_attrs(s.id, &s.attrs, |cx| {
732 run_lints!(cx, check_struct_field, late_passes, s);
733 hir_visit::walk_struct_field(cx, s);
737 fn visit_variant(&mut self,
738 v: &'tcx hir::Variant,
739 g: &'tcx hir::Generics,
740 item_id: ast::NodeId) {
741 self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |cx| {
742 run_lints!(cx, check_variant, late_passes, v, g);
743 hir_visit::walk_variant(cx, v, g, item_id);
744 run_lints!(cx, check_variant_post, late_passes, v, g);
748 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
749 run_lints!(self, check_ty, late_passes, t);
750 hir_visit::walk_ty(self, t);
753 fn visit_name(&mut self, sp: Span, name: ast::Name) {
754 run_lints!(self, check_name, late_passes, sp, name);
757 fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
758 run_lints!(self, check_mod, late_passes, m, s, n);
759 hir_visit::walk_mod(self, m, n);
760 run_lints!(self, check_mod_post, late_passes, m, s, n);
763 fn visit_local(&mut self, l: &'tcx hir::Local) {
764 self.with_lint_attrs(l.id, &l.attrs, |cx| {
765 run_lints!(cx, check_local, late_passes, l);
766 hir_visit::walk_local(cx, l);
770 fn visit_block(&mut self, b: &'tcx hir::Block) {
771 run_lints!(self, check_block, late_passes, b);
772 hir_visit::walk_block(self, b);
773 run_lints!(self, check_block_post, late_passes, b);
776 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
777 run_lints!(self, check_arm, late_passes, a);
778 hir_visit::walk_arm(self, a);
781 fn visit_decl(&mut self, d: &'tcx hir::Decl) {
782 run_lints!(self, check_decl, late_passes, d);
783 hir_visit::walk_decl(self, d);
786 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam) {
787 run_lints!(self, check_generic_param, late_passes, p);
788 hir_visit::walk_generic_param(self, p);
791 fn visit_generics(&mut self, g: &'tcx hir::Generics) {
792 run_lints!(self, check_generics, late_passes, g);
793 hir_visit::walk_generics(self, g);
796 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
797 let generics = self.generics.take();
798 self.generics = Some(&trait_item.generics);
799 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
800 cx.with_param_env(trait_item.id, |cx| {
801 run_lints!(cx, check_trait_item, late_passes, trait_item);
802 hir_visit::walk_trait_item(cx, trait_item);
803 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
806 self.generics = generics;
809 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
810 let generics = self.generics.take();
811 self.generics = Some(&impl_item.generics);
812 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
813 cx.with_param_env(impl_item.id, |cx| {
814 run_lints!(cx, check_impl_item, late_passes, impl_item);
815 hir_visit::walk_impl_item(cx, impl_item);
816 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
819 self.generics = generics;
822 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
823 run_lints!(self, check_lifetime, late_passes, lt);
824 hir_visit::walk_lifetime(self, lt);
827 fn visit_path(&mut self, p: &'tcx hir::Path, id: ast::NodeId) {
828 run_lints!(self, check_path, late_passes, p, id);
829 hir_visit::walk_path(self, p);
832 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
833 run_lints!(self, check_attribute, late_passes, attr);
837 impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> {
838 fn visit_item(&mut self, it: &'a ast::Item) {
839 self.with_lint_attrs(it.id, &it.attrs, |cx| {
840 run_lints!(cx, check_item, early_passes, it);
841 ast_visit::walk_item(cx, it);
842 run_lints!(cx, check_item_post, early_passes, it);
846 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
847 self.with_lint_attrs(it.id, &it.attrs, |cx| {
848 run_lints!(cx, check_foreign_item, early_passes, it);
849 ast_visit::walk_foreign_item(cx, it);
850 run_lints!(cx, check_foreign_item_post, early_passes, it);
854 fn visit_pat(&mut self, p: &'a ast::Pat) {
855 run_lints!(self, check_pat, early_passes, p);
857 ast_visit::walk_pat(self, p);
860 fn visit_expr(&mut self, e: &'a ast::Expr) {
861 self.with_lint_attrs(e.id, &e.attrs, |cx| {
862 run_lints!(cx, check_expr, early_passes, e);
863 ast_visit::walk_expr(cx, e);
867 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
868 run_lints!(self, check_stmt, early_passes, s);
870 ast_visit::walk_stmt(self, s);
873 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
874 span: Span, id: ast::NodeId) {
875 run_lints!(self, check_fn, early_passes, fk, decl, span, id);
877 ast_visit::walk_fn(self, fk, decl, span);
878 run_lints!(self, check_fn_post, early_passes, fk, decl, span, id);
881 fn visit_variant_data(&mut self,
882 s: &'a ast::VariantData,
884 g: &'a ast::Generics,
885 item_id: ast::NodeId,
887 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
888 self.check_id(s.id());
889 ast_visit::walk_struct_def(self, s);
890 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
893 fn visit_struct_field(&mut self, s: &'a ast::StructField) {
894 self.with_lint_attrs(s.id, &s.attrs, |cx| {
895 run_lints!(cx, check_struct_field, early_passes, s);
896 ast_visit::walk_struct_field(cx, s);
900 fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
901 self.with_lint_attrs(item_id, &v.node.attrs, |cx| {
902 run_lints!(cx, check_variant, early_passes, v, g);
903 ast_visit::walk_variant(cx, v, g, item_id);
904 run_lints!(cx, check_variant_post, early_passes, v, g);
908 fn visit_ty(&mut self, t: &'a ast::Ty) {
909 run_lints!(self, check_ty, early_passes, t);
911 ast_visit::walk_ty(self, t);
914 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
915 run_lints!(self, check_ident, early_passes, sp, id);
918 fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
919 run_lints!(self, check_mod, early_passes, m, s, n);
921 ast_visit::walk_mod(self, m);
922 run_lints!(self, check_mod_post, early_passes, m, s, n);
925 fn visit_local(&mut self, l: &'a ast::Local) {
926 self.with_lint_attrs(l.id, &l.attrs, |cx| {
927 run_lints!(cx, check_local, early_passes, l);
928 ast_visit::walk_local(cx, l);
932 fn visit_block(&mut self, b: &'a ast::Block) {
933 run_lints!(self, check_block, early_passes, b);
935 ast_visit::walk_block(self, b);
936 run_lints!(self, check_block_post, early_passes, b);
939 fn visit_arm(&mut self, a: &'a ast::Arm) {
940 run_lints!(self, check_arm, early_passes, a);
941 ast_visit::walk_arm(self, a);
944 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
945 run_lints!(self, check_expr_post, early_passes, e);
948 fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
949 run_lints!(self, check_generic_param, early_passes, param);
950 ast_visit::walk_generic_param(self, param);
953 fn visit_generics(&mut self, g: &'a ast::Generics) {
954 run_lints!(self, check_generics, early_passes, g);
955 ast_visit::walk_generics(self, g);
958 fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
959 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
960 run_lints!(cx, check_trait_item, early_passes, trait_item);
961 ast_visit::walk_trait_item(cx, trait_item);
962 run_lints!(cx, check_trait_item_post, early_passes, trait_item);
966 fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
967 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
968 run_lints!(cx, check_impl_item, early_passes, impl_item);
969 ast_visit::walk_impl_item(cx, impl_item);
970 run_lints!(cx, check_impl_item_post, early_passes, impl_item);
974 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
975 run_lints!(self, check_lifetime, early_passes, lt);
976 self.check_id(lt.id);
979 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
980 run_lints!(self, check_path, early_passes, p, id);
982 ast_visit::walk_path(self, p);
985 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
986 run_lints!(self, check_attribute, early_passes, attr);
989 fn visit_mac_def(&mut self, _mac: &'a ast::MacroDef, id: ast::NodeId) {
995 /// Perform lint checking on a crate.
997 /// Consumes the `lint_store` field of the `Session`.
998 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
999 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1001 let krate = tcx.hir.krate();
1003 let mut cx = LateContext {
1005 tables: &ty::TypeckTables::empty(None),
1006 param_env: ty::ParamEnv::empty(Reveal::UserFacing),
1008 lint_sess: LintSession::new(&tcx.sess.lint_store),
1009 last_ast_node_with_lint_attrs: ast::CRATE_NODE_ID,
1013 // Visit the whole crate.
1014 cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1015 // since the root module isn't visited as an item (because it isn't an
1016 // item), warn for it here.
1017 run_lints!(cx, check_crate, late_passes, krate);
1019 hir_visit::walk_crate(cx, krate);
1021 run_lints!(cx, check_crate_post, late_passes, krate);
1024 // Put the lint store levels and passes back in the session.
1025 cx.lint_sess.restore(&tcx.sess.lint_store);
1028 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1029 let mut cx = EarlyContext::new(sess, krate);
1031 // Visit the whole crate.
1032 cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1033 // since the root module isn't visited as an item (because it isn't an
1034 // item), warn for it here.
1035 run_lints!(cx, check_crate, early_passes, krate);
1037 ast_visit::walk_crate(cx, krate);
1039 run_lints!(cx, check_crate_post, early_passes, krate);
1042 // Put the lint store levels and passes back in the session.
1043 cx.lint_sess.restore(&sess.lint_store);
1045 // Emit all buffered lints from early on in the session now that we've
1046 // calculated the lint levels for all AST nodes.
1047 for (_id, lints) in cx.buffered.map {
1048 for early_lint in lints {
1049 span_bug!(early_lint.span, "failed to process bufferd lint here");
1054 impl Encodable for LintId {
1055 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1056 s.emit_str(&self.lint.name.to_lowercase())
1060 impl Decodable for LintId {
1062 fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1063 let s = d.read_str()?;
1064 ty::tls::with(|tcx| {
1065 match tcx.sess.lint_store.borrow().find_lints(&s) {
1068 panic!("invalid lint-id `{}`", s);
1072 Err(_) => panic!("invalid lint-id `{}`", s),