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::lint::builtin::parser::{ILL_FORMED_ATTRIBUTE_INPUT, META_VARIABLE_MISUSE};
31 use crate::lint::builtin::parser::INCOMPLETE_INCLUDE;
32 use crate::session::{Session, DiagnosticMessageId};
33 use crate::ty::TyCtxt;
34 use crate::ty::query::Providers;
35 use crate::util::nodemap::NodeMap;
36 use errors::{DiagnosticBuilder, DiagnosticId};
39 use syntax::source_map::{MultiSpan, ExpnKind, DesugaringKind};
40 use syntax::early_buffered_lints::BufferedEarlyLintId;
41 use syntax::edition::Edition;
42 use syntax::symbol::Symbol;
43 use syntax_pos::hygiene::MacroKind;
46 pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore,
47 check_crate, check_ast_crate, late_lint_mod, CheckLintNameResult,
50 pub use rustc_session::lint::Level;
52 /// Specification of a single lint.
53 #[derive(Copy, Clone, Debug)]
55 /// A string identifier for the lint.
57 /// This identifies the lint in attributes and in command-line arguments.
58 /// In those contexts it is always lowercase, but this field is compared
59 /// in a way which is case-insensitive for ASCII characters. This allows
60 /// `declare_lint!()` invocations to follow the convention of upper-case
61 /// statics without repeating the name.
63 /// The name is written with underscores, e.g., "unused_imports".
64 /// On the command line, underscores become dashes.
65 pub name: &'static str,
67 /// Default level for the lint.
68 pub default_level: Level,
70 /// Description of the lint or the issue it detects.
72 /// e.g., "imports that are never used"
73 pub desc: &'static str,
75 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
77 pub edition_lint_opts: Option<(Edition, Level)>,
79 /// `true` if this lint is reported even inside expansions of external macros.
80 pub report_in_external_macro: bool,
82 pub future_incompatible: Option<FutureIncompatibleInfo>,
87 /// Extra information for a future incompatibility lint.
88 #[derive(Copy, Clone, Debug)]
89 pub struct FutureIncompatibleInfo {
90 /// e.g., a URL for an issue/PR/RFC or error code
91 pub reference: &'static str,
92 /// If this is an edition fixing lint, the edition in which
93 /// this lint becomes obsolete
94 pub edition: Option<Edition>,
98 pub const fn default_fields_for_macro() -> Self {
101 default_level: Level::Forbid,
103 edition_lint_opts: None,
105 report_in_external_macro: false,
106 future_incompatible: None,
110 /// Returns the `rust::lint::Lint` for a `syntax::early_buffered_lints::BufferedEarlyLintId`.
111 pub fn from_parser_lint_id(lint_id: BufferedEarlyLintId) -> &'static Self {
113 BufferedEarlyLintId::IllFormedAttributeInput => ILL_FORMED_ATTRIBUTE_INPUT,
114 BufferedEarlyLintId::MetaVariableMisuse => META_VARIABLE_MISUSE,
115 BufferedEarlyLintId::IncompleteInclude => INCOMPLETE_INCLUDE,
119 /// Gets the lint's name, with ASCII letters converted to lowercase.
120 pub fn name_lower(&self) -> String {
121 self.name.to_ascii_lowercase()
124 pub fn default_level(&self, session: &Session) -> Level {
125 self.edition_lint_opts
126 .filter(|(e, _)| *e <= session.edition())
128 .unwrap_or(self.default_level)
132 /// Declares a static item of type `&'static Lint`.
134 macro_rules! declare_lint {
135 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
137 $vis $NAME, $Level, $desc,
140 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
141 $(@future_incompatible = $fi:expr;)? $($v:ident),*) => (
142 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
143 name: stringify!($NAME),
144 default_level: $crate::lint::$Level,
146 edition_lint_opts: None,
149 $(future_incompatible: Some($fi),)*
150 ..$crate::lint::Lint::default_fields_for_macro()
153 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
154 $lint_edition: expr => $edition_level: ident
156 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
157 name: stringify!($NAME),
158 default_level: $crate::lint::$Level,
160 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
161 report_in_external_macro: false,
168 macro_rules! declare_tool_lint {
170 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
172 declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
175 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
176 report_in_external_macro: $rep:expr
178 declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
181 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
185 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
186 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
187 default_level: $crate::lint::$Level,
189 edition_lint_opts: None,
190 report_in_external_macro: $external,
191 future_incompatible: None,
197 /// Declares a static `LintArray` and return it as an expression.
199 macro_rules! lint_array {
200 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
201 ($( $lint:expr ),*) => {{
206 pub type LintArray = Vec<&'static Lint>;
209 fn name(&self) -> &'static str;
212 /// Implements `LintPass for $name` with the given list of `Lint` statics.
214 macro_rules! impl_lint_pass {
215 ($name:ident => [$($lint:expr),* $(,)?]) => {
216 impl LintPass for $name {
217 fn name(&self) -> &'static str { stringify!($name) }
220 pub fn get_lints() -> LintArray { $crate::lint_array!($($lint),*) }
225 /// Declares a type named `$name` which implements `LintPass`.
226 /// To the right of `=>` a comma separated list of `Lint` statics is given.
228 macro_rules! declare_lint_pass {
229 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
230 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
231 $crate::impl_lint_pass!($name => [$($lint),*]);
236 macro_rules! late_lint_methods {
237 ($macro:path, $args:tt, [$hir:tt]) => (
238 $macro!($args, [$hir], [
239 fn check_param(a: &$hir hir::Param);
240 fn check_body(a: &$hir hir::Body);
241 fn check_body_post(a: &$hir hir::Body);
242 fn check_name(a: Span, b: ast::Name);
243 fn check_crate(a: &$hir hir::Crate);
244 fn check_crate_post(a: &$hir hir::Crate);
245 fn check_mod(a: &$hir hir::Mod, b: Span, c: hir::HirId);
246 fn check_mod_post(a: &$hir hir::Mod, b: Span, c: hir::HirId);
247 fn check_foreign_item(a: &$hir hir::ForeignItem);
248 fn check_foreign_item_post(a: &$hir hir::ForeignItem);
249 fn check_item(a: &$hir hir::Item);
250 fn check_item_post(a: &$hir hir::Item);
251 fn check_local(a: &$hir hir::Local);
252 fn check_block(a: &$hir hir::Block);
253 fn check_block_post(a: &$hir hir::Block);
254 fn check_stmt(a: &$hir hir::Stmt);
255 fn check_arm(a: &$hir hir::Arm);
256 fn check_pat(a: &$hir hir::Pat);
257 fn check_expr(a: &$hir hir::Expr);
258 fn check_expr_post(a: &$hir hir::Expr);
259 fn check_ty(a: &$hir hir::Ty);
260 fn check_generic_param(a: &$hir hir::GenericParam);
261 fn check_generics(a: &$hir hir::Generics);
262 fn check_where_predicate(a: &$hir hir::WherePredicate);
263 fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
265 a: hir::intravisit::FnKind<$hir>,
266 b: &$hir hir::FnDecl,
271 a: hir::intravisit::FnKind<$hir>,
272 b: &$hir hir::FnDecl,
277 fn check_trait_item(a: &$hir hir::TraitItem);
278 fn check_trait_item_post(a: &$hir hir::TraitItem);
279 fn check_impl_item(a: &$hir hir::ImplItem);
280 fn check_impl_item_post(a: &$hir hir::ImplItem);
281 fn check_struct_def(a: &$hir hir::VariantData);
282 fn check_struct_def_post(a: &$hir hir::VariantData);
283 fn check_struct_field(a: &$hir hir::StructField);
284 fn check_variant(a: &$hir hir::Variant);
285 fn check_variant_post(a: &$hir hir::Variant);
286 fn check_lifetime(a: &$hir hir::Lifetime);
287 fn check_path(a: &$hir hir::Path, b: hir::HirId);
288 fn check_attribute(a: &$hir ast::Attribute);
290 /// Called when entering a syntax node that can have lint attributes such
291 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
292 fn enter_lint_attrs(a: &$hir [ast::Attribute]);
294 /// Counterpart to `enter_lint_attrs`.
295 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
300 /// Trait for types providing lint checks.
302 /// Each `check` method checks a single syntax node, and should not
303 /// invoke methods recursively (unlike `Visitor`). By default they
306 // FIXME: eliminate the duplication with `Visitor`. But this also
307 // contains a few lint-specific methods with no equivalent in `Visitor`.
309 macro_rules! expand_lint_pass_methods {
310 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
311 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
315 macro_rules! declare_late_lint_pass {
316 ([], [$hir:tt], [$($methods:tt)*]) => (
317 pub trait LateLintPass<'a, $hir>: LintPass {
318 expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
323 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
326 macro_rules! expand_combined_late_lint_pass_method {
327 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
328 $($self.$passes.$name $params;)*
333 macro_rules! expand_combined_late_lint_pass_methods {
334 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
335 $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
336 expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
342 macro_rules! declare_combined_late_lint_pass {
343 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
344 #[allow(non_snake_case)]
346 $($passes: $passes,)*
350 $v fn new() -> Self {
352 $($passes: $constructor,)*
356 $v fn get_lints() -> LintArray {
357 let mut lints = Vec::new();
358 $(lints.extend_from_slice(&$passes::get_lints());)*
363 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
364 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
367 impl LintPass for $name {
368 fn name(&self) -> &'static str {
376 macro_rules! early_lint_methods {
377 ($macro:path, $args:tt) => (
379 fn check_param(a: &ast::Param);
380 fn check_ident(a: ast::Ident);
381 fn check_crate(a: &ast::Crate);
382 fn check_crate_post(a: &ast::Crate);
383 fn check_mod(a: &ast::Mod, b: Span, c: ast::NodeId);
384 fn check_mod_post(a: &ast::Mod, b: Span, c: ast::NodeId);
385 fn check_foreign_item(a: &ast::ForeignItem);
386 fn check_foreign_item_post(a: &ast::ForeignItem);
387 fn check_item(a: &ast::Item);
388 fn check_item_post(a: &ast::Item);
389 fn check_local(a: &ast::Local);
390 fn check_block(a: &ast::Block);
391 fn check_block_post(a: &ast::Block);
392 fn check_stmt(a: &ast::Stmt);
393 fn check_arm(a: &ast::Arm);
394 fn check_pat(a: &ast::Pat);
395 fn check_pat_post(a: &ast::Pat);
396 fn check_expr(a: &ast::Expr);
397 fn check_expr_post(a: &ast::Expr);
398 fn check_ty(a: &ast::Ty);
399 fn check_generic_param(a: &ast::GenericParam);
400 fn check_generics(a: &ast::Generics);
401 fn check_where_predicate(a: &ast::WherePredicate);
402 fn check_poly_trait_ref(a: &ast::PolyTraitRef,
403 b: &ast::TraitBoundModifier);
404 fn check_fn(a: syntax::visit::FnKind<'_>, b: &ast::FnDecl, c: Span, d_: ast::NodeId);
406 a: syntax::visit::FnKind<'_>,
411 fn check_trait_item(a: &ast::TraitItem);
412 fn check_trait_item_post(a: &ast::TraitItem);
413 fn check_impl_item(a: &ast::ImplItem);
414 fn check_impl_item_post(a: &ast::ImplItem);
415 fn check_struct_def(a: &ast::VariantData);
416 fn check_struct_def_post(a: &ast::VariantData);
417 fn check_struct_field(a: &ast::StructField);
418 fn check_variant(a: &ast::Variant);
419 fn check_variant_post(a: &ast::Variant);
420 fn check_lifetime(a: &ast::Lifetime);
421 fn check_path(a: &ast::Path, b: ast::NodeId);
422 fn check_attribute(a: &ast::Attribute);
423 fn check_mac_def(a: &ast::MacroDef, b: ast::NodeId);
424 fn check_mac(a: &ast::Mac);
426 /// Called when entering a syntax node that can have lint attributes such
427 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
428 fn enter_lint_attrs(a: &[ast::Attribute]);
430 /// Counterpart to `enter_lint_attrs`.
431 fn exit_lint_attrs(a: &[ast::Attribute]);
436 macro_rules! expand_early_lint_pass_methods {
437 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
438 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
442 macro_rules! declare_early_lint_pass {
443 ([], [$($methods:tt)*]) => (
444 pub trait EarlyLintPass: LintPass {
445 expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]);
450 early_lint_methods!(declare_early_lint_pass, []);
453 macro_rules! expand_combined_early_lint_pass_method {
454 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
455 $($self.$passes.$name $params;)*
460 macro_rules! expand_combined_early_lint_pass_methods {
461 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
462 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
463 expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
469 macro_rules! declare_combined_early_lint_pass {
470 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
471 #[allow(non_snake_case)]
473 $($passes: $passes,)*
477 $v fn new() -> Self {
479 $($passes: $constructor,)*
483 $v fn get_lints() -> LintArray {
484 let mut lints = Vec::new();
485 $(lints.extend_from_slice(&$passes::get_lints());)*
490 impl EarlyLintPass for $name {
491 expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
494 impl LintPass for $name {
495 fn name(&self) -> &'static str {
502 /// A lint pass boxed up as a trait object.
503 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
504 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
505 + sync::Sync + 'static>;
507 /// Identifies a lint known to the compiler.
508 #[derive(Clone, Copy, Debug)]
510 // Identity is based on pointer equality of this field.
514 impl PartialEq for LintId {
515 fn eq(&self, other: &LintId) -> bool {
516 ptr::eq(self.lint, other.lint)
520 impl Eq for LintId { }
522 impl hash::Hash for LintId {
523 fn hash<H: hash::Hasher>(&self, state: &mut H) {
524 let ptr = self.lint as *const Lint;
530 /// Gets the `LintId` for a `Lint`.
531 pub fn of(lint: &'static Lint) -> LintId {
537 pub fn lint_name_raw(&self) -> &'static str {
541 /// Gets the name of the lint.
542 pub fn to_string(&self) -> String {
543 self.lint.name_lower()
547 /// How a lint level was set.
548 #[derive(Clone, Copy, PartialEq, Eq, HashStable)]
549 pub enum LintSource {
550 /// Lint is at the default level as declared
551 /// in rustc or a plugin.
554 /// Lint level was set by an attribute.
555 Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
557 /// Lint level was set by a command-line flag.
561 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 fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
596 self.map.remove(&id).unwrap_or_default()
599 pub fn buffer_lint<S: Into<MultiSpan>>(
606 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
609 pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(
615 diagnostic: BuiltinLintDiagnostics,
617 self.add_lint(lint, id, sp.into(), msg, diagnostic)
621 pub fn struct_lint_level<'a>(sess: &'a Session,
625 span: Option<MultiSpan>,
627 -> DiagnosticBuilder<'a>
629 let mut err = match (level, span) {
630 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
631 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
632 (Level::Warn, None) => sess.struct_warn(msg),
633 (Level::Deny, Some(span)) |
634 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
635 (Level::Deny, None) |
636 (Level::Forbid, None) => sess.struct_err(msg),
639 // Check for future incompatibility lints and issue a stronger warning.
640 let lint_id = LintId::of(lint);
641 let future_incompatible = lint.future_incompatible;
643 // If this code originates in a foreign macro, aka something that this crate
644 // did not itself author, then it's likely that there's nothing this crate
645 // can do about it. We probably want to skip the lint entirely.
646 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
647 // Any suggestions made here are likely to be incorrect, so anything we
648 // emit shouldn't be automatically fixed by rustfix.
649 err.allow_suggestions(false);
651 // If this is a future incompatible lint it'll become a hard error, so
652 // we have to emit *something*. Also allow lints to whitelist themselves
653 // on a case-by-case basis for emission in a foreign macro.
654 if future_incompatible.is_none() && !lint.report_in_external_macro {
656 // Don't continue further, since we don't want to have
657 // `diag_span_note_once` called for a diagnostic that isn't emitted.
662 let name = lint.name_lower();
664 LintSource::Default => {
667 DiagnosticMessageId::from(lint),
668 &format!("`#[{}({})]` on by default", level.as_str(), name));
670 LintSource::CommandLine(lint_flag_val) => {
671 let flag = match level {
674 Level::Forbid => "-F",
675 Level::Allow => panic!(),
677 let hyphen_case_lint_name = name.replace("_", "-");
678 if lint_flag_val.as_str() == name {
681 DiagnosticMessageId::from(lint),
682 &format!("requested on the command line with `{} {}`",
683 flag, hyphen_case_lint_name));
685 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
688 DiagnosticMessageId::from(lint),
689 &format!("`{} {}` implied by `{} {}`",
690 flag, hyphen_case_lint_name, flag,
691 hyphen_case_flag_val));
694 LintSource::Node(lint_attr_name, src, reason) => {
695 if let Some(rationale) = reason {
696 err.note(&rationale.as_str());
698 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
699 src, "lint level defined here");
700 if lint_attr_name.as_str() != name {
701 let level_str = level.as_str();
702 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
703 &format!("`#[{}({})]` implied by `#[{}({})]`",
704 level_str, name, level_str, lint_attr_name));
709 err.code(DiagnosticId::Lint(name));
711 if let Some(future_incompatible) = future_incompatible {
712 const STANDARD_MESSAGE: &str =
713 "this was previously accepted by the compiler but is being phased out; \
714 it will become a hard error";
716 let explanation = if lint_id == LintId::of(builtin::UNSTABLE_NAME_COLLISIONS) {
717 "once this method is added to the standard library, \
718 the ambiguity may cause an error or change in behavior!"
720 } else if lint_id == LintId::of(builtin::MUTABLE_BORROW_RESERVATION_CONFLICT) {
721 "this borrowing pattern was not meant to be accepted, \
722 and may become a hard error in the future"
724 } else if let Some(edition) = future_incompatible.edition {
725 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
727 format!("{} in a future release!", STANDARD_MESSAGE)
729 let citation = format!("for more information, see {}",
730 future_incompatible.reference);
731 err.warn(&explanation);
738 pub fn maybe_lint_level_root(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
739 let attrs = tcx.hir().attrs(id);
740 attrs.iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some())
743 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap {
744 assert_eq!(cnum, LOCAL_CRATE);
745 let store = &tcx.lint_store;
746 let mut builder = LintLevelMapBuilder {
747 levels: LintLevelSets::builder(tcx.sess, false, &store),
751 let krate = tcx.hir().krate();
753 let push = builder.levels.push(&krate.attrs, &store);
754 builder.levels.register_id(hir::CRATE_HIR_ID);
755 for macro_def in &krate.exported_macros {
756 builder.levels.register_id(macro_def.hir_id);
758 intravisit::walk_crate(&mut builder, krate);
759 builder.levels.pop(push);
761 tcx.arena.alloc(builder.levels.build_map())
764 struct LintLevelMapBuilder<'a, 'tcx> {
765 levels: levels::LintLevelsBuilder<'tcx>,
767 store: &'a LintStore,
770 impl LintLevelMapBuilder<'_, '_> {
771 fn with_lint_attrs<F>(&mut self,
773 attrs: &[ast::Attribute],
775 where F: FnOnce(&mut Self)
777 let push = self.levels.push(attrs, self.store);
779 self.levels.register_id(id);
782 self.levels.pop(push);
786 impl intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
787 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
788 intravisit::NestedVisitorMap::All(&self.tcx.hir())
791 fn visit_param(&mut self, param: &'tcx hir::Param) {
792 self.with_lint_attrs(param.hir_id, ¶m.attrs, |builder| {
793 intravisit::walk_param(builder, param);
797 fn visit_item(&mut self, it: &'tcx hir::Item) {
798 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
799 intravisit::walk_item(builder, it);
803 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
804 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
805 intravisit::walk_foreign_item(builder, it);
809 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
810 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
811 intravisit::walk_expr(builder, e);
815 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
816 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
817 intravisit::walk_struct_field(builder, s);
821 fn visit_variant(&mut self,
822 v: &'tcx hir::Variant,
823 g: &'tcx hir::Generics,
824 item_id: hir::HirId) {
825 self.with_lint_attrs(v.id, &v.attrs, |builder| {
826 intravisit::walk_variant(builder, v, g, item_id);
830 fn visit_local(&mut self, l: &'tcx hir::Local) {
831 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
832 intravisit::walk_local(builder, l);
836 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
837 self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
838 intravisit::walk_arm(builder, a);
842 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
843 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
844 intravisit::walk_trait_item(builder, trait_item);
848 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
849 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
850 intravisit::walk_impl_item(builder, impl_item);
855 pub fn provide(providers: &mut Providers<'_>) {
856 providers.lint_levels = lint_levels;
859 /// Returns whether `span` originates in a foreign crate's external macro.
861 /// This is used to test whether a lint should not even begin to figure out whether it should
862 /// be reported on the current node.
863 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
864 let expn_data = span.ctxt().outer_expn_data();
865 match expn_data.kind {
866 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
867 ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
868 ExpnKind::Macro(MacroKind::Bang, _) => {
869 if expn_data.def_site.is_dummy() {
870 // Dummy span for the `def_site` means it's an external macro.
873 match sess.source_map().span_to_snippet(expn_data.def_site) {
874 Ok(code) => !code.starts_with("macro_rules"),
875 // No snippet means external macro or compiler-builtin expansion.
879 ExpnKind::Macro(..) => true, // definitely a plugin
883 /// Returns `true` if `span` originates in a derive-macro's expansion.
884 pub fn in_derive_expansion(span: Span) -> bool {
885 if let ExpnKind::Macro(MacroKind::Derive, _) = span.ctxt().outer_expn_data().kind {