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::hir::def_id::{CrateNum, LOCAL_CRATE};
27 use crate::hir::intravisit;
29 use crate::lint::builtin::{BuiltinLintDiagnostics, DUPLICATE_MATCHER_BINDING_NAME};
30 use crate::lint::builtin::parser::{QUESTION_MARK_MACRO_SEP, ILL_FORMED_ATTRIBUTE_INPUT};
31 use crate::session::{Session, DiagnosticMessageId};
32 use crate::ty::TyCtxt;
33 use crate::ty::query::Providers;
34 use crate::util::nodemap::NodeMap;
35 use errors::{DiagnosticBuilder, DiagnosticId};
38 use syntax::source_map::{MultiSpan, ExpnFormat};
39 use syntax::early_buffered_lints::BufferedEarlyLintId;
40 use syntax::edition::Edition;
41 use syntax::symbol::Symbol;
44 pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore,
45 check_crate, check_ast_crate, late_lint_mod, 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 /// `true` if 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,
85 BufferedEarlyLintId::DuplicateMacroMatcherBindingName => DUPLICATE_MATCHER_BINDING_NAME,
89 /// Gets the lint's name, with ASCII letters converted to lowercase.
90 pub fn name_lower(&self) -> String {
91 self.name.to_ascii_lowercase()
94 pub fn default_level(&self, session: &Session) -> Level {
95 self.edition_lint_opts
96 .filter(|(e, _)| *e <= session.edition())
98 .unwrap_or(self.default_level)
102 /// Declares a static item of type `&'static Lint`.
104 macro_rules! declare_lint {
105 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
106 declare_lint!{$vis $NAME, $Level, $desc, false}
108 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, report_in_external_macro: $rep: expr) => (
109 declare_lint!{$vis $NAME, $Level, $desc, $rep}
111 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, $external: expr) => (
112 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
113 name: stringify!($NAME),
114 default_level: $crate::lint::$Level,
116 edition_lint_opts: None,
117 report_in_external_macro: $external,
120 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
121 $lint_edition: expr => $edition_level: ident
123 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
124 name: stringify!($NAME),
125 default_level: $crate::lint::$Level,
127 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
128 report_in_external_macro: false,
134 macro_rules! declare_tool_lint {
136 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
138 declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
141 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
142 report_in_external_macro: $rep:expr
144 declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
147 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
151 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
152 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
153 default_level: $crate::lint::$Level,
155 edition_lint_opts: None,
156 report_in_external_macro: $external,
161 /// Declares a static `LintArray` and return it as an expression.
163 macro_rules! lint_array {
164 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
165 ($( $lint:expr ),*) => {{
170 pub type LintArray = Vec<&'static Lint>;
173 fn name(&self) -> &'static str;
175 /// Gets descriptions of the lints this `LintPass` object can emit.
177 /// N.B., there is no enforcement that the object only emits lints it registered.
178 /// And some `rustc` internal `LintPass`es register lints to be emitted by other
179 /// parts of the compiler. If you want enforced access restrictions for your
180 /// `Lint`, make it a private `static` item in its own module.
181 fn get_lints(&self) -> LintArray;
184 /// Implements `LintPass for $name` with the given list of `Lint` statics.
186 macro_rules! impl_lint_pass {
187 ($name:ident => [$($lint:expr),* $(,)?]) => {
188 impl LintPass for $name {
189 fn name(&self) -> &'static str { stringify!($name) }
190 fn get_lints(&self) -> LintArray { $crate::lint_array!($($lint),*) }
195 /// Declares a type named `$name` which implements `LintPass`.
196 /// To the right of `=>` a comma separated list of `Lint` statics is given.
198 macro_rules! declare_lint_pass {
199 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
200 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
201 $crate::impl_lint_pass!($name => [$($lint),*]);
206 macro_rules! late_lint_methods {
207 ($macro:path, $args:tt, [$hir:tt]) => (
208 $macro!($args, [$hir], [
209 fn check_body(a: &$hir hir::Body);
210 fn check_body_post(a: &$hir hir::Body);
211 fn check_name(a: Span, b: ast::Name);
212 fn check_crate(a: &$hir hir::Crate);
213 fn check_crate_post(a: &$hir hir::Crate);
214 fn check_mod(a: &$hir hir::Mod, b: Span, c: hir::HirId);
215 fn check_mod_post(a: &$hir hir::Mod, b: Span, c: hir::HirId);
216 fn check_foreign_item(a: &$hir hir::ForeignItem);
217 fn check_foreign_item_post(a: &$hir hir::ForeignItem);
218 fn check_item(a: &$hir hir::Item);
219 fn check_item_post(a: &$hir hir::Item);
220 fn check_local(a: &$hir hir::Local);
221 fn check_block(a: &$hir hir::Block);
222 fn check_block_post(a: &$hir hir::Block);
223 fn check_stmt(a: &$hir hir::Stmt);
224 fn check_arm(a: &$hir hir::Arm);
225 fn check_pat(a: &$hir hir::Pat);
226 fn check_expr(a: &$hir hir::Expr);
227 fn check_expr_post(a: &$hir hir::Expr);
228 fn check_ty(a: &$hir hir::Ty);
229 fn check_generic_param(a: &$hir hir::GenericParam);
230 fn check_generics(a: &$hir hir::Generics);
231 fn check_where_predicate(a: &$hir hir::WherePredicate);
232 fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
234 a: hir::intravisit::FnKind<$hir>,
235 b: &$hir hir::FnDecl,
240 a: hir::intravisit::FnKind<$hir>,
241 b: &$hir hir::FnDecl,
246 fn check_trait_item(a: &$hir hir::TraitItem);
247 fn check_trait_item_post(a: &$hir hir::TraitItem);
248 fn check_impl_item(a: &$hir hir::ImplItem);
249 fn check_impl_item_post(a: &$hir hir::ImplItem);
251 a: &$hir hir::VariantData,
253 c: &$hir hir::Generics,
256 fn check_struct_def_post(
257 a: &$hir hir::VariantData,
259 c: &$hir hir::Generics,
262 fn check_struct_field(a: &$hir hir::StructField);
263 fn check_variant(a: &$hir hir::Variant, b: &$hir hir::Generics);
264 fn check_variant_post(a: &$hir hir::Variant, b: &$hir hir::Generics);
265 fn check_lifetime(a: &$hir hir::Lifetime);
266 fn check_path(a: &$hir hir::Path, b: hir::HirId);
267 fn check_attribute(a: &$hir ast::Attribute);
269 /// Called when entering a syntax node that can have lint attributes such
270 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
271 fn enter_lint_attrs(a: &$hir [ast::Attribute]);
273 /// Counterpart to `enter_lint_attrs`.
274 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
279 /// Trait for types providing lint checks.
281 /// Each `check` method checks a single syntax node, and should not
282 /// invoke methods recursively (unlike `Visitor`). By default they
285 // FIXME: eliminate the duplication with `Visitor`. But this also
286 // contains a few lint-specific methods with no equivalent in `Visitor`.
288 macro_rules! expand_lint_pass_methods {
289 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
290 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
294 macro_rules! declare_late_lint_pass {
295 ([], [$hir:tt], [$($methods:tt)*]) => (
296 pub trait LateLintPass<'a, $hir>: LintPass {
297 fn fresh_late_pass(&self) -> LateLintPassObject {
300 expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
305 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
308 macro_rules! expand_combined_late_lint_pass_method {
309 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
310 $($self.$passes.$name $params;)*
315 macro_rules! expand_combined_late_lint_pass_methods {
316 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
317 $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
318 expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
324 macro_rules! declare_combined_late_lint_pass {
325 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
326 #[allow(non_snake_case)]
328 $($passes: $passes,)*
332 $v fn new() -> Self {
334 $($passes: $constructor,)*
339 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
340 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
343 impl LintPass for $name {
344 fn name(&self) -> &'static str {
348 fn get_lints(&self) -> LintArray {
349 let mut lints = Vec::new();
350 $(lints.extend_from_slice(&self.$passes.get_lints());)*
358 macro_rules! early_lint_methods {
359 ($macro:path, $args:tt) => (
361 fn check_ident(a: ast::Ident);
362 fn check_crate(a: &ast::Crate);
363 fn check_crate_post(a: &ast::Crate);
364 fn check_mod(a: &ast::Mod, b: Span, c: ast::NodeId);
365 fn check_mod_post(a: &ast::Mod, b: Span, c: ast::NodeId);
366 fn check_foreign_item(a: &ast::ForeignItem);
367 fn check_foreign_item_post(a: &ast::ForeignItem);
368 fn check_item(a: &ast::Item);
369 fn check_item_post(a: &ast::Item);
370 fn check_local(a: &ast::Local);
371 fn check_block(a: &ast::Block);
372 fn check_block_post(a: &ast::Block);
373 fn check_stmt(a: &ast::Stmt);
374 fn check_arm(a: &ast::Arm);
375 fn check_pat(a: &ast::Pat, b: &mut bool); // FIXME: &mut bool looks just broken
376 fn check_expr(a: &ast::Expr);
377 fn check_expr_post(a: &ast::Expr);
378 fn check_ty(a: &ast::Ty);
379 fn check_generic_param(a: &ast::GenericParam);
380 fn check_generics(a: &ast::Generics);
381 fn check_where_predicate(a: &ast::WherePredicate);
382 fn check_poly_trait_ref(a: &ast::PolyTraitRef,
383 b: &ast::TraitBoundModifier);
384 fn check_fn(a: syntax::visit::FnKind<'_>, b: &ast::FnDecl, c: Span, d_: ast::NodeId);
386 a: syntax::visit::FnKind<'_>,
391 fn check_trait_item(a: &ast::TraitItem);
392 fn check_trait_item_post(a: &ast::TraitItem);
393 fn check_impl_item(a: &ast::ImplItem);
394 fn check_impl_item_post(a: &ast::ImplItem);
396 a: &ast::VariantData,
401 fn check_struct_def_post(
402 a: &ast::VariantData,
407 fn check_struct_field(a: &ast::StructField);
408 fn check_variant(a: &ast::Variant, b: &ast::Generics);
409 fn check_variant_post(a: &ast::Variant, b: &ast::Generics);
410 fn check_lifetime(a: &ast::Lifetime);
411 fn check_path(a: &ast::Path, b: ast::NodeId);
412 fn check_attribute(a: &ast::Attribute);
413 fn check_mac_def(a: &ast::MacroDef, b: ast::NodeId);
414 fn check_mac(a: &ast::Mac);
416 /// Called when entering a syntax node that can have lint attributes such
417 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
418 fn enter_lint_attrs(a: &[ast::Attribute]);
420 /// Counterpart to `enter_lint_attrs`.
421 fn exit_lint_attrs(a: &[ast::Attribute]);
426 macro_rules! expand_early_lint_pass_methods {
427 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
428 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
432 macro_rules! declare_early_lint_pass {
433 ([], [$($methods:tt)*]) => (
434 pub trait EarlyLintPass: LintPass {
435 expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]);
440 early_lint_methods!(declare_early_lint_pass, []);
443 macro_rules! expand_combined_early_lint_pass_method {
444 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
445 $($self.$passes.$name $params;)*
450 macro_rules! expand_combined_early_lint_pass_methods {
451 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
452 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
453 expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
459 macro_rules! declare_combined_early_lint_pass {
460 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
461 #[allow(non_snake_case)]
463 $($passes: $passes,)*
467 $v fn new() -> Self {
469 $($passes: $constructor,)*
474 impl EarlyLintPass for $name {
475 expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
478 impl LintPass for $name {
479 fn name(&self) -> &'static str {
483 fn get_lints(&self) -> LintArray {
484 let mut lints = Vec::new();
485 $(lints.extend_from_slice(&self.$passes.get_lints());)*
492 /// A lint pass boxed up as a trait object.
493 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
494 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
495 + sync::Sync + 'static>;
499 /// Identifies a lint known to the compiler.
500 #[derive(Clone, Copy, Debug)]
502 // Identity is based on pointer equality of this field.
506 impl PartialEq for LintId {
507 fn eq(&self, other: &LintId) -> bool {
508 ptr::eq(self.lint, other.lint)
512 impl Eq for LintId { }
514 impl hash::Hash for LintId {
515 fn hash<H: hash::Hasher>(&self, state: &mut H) {
516 let ptr = self.lint as *const Lint;
522 /// Gets the `LintId` for a `Lint`.
523 pub fn of(lint: &'static Lint) -> LintId {
529 pub fn lint_name_raw(&self) -> &'static str {
533 /// Gets the name of the lint.
534 pub fn to_string(&self) -> String {
535 self.lint.name_lower()
539 /// Setting for how to handle a lint.
540 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
542 Allow, Warn, Deny, Forbid,
545 impl_stable_hash_for!(enum self::Level {
553 /// Converts a level to a lower-case string.
554 pub fn as_str(self) -> &'static str {
563 /// Converts a lower-case string to a level.
564 pub fn from_str(x: &str) -> Option<Level> {
566 "allow" => Some(Allow),
567 "warn" => Some(Warn),
568 "deny" => Some(Deny),
569 "forbid" => Some(Forbid),
575 /// How a lint level was set.
576 #[derive(Clone, Copy, PartialEq, Eq)]
577 pub enum LintSource {
578 /// Lint is at the default level as declared
579 /// in rustc or a plugin.
582 /// Lint level was set by an attribute.
583 Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
585 /// Lint level was set by a command-line flag.
589 impl_stable_hash_for!(enum self::LintSource {
591 Node(name, span, reason),
595 pub type LevelSource = (Level, LintSource);
602 pub use self::levels::{LintLevelSets, LintLevelMap};
605 pub struct LintBuffer {
606 map: NodeMap<Vec<BufferedEarlyLint>>,
610 pub fn add_lint(&mut self,
615 diagnostic: BuiltinLintDiagnostics) {
616 let early_lint = BufferedEarlyLint {
617 lint_id: LintId::of(lint),
620 msg: msg.to_string(),
623 let arr = self.map.entry(id).or_default();
624 if !arr.contains(&early_lint) {
625 arr.push(early_lint);
629 pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
630 self.map.remove(&id).unwrap_or_default()
633 pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
634 let key = self.map.keys().next().map(|k| *k);
635 key.map(|k| &self.map[&k][..])
639 pub fn struct_lint_level<'a>(sess: &'a Session,
643 span: Option<MultiSpan>,
645 -> DiagnosticBuilder<'a>
647 let mut err = match (level, span) {
648 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
649 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
650 (Level::Warn, None) => sess.struct_warn(msg),
651 (Level::Deny, Some(span)) |
652 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
653 (Level::Deny, None) |
654 (Level::Forbid, None) => sess.struct_err(msg),
657 let name = lint.name_lower();
659 LintSource::Default => {
662 DiagnosticMessageId::from(lint),
663 &format!("#[{}({})] on by default", level.as_str(), name));
665 LintSource::CommandLine(lint_flag_val) => {
666 let flag = match level {
669 Level::Forbid => "-F",
670 Level::Allow => panic!(),
672 let hyphen_case_lint_name = name.replace("_", "-");
673 if lint_flag_val.as_str() == name {
676 DiagnosticMessageId::from(lint),
677 &format!("requested on the command line with `{} {}`",
678 flag, hyphen_case_lint_name));
680 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
683 DiagnosticMessageId::from(lint),
684 &format!("`{} {}` implied by `{} {}`",
685 flag, hyphen_case_lint_name, flag,
686 hyphen_case_flag_val));
689 LintSource::Node(lint_attr_name, src, reason) => {
690 if let Some(rationale) = reason {
691 err.note(&rationale.as_str());
693 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
694 src, "lint level defined here");
695 if lint_attr_name.as_str() != name {
696 let level_str = level.as_str();
697 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
698 &format!("#[{}({})] implied by #[{}({})]",
699 level_str, name, level_str, lint_attr_name));
704 err.code(DiagnosticId::Lint(name));
706 // Check for future incompatibility lints and issue a stronger warning.
707 let lints = sess.lint_store.borrow();
708 let lint_id = LintId::of(lint);
709 let future_incompatible = lints.future_incompatible(lint_id);
710 if let Some(future_incompatible) = future_incompatible {
711 const STANDARD_MESSAGE: &str =
712 "this was previously accepted by the compiler but is being phased out; \
713 it will become a hard error";
715 let explanation = if lint_id == LintId::of(crate::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
716 "once this method is added to the standard library, \
717 the ambiguity may cause an error or change in behavior!"
719 } else if lint_id == LintId::of(crate::lint::builtin::MUTABLE_BORROW_RESERVATION_CONFLICT) {
720 "this borrowing pattern was not meant to be accepted, \
721 and may become a hard error in the future"
723 } else if let Some(edition) = future_incompatible.edition {
724 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
726 format!("{} in a future release!", STANDARD_MESSAGE)
728 let citation = format!("for more information, see {}",
729 future_incompatible.reference);
730 err.warn(&explanation);
734 // If this code originates in a foreign macro, aka something that this crate
735 // did not itself author, then it's likely that there's nothing this crate
736 // can do about it. We probably want to skip the lint entirely.
737 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
738 // Any suggestions made here are likely to be incorrect, so anything we
739 // emit shouldn't be automatically fixed by rustfix.
740 err.allow_suggestions(false);
742 // If this is a future incompatible lint it'll become a hard error, so
743 // we have to emit *something*. Also allow lints to whitelist themselves
744 // on a case-by-case basis for emission in a foreign macro.
745 if future_incompatible.is_none() && !lint.report_in_external_macro {
753 pub fn maybe_lint_level_root(tcx: TyCtxt<'_, '_, '_>, id: hir::HirId) -> bool {
754 let attrs = tcx.hir().attrs_by_hir_id(id);
755 attrs.iter().any(|attr| Level::from_str(&attr.name_or_empty()).is_some())
758 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
761 assert_eq!(cnum, LOCAL_CRATE);
762 let mut builder = LintLevelMapBuilder {
763 levels: LintLevelSets::builder(tcx.sess),
766 let krate = tcx.hir().krate();
768 let push = builder.levels.push(&krate.attrs);
769 builder.levels.register_id(hir::CRATE_HIR_ID);
770 intravisit::walk_crate(&mut builder, krate);
771 builder.levels.pop(push);
773 Lrc::new(builder.levels.build_map())
776 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
777 levels: levels::LintLevelsBuilder<'tcx>,
778 tcx: TyCtxt<'a, 'tcx, 'tcx>,
781 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
782 fn with_lint_attrs<F>(&mut self,
784 attrs: &[ast::Attribute],
786 where F: FnOnce(&mut Self)
788 let push = self.levels.push(attrs);
790 self.levels.register_id(id);
793 self.levels.pop(push);
797 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
798 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
799 intravisit::NestedVisitorMap::All(&self.tcx.hir())
802 fn visit_item(&mut self, it: &'tcx hir::Item) {
803 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
804 intravisit::walk_item(builder, it);
808 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
809 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
810 intravisit::walk_foreign_item(builder, it);
814 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
815 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
816 intravisit::walk_expr(builder, e);
820 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
821 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
822 intravisit::walk_struct_field(builder, s);
826 fn visit_variant(&mut self,
827 v: &'tcx hir::Variant,
828 g: &'tcx hir::Generics,
829 item_id: hir::HirId) {
830 self.with_lint_attrs(v.node.id, &v.node.attrs, |builder| {
831 intravisit::walk_variant(builder, v, g, item_id);
835 fn visit_local(&mut self, l: &'tcx hir::Local) {
836 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
837 intravisit::walk_local(builder, l);
841 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
842 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
843 intravisit::walk_trait_item(builder, trait_item);
847 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
848 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
849 intravisit::walk_impl_item(builder, impl_item);
854 pub fn provide(providers: &mut Providers<'_>) {
855 providers.lint_levels = lint_levels;
858 /// Returns whether `span` originates in a foreign crate's external macro.
860 /// This is used to test whether a lint should not even begin to figure out whether it should
861 /// be reported on the current node.
862 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
863 let info = match span.ctxt().outer().expn_info() {
865 // no ExpnInfo means this span doesn't come from a macro
866 None => return false,
870 ExpnFormat::MacroAttribute(..) => return true, // definitely a plugin
871 ExpnFormat::CompilerDesugaring(_) => return true, // well, it's "external"
872 ExpnFormat::MacroBang(..) => {} // check below
875 let def_site = match info.def_site {
877 // no span for the def_site means it's an external macro
881 match sess.source_map().span_to_snippet(def_site) {
882 Ok(code) => !code.starts_with("macro_rules"),
883 // no snippet = external macro or compiler-builtin expansion
888 /// Returns whether `span` originates in a derive macro's expansion
889 pub fn in_derive_expansion(span: Span) -> bool {
890 let info = match span.ctxt().outer().expn_info() {
892 // no ExpnInfo means this span doesn't come from a macro
893 None => return false,
897 ExpnFormat::MacroAttribute(symbol) => symbol.as_str().starts_with("derive("),