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::{self, Lrc};
26 use crate::errors::{DiagnosticBuilder, DiagnosticId};
27 use crate::hir::def_id::{CrateNum, LOCAL_CRATE};
28 use crate::hir::intravisit;
30 use crate::lint::builtin::BuiltinLintDiagnostics;
31 use crate::lint::builtin::parser::{QUESTION_MARK_MACRO_SEP, ILL_FORMED_ATTRIBUTE_INPUT};
32 use crate::session::{Session, DiagnosticMessageId};
35 use syntax::source_map::{MultiSpan, ExpnFormat};
36 use syntax::early_buffered_lints::BufferedEarlyLintId;
37 use syntax::edition::Edition;
38 use syntax::symbol::Symbol;
40 use crate::ty::TyCtxt;
41 use crate::ty::query::Providers;
42 use crate::util::nodemap::NodeMap;
44 pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore,
45 check_crate, check_ast_crate, CheckLintNameResult,
46 FutureIncompatibleInfo, BufferedEarlyLint};
48 /// Specification of a single lint.
49 #[derive(Copy, Clone, Debug)]
51 /// A string identifier for the lint.
53 /// This identifies the lint in attributes and in command-line arguments.
54 /// In those contexts it is always lowercase, but this field is compared
55 /// in a way which is case-insensitive for ASCII characters. This allows
56 /// `declare_lint!()` invocations to follow the convention of upper-case
57 /// statics without repeating the name.
59 /// The name is written with underscores, e.g., "unused_imports".
60 /// On the command line, underscores become dashes.
61 pub name: &'static str,
63 /// Default level for the lint.
64 pub default_level: Level,
66 /// Description of the lint or the issue it detects.
68 /// e.g., "imports that are never used"
69 pub desc: &'static str,
71 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
73 pub edition_lint_opts: Option<(Edition, Level)>,
75 /// Whether this lint is reported even inside expansions of external macros
76 pub report_in_external_macro: bool,
80 /// Returns the `rust::lint::Lint` for a `syntax::early_buffered_lints::BufferedEarlyLintId`.
81 pub fn from_parser_lint_id(lint_id: BufferedEarlyLintId) -> &'static Self {
83 BufferedEarlyLintId::QuestionMarkMacroSep => QUESTION_MARK_MACRO_SEP,
84 BufferedEarlyLintId::IllFormedAttributeInput => ILL_FORMED_ATTRIBUTE_INPUT,
88 /// Get the lint's name, with ASCII letters converted to lowercase.
89 pub fn name_lower(&self) -> String {
90 self.name.to_ascii_lowercase()
93 pub fn default_level(&self, session: &Session) -> Level {
94 self.edition_lint_opts
95 .filter(|(e, _)| *e <= session.edition())
97 .unwrap_or(self.default_level)
101 /// Declare a static item of type `&'static Lint`.
103 macro_rules! declare_lint {
104 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
105 declare_lint!{$vis $NAME, $Level, $desc, false}
107 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, report_in_external_macro: $rep: expr) => (
108 declare_lint!{$vis $NAME, $Level, $desc, $rep}
110 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, $external: expr) => (
111 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
112 name: stringify!($NAME),
113 default_level: $crate::lint::$Level,
115 edition_lint_opts: None,
116 report_in_external_macro: $external,
119 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
120 $lint_edition: expr => $edition_level: ident
122 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
123 name: stringify!($NAME),
124 default_level: $crate::lint::$Level,
126 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
127 report_in_external_macro: false,
133 macro_rules! declare_tool_lint {
134 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr) => (
135 declare_tool_lint!{$vis $tool::$NAME, $Level, $desc, false}
137 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr,
138 report_in_external_macro: $rep: expr) => (
139 declare_tool_lint!{$vis $tool::$NAME, $Level, $desc, $rep}
141 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr, $external: expr) => (
142 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
143 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
144 default_level: $crate::lint::$Level,
146 edition_lint_opts: None,
147 report_in_external_macro: $external,
152 /// Declare a static `LintArray` and return it as an expression.
154 macro_rules! lint_array {
155 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
156 ($( $lint:expr ),*) => {{
161 pub type LintArray = Vec<&'static Lint>;
164 fn name(&self) -> &'static str;
166 /// Get descriptions of the lints this `LintPass` object can emit.
168 /// N.B., there is no enforcement that the object only emits lints it registered.
169 /// And some `rustc` internal `LintPass`es register lints to be emitted by other
170 /// parts of the compiler. If you want enforced access restrictions for your
171 /// `Lint`, make it a private `static` item in its own module.
172 fn get_lints(&self) -> LintArray;
176 macro_rules! late_lint_methods {
177 ($macro:path, $args:tt, [$hir:tt]) => (
178 $macro!($args, [$hir], [
179 fn check_body(a: &$hir hir::Body);
180 fn check_body_post(a: &$hir hir::Body);
181 fn check_name(a: Span, b: ast::Name);
182 fn check_crate(a: &$hir hir::Crate);
183 fn check_crate_post(a: &$hir hir::Crate);
184 fn check_mod(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
185 fn check_mod_post(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
186 fn check_foreign_item(a: &$hir hir::ForeignItem);
187 fn check_foreign_item_post(a: &$hir hir::ForeignItem);
188 fn check_item(a: &$hir hir::Item);
189 fn check_item_post(a: &$hir hir::Item);
190 fn check_local(a: &$hir hir::Local);
191 fn check_block(a: &$hir hir::Block);
192 fn check_block_post(a: &$hir hir::Block);
193 fn check_stmt(a: &$hir hir::Stmt);
194 fn check_arm(a: &$hir hir::Arm);
195 fn check_pat(a: &$hir hir::Pat);
196 fn check_expr(a: &$hir hir::Expr);
197 fn check_expr_post(a: &$hir hir::Expr);
198 fn check_ty(a: &$hir hir::Ty);
199 fn check_generic_param(a: &$hir hir::GenericParam);
200 fn check_generics(a: &$hir hir::Generics);
201 fn check_where_predicate(a: &$hir hir::WherePredicate);
202 fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
204 a: hir::intravisit::FnKind<$hir>,
205 b: &$hir hir::FnDecl,
210 a: hir::intravisit::FnKind<$hir>,
211 b: &$hir hir::FnDecl,
216 fn check_trait_item(a: &$hir hir::TraitItem);
217 fn check_trait_item_post(a: &$hir hir::TraitItem);
218 fn check_impl_item(a: &$hir hir::ImplItem);
219 fn check_impl_item_post(a: &$hir hir::ImplItem);
221 a: &$hir hir::VariantData,
223 c: &$hir hir::Generics,
226 fn check_struct_def_post(
227 a: &$hir hir::VariantData,
229 c: &$hir hir::Generics,
232 fn check_struct_field(a: &$hir hir::StructField);
233 fn check_variant(a: &$hir hir::Variant, b: &$hir hir::Generics);
234 fn check_variant_post(a: &$hir hir::Variant, b: &$hir hir::Generics);
235 fn check_lifetime(a: &$hir hir::Lifetime);
236 fn check_path(a: &$hir hir::Path, b: hir::HirId);
237 fn check_attribute(a: &$hir ast::Attribute);
239 /// Called when entering a syntax node that can have lint attributes such
240 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
241 fn enter_lint_attrs(a: &$hir [ast::Attribute]);
243 /// Counterpart to `enter_lint_attrs`.
244 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
249 /// Trait for types providing lint checks.
251 /// Each `check` method checks a single syntax node, and should not
252 /// invoke methods recursively (unlike `Visitor`). By default they
255 // FIXME: eliminate the duplication with `Visitor`. But this also
256 // contains a few lint-specific methods with no equivalent in `Visitor`.
258 macro_rules! expand_lint_pass_methods {
259 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
260 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
264 macro_rules! declare_late_lint_pass {
265 ([], [$hir:tt], [$($methods:tt)*]) => (
266 pub trait LateLintPass<'a, $hir>: LintPass {
267 expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
272 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
275 macro_rules! expand_combined_late_lint_pass_method {
276 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
277 $($self.$passes.$name $params;)*
282 macro_rules! expand_combined_late_lint_pass_methods {
283 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
284 $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
285 expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
291 macro_rules! declare_combined_late_lint_pass {
292 ([$name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
293 #[allow(non_snake_case)]
295 $($passes: $passes,)*
301 $($passes: $constructor,)*
306 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
307 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
310 impl LintPass for $name {
311 fn name(&self) -> &'static str {
315 fn get_lints(&self) -> LintArray {
316 let mut lints = Vec::new();
317 $(lints.extend_from_slice(&self.$passes.get_lints());)*
325 macro_rules! early_lint_methods {
326 ($macro:path, $args:tt) => (
328 fn check_ident(a: ast::Ident);
329 fn check_crate(a: &ast::Crate);
330 fn check_crate_post(a: &ast::Crate);
331 fn check_mod(a: &ast::Mod, b: Span, c: ast::NodeId);
332 fn check_mod_post(a: &ast::Mod, b: Span, c: ast::NodeId);
333 fn check_foreign_item(a: &ast::ForeignItem);
334 fn check_foreign_item_post(a: &ast::ForeignItem);
335 fn check_item(a: &ast::Item);
336 fn check_item_post(a: &ast::Item);
337 fn check_local(a: &ast::Local);
338 fn check_block(a: &ast::Block);
339 fn check_block_post(a: &ast::Block);
340 fn check_stmt(a: &ast::Stmt);
341 fn check_arm(a: &ast::Arm);
342 fn check_pat(a: &ast::Pat, b: &mut bool); // FIXME: &mut bool looks just broken
343 fn check_expr(a: &ast::Expr);
344 fn check_expr_post(a: &ast::Expr);
345 fn check_ty(a: &ast::Ty);
346 fn check_generic_param(a: &ast::GenericParam);
347 fn check_generics(a: &ast::Generics);
348 fn check_where_predicate(a: &ast::WherePredicate);
349 fn check_poly_trait_ref(a: &ast::PolyTraitRef,
350 b: &ast::TraitBoundModifier);
351 fn check_fn(a: syntax::visit::FnKind<'_>, b: &ast::FnDecl, c: Span, d_: ast::NodeId);
353 a: syntax::visit::FnKind<'_>,
358 fn check_trait_item(a: &ast::TraitItem);
359 fn check_trait_item_post(a: &ast::TraitItem);
360 fn check_impl_item(a: &ast::ImplItem);
361 fn check_impl_item_post(a: &ast::ImplItem);
363 a: &ast::VariantData,
368 fn check_struct_def_post(
369 a: &ast::VariantData,
374 fn check_struct_field(a: &ast::StructField);
375 fn check_variant(a: &ast::Variant, b: &ast::Generics);
376 fn check_variant_post(a: &ast::Variant, b: &ast::Generics);
377 fn check_lifetime(a: &ast::Lifetime);
378 fn check_path(a: &ast::Path, b: ast::NodeId);
379 fn check_attribute(a: &ast::Attribute);
380 fn check_mac_def(a: &ast::MacroDef, b: ast::NodeId);
381 fn check_mac(a: &ast::Mac);
383 /// Called when entering a syntax node that can have lint attributes such
384 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
385 fn enter_lint_attrs(a: &[ast::Attribute]);
387 /// Counterpart to `enter_lint_attrs`.
388 fn exit_lint_attrs(a: &[ast::Attribute]);
393 macro_rules! expand_early_lint_pass_methods {
394 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
395 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
399 macro_rules! declare_early_lint_pass {
400 ([], [$($methods:tt)*]) => (
401 pub trait EarlyLintPass: LintPass {
402 expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]);
407 early_lint_methods!(declare_early_lint_pass, []);
410 macro_rules! expand_combined_early_lint_pass_method {
411 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
412 $($self.$passes.$name $params;)*
417 macro_rules! expand_combined_early_lint_pass_methods {
418 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
419 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
420 expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
426 macro_rules! declare_combined_early_lint_pass {
427 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
428 #[allow(non_snake_case)]
430 $($passes: $passes,)*
434 $v fn new() -> Self {
436 $($passes: $constructor,)*
441 impl EarlyLintPass for $name {
442 expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
445 impl LintPass for $name {
446 fn name(&self) -> &'static str {
450 fn get_lints(&self) -> LintArray {
451 let mut lints = Vec::new();
452 $(lints.extend_from_slice(&self.$passes.get_lints());)*
459 /// A lint pass boxed up as a trait object.
460 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
461 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
462 + sync::Sync + 'static>;
466 /// Identifies a lint known to the compiler.
467 #[derive(Clone, Copy, Debug)]
469 // Identity is based on pointer equality of this field.
473 impl PartialEq for LintId {
474 fn eq(&self, other: &LintId) -> bool {
475 ptr::eq(self.lint, other.lint)
479 impl Eq for LintId { }
481 impl hash::Hash for LintId {
482 fn hash<H: hash::Hasher>(&self, state: &mut H) {
483 let ptr = self.lint as *const Lint;
489 /// Get the `LintId` for a `Lint`.
490 pub fn of(lint: &'static Lint) -> LintId {
496 pub fn lint_name_raw(&self) -> &'static str {
500 /// Get the name of the lint.
501 pub fn to_string(&self) -> String {
502 self.lint.name_lower()
506 /// Setting for how to handle a lint.
507 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
509 Allow, Warn, Deny, Forbid,
512 impl_stable_hash_for!(enum self::Level {
520 /// Convert a level to a lower-case string.
521 pub fn as_str(self) -> &'static str {
530 /// Convert a lower-case string to a level.
531 pub fn from_str(x: &str) -> Option<Level> {
533 "allow" => Some(Allow),
534 "warn" => Some(Warn),
535 "deny" => Some(Deny),
536 "forbid" => Some(Forbid),
542 /// How a lint level was set.
543 #[derive(Clone, Copy, PartialEq, Eq)]
544 pub enum LintSource {
545 /// Lint is at the default level as declared
546 /// in rustc or a plugin.
549 /// Lint level was set by an attribute.
550 Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
552 /// Lint level was set by a command-line flag.
556 impl_stable_hash_for!(enum self::LintSource {
558 Node(name, span, reason),
562 pub type LevelSource = (Level, LintSource);
568 pub use self::levels::{LintLevelSets, LintLevelMap};
571 pub struct LintBuffer {
572 map: NodeMap<Vec<BufferedEarlyLint>>,
576 pub fn add_lint(&mut self,
581 diagnostic: BuiltinLintDiagnostics) {
582 let early_lint = BufferedEarlyLint {
583 lint_id: LintId::of(lint),
586 msg: msg.to_string(),
589 let arr = self.map.entry(id).or_default();
590 if !arr.contains(&early_lint) {
591 arr.push(early_lint);
595 pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
596 self.map.remove(&id).unwrap_or_default()
599 pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
600 let key = self.map.keys().next().map(|k| *k);
601 key.map(|k| &self.map[&k][..])
605 pub fn struct_lint_level<'a>(sess: &'a Session,
609 span: Option<MultiSpan>,
611 -> DiagnosticBuilder<'a>
613 let mut err = match (level, span) {
614 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
615 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
616 (Level::Warn, None) => sess.struct_warn(msg),
617 (Level::Deny, Some(span)) |
618 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
619 (Level::Deny, None) |
620 (Level::Forbid, None) => sess.struct_err(msg),
623 let name = lint.name_lower();
625 LintSource::Default => {
628 DiagnosticMessageId::from(lint),
629 &format!("#[{}({})] on by default", level.as_str(), name));
631 LintSource::CommandLine(lint_flag_val) => {
632 let flag = match level {
635 Level::Forbid => "-F",
636 Level::Allow => panic!(),
638 let hyphen_case_lint_name = name.replace("_", "-");
639 if lint_flag_val.as_str() == name {
642 DiagnosticMessageId::from(lint),
643 &format!("requested on the command line with `{} {}`",
644 flag, hyphen_case_lint_name));
646 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
649 DiagnosticMessageId::from(lint),
650 &format!("`{} {}` implied by `{} {}`",
651 flag, hyphen_case_lint_name, flag,
652 hyphen_case_flag_val));
655 LintSource::Node(lint_attr_name, src, reason) => {
656 if let Some(rationale) = reason {
657 err.note(&rationale.as_str());
659 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
660 src, "lint level defined here");
661 if lint_attr_name.as_str() != name {
662 let level_str = level.as_str();
663 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
664 &format!("#[{}({})] implied by #[{}({})]",
665 level_str, name, level_str, lint_attr_name));
670 err.code(DiagnosticId::Lint(name));
672 // Check for future incompatibility lints and issue a stronger warning.
673 let lints = sess.lint_store.borrow();
674 let lint_id = LintId::of(lint);
675 let future_incompatible = lints.future_incompatible(lint_id);
676 if let Some(future_incompatible) = future_incompatible {
677 const STANDARD_MESSAGE: &str =
678 "this was previously accepted by the compiler but is being phased out; \
679 it will become a hard error";
681 let explanation = if lint_id == LintId::of(crate::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
682 "once this method is added to the standard library, \
683 the ambiguity may cause an error or change in behavior!"
685 } else if let Some(edition) = future_incompatible.edition {
686 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
688 format!("{} in a future release!", STANDARD_MESSAGE)
690 let citation = format!("for more information, see {}",
691 future_incompatible.reference);
692 err.warn(&explanation);
696 // If this code originates in a foreign macro, aka something that this crate
697 // did not itself author, then it's likely that there's nothing this crate
698 // can do about it. We probably want to skip the lint entirely.
699 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
700 // Any suggestions made here are likely to be incorrect, so anything we
701 // emit shouldn't be automatically fixed by rustfix.
702 err.allow_suggestions(false);
704 // If this is a future incompatible lint it'll become a hard error, so
705 // we have to emit *something*. Also allow lints to whitelist themselves
706 // on a case-by-case basis for emission in a foreign macro.
707 if future_incompatible.is_none() && !lint.report_in_external_macro {
715 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
718 assert_eq!(cnum, LOCAL_CRATE);
719 let mut builder = LintLevelMapBuilder {
720 levels: LintLevelSets::builder(tcx.sess),
723 let krate = tcx.hir().krate();
725 builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
726 intravisit::walk_crate(builder, krate);
729 Lrc::new(builder.levels.build_map())
732 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
733 levels: levels::LintLevelsBuilder<'tcx>,
734 tcx: TyCtxt<'a, 'tcx, 'tcx>,
737 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
738 fn with_lint_attrs<F>(&mut self,
740 attrs: &[ast::Attribute],
742 where F: FnOnce(&mut Self)
744 let push = self.levels.push(attrs);
745 self.levels.register_id(self.tcx.hir().definitions().node_to_hir_id(id));
747 self.levels.pop(push);
751 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
752 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
753 intravisit::NestedVisitorMap::All(&self.tcx.hir())
756 fn visit_item(&mut self, it: &'tcx hir::Item) {
757 self.with_lint_attrs(it.id, &it.attrs, |builder| {
758 intravisit::walk_item(builder, it);
762 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
763 self.with_lint_attrs(it.id, &it.attrs, |builder| {
764 intravisit::walk_foreign_item(builder, it);
768 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
769 self.with_lint_attrs(e.id, &e.attrs, |builder| {
770 intravisit::walk_expr(builder, e);
774 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
775 self.with_lint_attrs(s.id, &s.attrs, |builder| {
776 intravisit::walk_struct_field(builder, s);
780 fn visit_variant(&mut self,
781 v: &'tcx hir::Variant,
782 g: &'tcx hir::Generics,
783 item_id: ast::NodeId) {
784 self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
785 intravisit::walk_variant(builder, v, g, item_id);
789 fn visit_local(&mut self, l: &'tcx hir::Local) {
790 self.with_lint_attrs(l.id, &l.attrs, |builder| {
791 intravisit::walk_local(builder, l);
795 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
796 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
797 intravisit::walk_trait_item(builder, trait_item);
801 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
802 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
803 intravisit::walk_impl_item(builder, impl_item);
808 pub fn provide(providers: &mut Providers<'_>) {
809 providers.lint_levels = lint_levels;
812 /// Returns whether `span` originates in a foreign crate's external macro.
814 /// This is used to test whether a lint should be entirely aborted above.
815 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
816 let info = match span.ctxt().outer().expn_info() {
818 // no ExpnInfo means this span doesn't come from a macro
819 None => return false,
823 ExpnFormat::MacroAttribute(..) => return true, // definitely a plugin
824 ExpnFormat::CompilerDesugaring(_) => return true, // well, it's "external"
825 ExpnFormat::MacroBang(..) => {} // check below
828 let def_site = match info.def_site {
830 // no span for the def_site means it's an external macro
834 match sess.source_map().span_to_snippet(def_site) {
835 Ok(code) => !code.starts_with("macro_rules"),
836 // no snippet = external macro or compiler-builtin expansion