1 //! Lints, aka compiler warnings.
3 //! A 'lint' check is a kind of miscellaneous constraint that a user _might_
4 //! want to enforce, but might reasonably want to permit as well, on a
5 //! module-by-module basis. They contrast with static constraints enforced by
6 //! other phases of the compiler, which are generally required to hold in order
7 //! to compile the program at all.
9 //! Most lints can be written as `LintPass` instances. These run after
10 //! all other analyses. The `LintPass`es built into rustc are defined
11 //! within `builtin.rs`, which has further comments on how to add such a lint.
12 //! rustc can also load user-defined lint plugins via the plugin mechanism.
14 //! Some of rustc's lints are defined elsewhere in the compiler and work by
15 //! calling `add_lint()` on the overall `Session` object. This works when
16 //! it happens before the main lint pass, which emits the lints stored by
17 //! `add_lint()`. To emit lints after the main lint pass (from codegen, for
18 //! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
21 pub use self::Level::*;
22 pub use self::LintSource::*;
24 use rustc_data_structures::sync;
26 use crate::hir::def_id::{CrateNum, LOCAL_CRATE};
27 use crate::hir::intravisit;
29 use crate::lint::builtin::BuiltinLintDiagnostics;
30 use crate::session::{Session, DiagnosticMessageId};
31 use crate::ty::TyCtxt;
32 use crate::ty::query::Providers;
33 use crate::util::nodemap::NodeMap;
34 use errors::{DiagnosticBuilder, DiagnosticId};
36 use syntax::source_map::{MultiSpan, ExpnKind, DesugaringKind};
37 use syntax::symbol::Symbol;
38 use syntax_pos::hygiene::MacroKind;
41 pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore,
42 check_crate, check_ast_crate, late_lint_mod, CheckLintNameResult,
45 pub use rustc_session::lint::{Lint, LintId, Level, FutureIncompatibleInfo};
47 /// Declares a static `LintArray` and return it as an expression.
49 macro_rules! lint_array {
50 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
51 ($( $lint:expr ),*) => {{
56 pub type LintArray = Vec<&'static Lint>;
59 fn name(&self) -> &'static str;
62 /// Implements `LintPass for $name` with the given list of `Lint` statics.
64 macro_rules! impl_lint_pass {
65 ($name:ident => [$($lint:expr),* $(,)?]) => {
66 impl LintPass for $name {
67 fn name(&self) -> &'static str { stringify!($name) }
70 pub fn get_lints() -> LintArray { $crate::lint_array!($($lint),*) }
75 /// Declares a type named `$name` which implements `LintPass`.
76 /// To the right of `=>` a comma separated list of `Lint` statics is given.
78 macro_rules! declare_lint_pass {
79 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
80 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
81 $crate::impl_lint_pass!($name => [$($lint),*]);
86 macro_rules! late_lint_methods {
87 ($macro:path, $args:tt, [$hir:tt]) => (
88 $macro!($args, [$hir], [
89 fn check_param(a: &$hir hir::Param);
90 fn check_body(a: &$hir hir::Body<$hir>);
91 fn check_body_post(a: &$hir hir::Body<$hir>);
92 fn check_name(a: Span, b: ast::Name);
93 fn check_crate(a: &$hir hir::Crate<$hir>);
94 fn check_crate_post(a: &$hir hir::Crate<$hir>);
95 fn check_mod(a: &$hir hir::Mod<$hir>, b: Span, c: hir::HirId);
96 fn check_mod_post(a: &$hir hir::Mod<$hir>, b: Span, c: hir::HirId);
97 fn check_foreign_item(a: &$hir hir::ForeignItem<$hir>);
98 fn check_foreign_item_post(a: &$hir hir::ForeignItem<$hir>);
99 fn check_item(a: &$hir hir::Item<$hir>);
100 fn check_item_post(a: &$hir hir::Item<$hir>);
101 fn check_local(a: &$hir hir::Local);
102 fn check_block(a: &$hir hir::Block);
103 fn check_block_post(a: &$hir hir::Block);
104 fn check_stmt(a: &$hir hir::Stmt);
105 fn check_arm(a: &$hir hir::Arm);
106 fn check_pat(a: &$hir hir::Pat);
107 fn check_expr(a: &$hir hir::Expr);
108 fn check_expr_post(a: &$hir hir::Expr);
109 fn check_ty(a: &$hir hir::Ty);
110 fn check_generic_param(a: &$hir hir::GenericParam);
111 fn check_generics(a: &$hir hir::Generics);
112 fn check_where_predicate(a: &$hir hir::WherePredicate);
113 fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
115 a: hir::intravisit::FnKind<$hir>,
116 b: &$hir hir::FnDecl,
117 c: &$hir hir::Body<$hir>,
121 a: hir::intravisit::FnKind<$hir>,
122 b: &$hir hir::FnDecl,
123 c: &$hir hir::Body<$hir>,
127 fn check_trait_item(a: &$hir hir::TraitItem<$hir>);
128 fn check_trait_item_post(a: &$hir hir::TraitItem<$hir>);
129 fn check_impl_item(a: &$hir hir::ImplItem<$hir>);
130 fn check_impl_item_post(a: &$hir hir::ImplItem<$hir>);
131 fn check_struct_def(a: &$hir hir::VariantData<$hir>);
132 fn check_struct_def_post(a: &$hir hir::VariantData<$hir>);
133 fn check_struct_field(a: &$hir hir::StructField<$hir>);
134 fn check_variant(a: &$hir hir::Variant<$hir>);
135 fn check_variant_post(a: &$hir hir::Variant<$hir>);
136 fn check_lifetime(a: &$hir hir::Lifetime);
137 fn check_path(a: &$hir hir::Path, b: hir::HirId);
138 fn check_attribute(a: &$hir ast::Attribute);
140 /// Called when entering a syntax node that can have lint attributes such
141 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
142 fn enter_lint_attrs(a: &$hir [ast::Attribute]);
144 /// Counterpart to `enter_lint_attrs`.
145 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
150 /// Trait for types providing lint checks.
152 /// Each `check` method checks a single syntax node, and should not
153 /// invoke methods recursively (unlike `Visitor`). By default they
156 // FIXME: eliminate the duplication with `Visitor`. But this also
157 // contains a few lint-specific methods with no equivalent in `Visitor`.
159 macro_rules! expand_lint_pass_methods {
160 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
161 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
165 macro_rules! declare_late_lint_pass {
166 ([], [$hir:tt], [$($methods:tt)*]) => (
167 pub trait LateLintPass<'a, $hir>: LintPass {
168 expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
173 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
176 macro_rules! expand_combined_late_lint_pass_method {
177 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
178 $($self.$passes.$name $params;)*
183 macro_rules! expand_combined_late_lint_pass_methods {
184 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
185 $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
186 expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
192 macro_rules! declare_combined_late_lint_pass {
193 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
194 #[allow(non_snake_case)]
196 $($passes: $passes,)*
200 $v fn new() -> Self {
202 $($passes: $constructor,)*
206 $v fn get_lints() -> LintArray {
207 let mut lints = Vec::new();
208 $(lints.extend_from_slice(&$passes::get_lints());)*
213 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
214 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
217 impl LintPass for $name {
218 fn name(&self) -> &'static str {
226 macro_rules! early_lint_methods {
227 ($macro:path, $args:tt) => (
229 fn check_param(a: &ast::Param);
230 fn check_ident(a: ast::Ident);
231 fn check_crate(a: &ast::Crate);
232 fn check_crate_post(a: &ast::Crate);
233 fn check_mod(a: &ast::Mod, b: Span, c: ast::NodeId);
234 fn check_mod_post(a: &ast::Mod, b: Span, c: ast::NodeId);
235 fn check_foreign_item(a: &ast::ForeignItem);
236 fn check_foreign_item_post(a: &ast::ForeignItem);
237 fn check_item(a: &ast::Item);
238 fn check_item_post(a: &ast::Item);
239 fn check_local(a: &ast::Local);
240 fn check_block(a: &ast::Block);
241 fn check_block_post(a: &ast::Block);
242 fn check_stmt(a: &ast::Stmt);
243 fn check_arm(a: &ast::Arm);
244 fn check_pat(a: &ast::Pat);
245 fn check_pat_post(a: &ast::Pat);
246 fn check_expr(a: &ast::Expr);
247 fn check_expr_post(a: &ast::Expr);
248 fn check_ty(a: &ast::Ty);
249 fn check_generic_param(a: &ast::GenericParam);
250 fn check_generics(a: &ast::Generics);
251 fn check_where_predicate(a: &ast::WherePredicate);
252 fn check_poly_trait_ref(a: &ast::PolyTraitRef,
253 b: &ast::TraitBoundModifier);
254 fn check_fn(a: syntax::visit::FnKind<'_>, b: &ast::FnDecl, c: Span, d_: ast::NodeId);
256 a: syntax::visit::FnKind<'_>,
261 fn check_trait_item(a: &ast::AssocItem);
262 fn check_trait_item_post(a: &ast::AssocItem);
263 fn check_impl_item(a: &ast::AssocItem);
264 fn check_impl_item_post(a: &ast::AssocItem);
265 fn check_struct_def(a: &ast::VariantData);
266 fn check_struct_def_post(a: &ast::VariantData);
267 fn check_struct_field(a: &ast::StructField);
268 fn check_variant(a: &ast::Variant);
269 fn check_variant_post(a: &ast::Variant);
270 fn check_lifetime(a: &ast::Lifetime);
271 fn check_path(a: &ast::Path, b: ast::NodeId);
272 fn check_attribute(a: &ast::Attribute);
273 fn check_mac_def(a: &ast::MacroDef, b: ast::NodeId);
274 fn check_mac(a: &ast::Mac);
276 /// Called when entering a syntax node that can have lint attributes such
277 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
278 fn enter_lint_attrs(a: &[ast::Attribute]);
280 /// Counterpart to `enter_lint_attrs`.
281 fn exit_lint_attrs(a: &[ast::Attribute]);
286 macro_rules! expand_early_lint_pass_methods {
287 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
288 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
292 macro_rules! declare_early_lint_pass {
293 ([], [$($methods:tt)*]) => (
294 pub trait EarlyLintPass: LintPass {
295 expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]);
300 early_lint_methods!(declare_early_lint_pass, []);
303 macro_rules! expand_combined_early_lint_pass_method {
304 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
305 $($self.$passes.$name $params;)*
310 macro_rules! expand_combined_early_lint_pass_methods {
311 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
312 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
313 expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
319 macro_rules! declare_combined_early_lint_pass {
320 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
321 #[allow(non_snake_case)]
323 $($passes: $passes,)*
327 $v fn new() -> Self {
329 $($passes: $constructor,)*
333 $v fn get_lints() -> LintArray {
334 let mut lints = Vec::new();
335 $(lints.extend_from_slice(&$passes::get_lints());)*
340 impl EarlyLintPass for $name {
341 expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
344 impl LintPass for $name {
345 fn name(&self) -> &'static str {
352 /// A lint pass boxed up as a trait object.
353 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
354 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
355 + sync::Sync + 'static>;
357 /// How a lint level was set.
358 #[derive(Clone, Copy, PartialEq, Eq, HashStable)]
359 pub enum LintSource {
360 /// Lint is at the default level as declared
361 /// in rustc or a plugin.
364 /// Lint level was set by an attribute.
365 Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
367 /// Lint level was set by a command-line flag.
371 pub type LevelSource = (Level, LintSource);
378 pub use self::levels::{LintLevelSets, LintLevelMap};
381 pub struct LintBuffer {
382 map: NodeMap<Vec<BufferedEarlyLint>>,
386 pub fn add_lint(&mut self,
391 diagnostic: BuiltinLintDiagnostics) {
392 let early_lint = BufferedEarlyLint {
393 lint_id: LintId::of(lint),
396 msg: msg.to_string(),
399 let arr = self.map.entry(id).or_default();
400 if !arr.contains(&early_lint) {
401 arr.push(early_lint);
405 fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
406 self.map.remove(&id).unwrap_or_default()
409 pub fn buffer_lint<S: Into<MultiSpan>>(
416 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
419 pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(
425 diagnostic: BuiltinLintDiagnostics,
427 self.add_lint(lint, id, sp.into(), msg, diagnostic)
431 pub fn struct_lint_level<'a>(sess: &'a Session,
435 span: Option<MultiSpan>,
437 -> DiagnosticBuilder<'a>
439 let mut err = match (level, span) {
440 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
441 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
442 (Level::Warn, None) => sess.struct_warn(msg),
443 (Level::Deny, Some(span)) |
444 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
445 (Level::Deny, None) |
446 (Level::Forbid, None) => sess.struct_err(msg),
449 // Check for future incompatibility lints and issue a stronger warning.
450 let lint_id = LintId::of(lint);
451 let future_incompatible = lint.future_incompatible;
453 // If this code originates in a foreign macro, aka something that this crate
454 // did not itself author, then it's likely that there's nothing this crate
455 // can do about it. We probably want to skip the lint entirely.
456 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
457 // Any suggestions made here are likely to be incorrect, so anything we
458 // emit shouldn't be automatically fixed by rustfix.
459 err.allow_suggestions(false);
461 // If this is a future incompatible lint it'll become a hard error, so
462 // we have to emit *something*. Also allow lints to whitelist themselves
463 // on a case-by-case basis for emission in a foreign macro.
464 if future_incompatible.is_none() && !lint.report_in_external_macro {
466 // Don't continue further, since we don't want to have
467 // `diag_span_note_once` called for a diagnostic that isn't emitted.
472 let name = lint.name_lower();
474 LintSource::Default => {
477 DiagnosticMessageId::from(lint),
478 &format!("`#[{}({})]` on by default", level.as_str(), name));
480 LintSource::CommandLine(lint_flag_val) => {
481 let flag = match level {
484 Level::Forbid => "-F",
485 Level::Allow => panic!(),
487 let hyphen_case_lint_name = name.replace("_", "-");
488 if lint_flag_val.as_str() == name {
491 DiagnosticMessageId::from(lint),
492 &format!("requested on the command line with `{} {}`",
493 flag, hyphen_case_lint_name));
495 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
498 DiagnosticMessageId::from(lint),
499 &format!("`{} {}` implied by `{} {}`",
500 flag, hyphen_case_lint_name, flag,
501 hyphen_case_flag_val));
504 LintSource::Node(lint_attr_name, src, reason) => {
505 if let Some(rationale) = reason {
506 err.note(&rationale.as_str());
508 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
509 src, "lint level defined here");
510 if lint_attr_name.as_str() != name {
511 let level_str = level.as_str();
512 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
513 &format!("`#[{}({})]` implied by `#[{}({})]`",
514 level_str, name, level_str, lint_attr_name));
519 err.code(DiagnosticId::Lint(name));
521 if let Some(future_incompatible) = future_incompatible {
522 const STANDARD_MESSAGE: &str =
523 "this was previously accepted by the compiler but is being phased out; \
524 it will become a hard error";
526 let explanation = if lint_id == LintId::of(builtin::UNSTABLE_NAME_COLLISIONS) {
527 "once this method is added to the standard library, \
528 the ambiguity may cause an error or change in behavior!"
530 } else if lint_id == LintId::of(builtin::MUTABLE_BORROW_RESERVATION_CONFLICT) {
531 "this borrowing pattern was not meant to be accepted, \
532 and may become a hard error in the future"
534 } else if let Some(edition) = future_incompatible.edition {
535 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
537 format!("{} in a future release!", STANDARD_MESSAGE)
539 let citation = format!("for more information, see {}",
540 future_incompatible.reference);
541 err.warn(&explanation);
548 pub fn maybe_lint_level_root(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
549 let attrs = tcx.hir().attrs(id);
550 attrs.iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some())
553 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap {
554 assert_eq!(cnum, LOCAL_CRATE);
555 let store = &tcx.lint_store;
556 let mut builder = LintLevelMapBuilder {
557 levels: LintLevelSets::builder(tcx.sess, false, &store),
561 let krate = tcx.hir().krate();
563 let push = builder.levels.push(&krate.attrs, &store);
564 builder.levels.register_id(hir::CRATE_HIR_ID);
565 for macro_def in krate.exported_macros {
566 builder.levels.register_id(macro_def.hir_id);
568 intravisit::walk_crate(&mut builder, krate);
569 builder.levels.pop(push);
571 tcx.arena.alloc(builder.levels.build_map())
574 struct LintLevelMapBuilder<'a, 'tcx> {
575 levels: levels::LintLevelsBuilder<'tcx>,
577 store: &'a LintStore,
580 impl LintLevelMapBuilder<'_, '_> {
581 fn with_lint_attrs<F>(&mut self,
583 attrs: &[ast::Attribute],
585 where F: FnOnce(&mut Self)
587 let push = self.levels.push(attrs, self.store);
589 self.levels.register_id(id);
592 self.levels.pop(push);
596 impl intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
597 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
598 intravisit::NestedVisitorMap::All(&self.tcx.hir())
601 fn visit_param(&mut self, param: &'tcx hir::Param) {
602 self.with_lint_attrs(param.hir_id, ¶m.attrs, |builder| {
603 intravisit::walk_param(builder, param);
607 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
608 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
609 intravisit::walk_item(builder, it);
613 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
614 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
615 intravisit::walk_foreign_item(builder, it);
619 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
620 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
621 intravisit::walk_expr(builder, e);
625 fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
626 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
627 intravisit::walk_struct_field(builder, s);
631 fn visit_variant(&mut self,
632 v: &'tcx hir::Variant<'tcx>,
633 g: &'tcx hir::Generics,
634 item_id: hir::HirId) {
635 self.with_lint_attrs(v.id, &v.attrs, |builder| {
636 intravisit::walk_variant(builder, v, g, item_id);
640 fn visit_local(&mut self, l: &'tcx hir::Local) {
641 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
642 intravisit::walk_local(builder, l);
646 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
647 self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
648 intravisit::walk_arm(builder, a);
652 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
653 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
654 intravisit::walk_trait_item(builder, trait_item);
658 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
659 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
660 intravisit::walk_impl_item(builder, impl_item);
665 pub fn provide(providers: &mut Providers<'_>) {
666 providers.lint_levels = lint_levels;
669 /// Returns whether `span` originates in a foreign crate's external macro.
671 /// This is used to test whether a lint should not even begin to figure out whether it should
672 /// be reported on the current node.
673 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
674 let expn_data = span.ctxt().outer_expn_data();
675 match expn_data.kind {
676 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
677 ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
678 ExpnKind::Macro(MacroKind::Bang, _) => {
679 if expn_data.def_site.is_dummy() {
680 // Dummy span for the `def_site` means it's an external macro.
683 match sess.source_map().span_to_snippet(expn_data.def_site) {
684 Ok(code) => !code.starts_with("macro_rules"),
685 // No snippet means external macro or compiler-builtin expansion.
689 ExpnKind::Macro(..) => true, // definitely a plugin
693 /// Returns `true` if `span` originates in a derive-macro's expansion.
694 pub fn in_derive_expansion(span: Span) -> bool {
695 if let ExpnKind::Macro(MacroKind::Derive, _) = span.ctxt().outer_expn_data().kind {