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::ext::base::MacroKind;
43 use syntax::symbol::{Symbol, sym};
46 pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore,
47 check_crate, check_ast_crate, late_lint_mod, CheckLintNameResult,
48 FutureIncompatibleInfo, BufferedEarlyLint,};
50 /// Specification of a single lint.
51 #[derive(Copy, Clone, Debug)]
53 /// A string identifier for the lint.
55 /// This identifies the lint in attributes and in command-line arguments.
56 /// In those contexts it is always lowercase, but this field is compared
57 /// in a way which is case-insensitive for ASCII characters. This allows
58 /// `declare_lint!()` invocations to follow the convention of upper-case
59 /// statics without repeating the name.
61 /// The name is written with underscores, e.g., "unused_imports".
62 /// On the command line, underscores become dashes.
63 pub name: &'static str,
65 /// Default level for the lint.
66 pub default_level: Level,
68 /// Description of the lint or the issue it detects.
70 /// e.g., "imports that are never used"
71 pub desc: &'static str,
73 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
75 pub edition_lint_opts: Option<(Edition, Level)>,
77 /// `true` if this lint is reported even inside expansions of external macros.
78 pub report_in_external_macro: bool,
82 /// Returns the `rust::lint::Lint` for a `syntax::early_buffered_lints::BufferedEarlyLintId`.
83 pub fn from_parser_lint_id(lint_id: BufferedEarlyLintId) -> &'static Self {
85 BufferedEarlyLintId::IllFormedAttributeInput => ILL_FORMED_ATTRIBUTE_INPUT,
86 BufferedEarlyLintId::MetaVariableMisuse => META_VARIABLE_MISUSE,
87 BufferedEarlyLintId::IncompleteInclude => INCOMPLETE_INCLUDE,
91 /// Gets the lint's name, with ASCII letters converted to lowercase.
92 pub fn name_lower(&self) -> String {
93 self.name.to_ascii_lowercase()
96 pub fn default_level(&self, session: &Session) -> Level {
97 self.edition_lint_opts
98 .filter(|(e, _)| *e <= session.edition())
100 .unwrap_or(self.default_level)
104 /// Declares a static item of type `&'static Lint`.
106 macro_rules! declare_lint {
107 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
108 declare_lint!{$vis $NAME, $Level, $desc, false}
110 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, report_in_external_macro: $rep: expr) => (
111 declare_lint!{$vis $NAME, $Level, $desc, $rep}
113 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, $external: expr) => (
114 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
115 name: stringify!($NAME),
116 default_level: $crate::lint::$Level,
118 edition_lint_opts: None,
119 report_in_external_macro: $external,
122 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
123 $lint_edition: expr => $edition_level: ident
125 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
126 name: stringify!($NAME),
127 default_level: $crate::lint::$Level,
129 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
130 report_in_external_macro: false,
136 macro_rules! declare_tool_lint {
138 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
140 declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
143 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
144 report_in_external_macro: $rep:expr
146 declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
149 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
153 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
154 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
155 default_level: $crate::lint::$Level,
157 edition_lint_opts: None,
158 report_in_external_macro: $external,
163 /// Declares a static `LintArray` and return it as an expression.
165 macro_rules! lint_array {
166 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
167 ($( $lint:expr ),*) => {{
172 pub type LintArray = Vec<&'static Lint>;
175 fn name(&self) -> &'static str;
177 /// Gets descriptions of the lints this `LintPass` object can emit.
179 /// N.B., there is no enforcement that the object only emits lints it registered.
180 /// And some `rustc` internal `LintPass`es register lints to be emitted by other
181 /// parts of the compiler. If you want enforced access restrictions for your
182 /// `Lint`, make it a private `static` item in its own module.
183 fn get_lints(&self) -> LintArray;
186 /// Implements `LintPass for $name` with the given list of `Lint` statics.
188 macro_rules! impl_lint_pass {
189 ($name:ident => [$($lint:expr),* $(,)?]) => {
190 impl LintPass for $name {
191 fn name(&self) -> &'static str { stringify!($name) }
192 fn get_lints(&self) -> LintArray { $crate::lint_array!($($lint),*) }
197 /// Declares a type named `$name` which implements `LintPass`.
198 /// To the right of `=>` a comma separated list of `Lint` statics is given.
200 macro_rules! declare_lint_pass {
201 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
202 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
203 $crate::impl_lint_pass!($name => [$($lint),*]);
208 macro_rules! late_lint_methods {
209 ($macro:path, $args:tt, [$hir:tt]) => (
210 $macro!($args, [$hir], [
211 fn check_param(a: &$hir hir::Param);
212 fn check_body(a: &$hir hir::Body);
213 fn check_body_post(a: &$hir hir::Body);
214 fn check_name(a: Span, b: ast::Name);
215 fn check_crate(a: &$hir hir::Crate);
216 fn check_crate_post(a: &$hir hir::Crate);
217 fn check_mod(a: &$hir hir::Mod, b: Span, c: hir::HirId);
218 fn check_mod_post(a: &$hir hir::Mod, b: Span, c: hir::HirId);
219 fn check_foreign_item(a: &$hir hir::ForeignItem);
220 fn check_foreign_item_post(a: &$hir hir::ForeignItem);
221 fn check_item(a: &$hir hir::Item);
222 fn check_item_post(a: &$hir hir::Item);
223 fn check_local(a: &$hir hir::Local);
224 fn check_block(a: &$hir hir::Block);
225 fn check_block_post(a: &$hir hir::Block);
226 fn check_stmt(a: &$hir hir::Stmt);
227 fn check_arm(a: &$hir hir::Arm);
228 fn check_pat(a: &$hir hir::Pat);
229 fn check_expr(a: &$hir hir::Expr);
230 fn check_expr_post(a: &$hir hir::Expr);
231 fn check_ty(a: &$hir hir::Ty);
232 fn check_generic_param(a: &$hir hir::GenericParam);
233 fn check_generics(a: &$hir hir::Generics);
234 fn check_where_predicate(a: &$hir hir::WherePredicate);
235 fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
237 a: hir::intravisit::FnKind<$hir>,
238 b: &$hir hir::FnDecl,
243 a: hir::intravisit::FnKind<$hir>,
244 b: &$hir hir::FnDecl,
249 fn check_trait_item(a: &$hir hir::TraitItem);
250 fn check_trait_item_post(a: &$hir hir::TraitItem);
251 fn check_impl_item(a: &$hir hir::ImplItem);
252 fn check_impl_item_post(a: &$hir hir::ImplItem);
253 fn check_struct_def(a: &$hir hir::VariantData);
254 fn check_struct_def_post(a: &$hir hir::VariantData);
255 fn check_struct_field(a: &$hir hir::StructField);
256 fn check_variant(a: &$hir hir::Variant);
257 fn check_variant_post(a: &$hir hir::Variant);
258 fn check_lifetime(a: &$hir hir::Lifetime);
259 fn check_path(a: &$hir hir::Path, b: hir::HirId);
260 fn check_attribute(a: &$hir ast::Attribute);
262 /// Called when entering a syntax node that can have lint attributes such
263 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
264 fn enter_lint_attrs(a: &$hir [ast::Attribute]);
266 /// Counterpart to `enter_lint_attrs`.
267 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
272 /// Trait for types providing lint checks.
274 /// Each `check` method checks a single syntax node, and should not
275 /// invoke methods recursively (unlike `Visitor`). By default they
278 // FIXME: eliminate the duplication with `Visitor`. But this also
279 // contains a few lint-specific methods with no equivalent in `Visitor`.
281 macro_rules! expand_lint_pass_methods {
282 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
283 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
287 macro_rules! declare_late_lint_pass {
288 ([], [$hir:tt], [$($methods:tt)*]) => (
289 pub trait LateLintPass<'a, $hir>: LintPass {
290 fn fresh_late_pass(&self) -> LateLintPassObject {
293 expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
298 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
301 macro_rules! expand_combined_late_lint_pass_method {
302 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
303 $($self.$passes.$name $params;)*
308 macro_rules! expand_combined_late_lint_pass_methods {
309 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
310 $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
311 expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
317 macro_rules! declare_combined_late_lint_pass {
318 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
319 #[allow(non_snake_case)]
321 $($passes: $passes,)*
325 $v fn new() -> Self {
327 $($passes: $constructor,)*
332 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
333 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
336 impl LintPass for $name {
337 fn name(&self) -> &'static str {
341 fn get_lints(&self) -> LintArray {
342 let mut lints = Vec::new();
343 $(lints.extend_from_slice(&self.$passes.get_lints());)*
351 macro_rules! early_lint_methods {
352 ($macro:path, $args:tt) => (
354 fn check_param(a: &ast::Param);
355 fn check_ident(a: ast::Ident);
356 fn check_crate(a: &ast::Crate);
357 fn check_crate_post(a: &ast::Crate);
358 fn check_mod(a: &ast::Mod, b: Span, c: ast::NodeId);
359 fn check_mod_post(a: &ast::Mod, b: Span, c: ast::NodeId);
360 fn check_foreign_item(a: &ast::ForeignItem);
361 fn check_foreign_item_post(a: &ast::ForeignItem);
362 fn check_item(a: &ast::Item);
363 fn check_item_post(a: &ast::Item);
364 fn check_local(a: &ast::Local);
365 fn check_block(a: &ast::Block);
366 fn check_block_post(a: &ast::Block);
367 fn check_stmt(a: &ast::Stmt);
368 fn check_arm(a: &ast::Arm);
369 fn check_pat(a: &ast::Pat);
370 fn check_pat_post(a: &ast::Pat);
371 fn check_expr(a: &ast::Expr);
372 fn check_expr_post(a: &ast::Expr);
373 fn check_ty(a: &ast::Ty);
374 fn check_generic_param(a: &ast::GenericParam);
375 fn check_generics(a: &ast::Generics);
376 fn check_where_predicate(a: &ast::WherePredicate);
377 fn check_poly_trait_ref(a: &ast::PolyTraitRef,
378 b: &ast::TraitBoundModifier);
379 fn check_fn(a: syntax::visit::FnKind<'_>, b: &ast::FnDecl, c: Span, d_: ast::NodeId);
381 a: syntax::visit::FnKind<'_>,
386 fn check_trait_item(a: &ast::TraitItem);
387 fn check_trait_item_post(a: &ast::TraitItem);
388 fn check_impl_item(a: &ast::ImplItem);
389 fn check_impl_item_post(a: &ast::ImplItem);
390 fn check_struct_def(a: &ast::VariantData);
391 fn check_struct_def_post(a: &ast::VariantData);
392 fn check_struct_field(a: &ast::StructField);
393 fn check_variant(a: &ast::Variant);
394 fn check_variant_post(a: &ast::Variant);
395 fn check_lifetime(a: &ast::Lifetime);
396 fn check_path(a: &ast::Path, b: ast::NodeId);
397 fn check_attribute(a: &ast::Attribute);
398 fn check_mac_def(a: &ast::MacroDef, b: ast::NodeId);
399 fn check_mac(a: &ast::Mac);
401 /// Called when entering a syntax node that can have lint attributes such
402 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
403 fn enter_lint_attrs(a: &[ast::Attribute]);
405 /// Counterpart to `enter_lint_attrs`.
406 fn exit_lint_attrs(a: &[ast::Attribute]);
411 macro_rules! expand_early_lint_pass_methods {
412 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
413 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
417 macro_rules! declare_early_lint_pass {
418 ([], [$($methods:tt)*]) => (
419 pub trait EarlyLintPass: LintPass {
420 expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]);
425 early_lint_methods!(declare_early_lint_pass, []);
428 macro_rules! expand_combined_early_lint_pass_method {
429 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
430 $($self.$passes.$name $params;)*
435 macro_rules! expand_combined_early_lint_pass_methods {
436 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
437 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
438 expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
444 macro_rules! declare_combined_early_lint_pass {
445 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
446 #[allow(non_snake_case)]
448 $($passes: $passes,)*
452 $v fn new() -> Self {
454 $($passes: $constructor,)*
459 impl EarlyLintPass for $name {
460 expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
463 impl LintPass for $name {
464 fn name(&self) -> &'static str {
468 fn get_lints(&self) -> LintArray {
469 let mut lints = Vec::new();
470 $(lints.extend_from_slice(&self.$passes.get_lints());)*
477 /// A lint pass boxed up as a trait object.
478 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
479 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
480 + sync::Sync + 'static>;
482 /// Identifies a lint known to the compiler.
483 #[derive(Clone, Copy, Debug)]
485 // Identity is based on pointer equality of this field.
489 impl PartialEq for LintId {
490 fn eq(&self, other: &LintId) -> bool {
491 ptr::eq(self.lint, other.lint)
495 impl Eq for LintId { }
497 impl hash::Hash for LintId {
498 fn hash<H: hash::Hasher>(&self, state: &mut H) {
499 let ptr = self.lint as *const Lint;
505 /// Gets the `LintId` for a `Lint`.
506 pub fn of(lint: &'static Lint) -> LintId {
512 pub fn lint_name_raw(&self) -> &'static str {
516 /// Gets the name of the lint.
517 pub fn to_string(&self) -> String {
518 self.lint.name_lower()
522 /// Setting for how to handle a lint.
523 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
525 Allow, Warn, Deny, Forbid,
528 impl_stable_hash_for!(enum self::Level {
536 /// Converts a level to a lower-case string.
537 pub fn as_str(self) -> &'static str {
546 /// Converts a lower-case string to a level.
547 pub fn from_str(x: &str) -> Option<Level> {
549 "allow" => Some(Allow),
550 "warn" => Some(Warn),
551 "deny" => Some(Deny),
552 "forbid" => Some(Forbid),
557 /// Converts a symbol to a level.
558 pub fn from_symbol(x: Symbol) -> Option<Level> {
560 sym::allow => Some(Allow),
561 sym::warn => Some(Warn),
562 sym::deny => Some(Deny),
563 sym::forbid => Some(Forbid),
569 /// How a lint level was set.
570 #[derive(Clone, Copy, PartialEq, Eq)]
571 pub enum LintSource {
572 /// Lint is at the default level as declared
573 /// in rustc or a plugin.
576 /// Lint level was set by an attribute.
577 Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
579 /// Lint level was set by a command-line flag.
583 impl_stable_hash_for!(enum self::LintSource {
585 Node(name, span, reason),
589 pub type LevelSource = (Level, LintSource);
596 pub use self::levels::{LintLevelSets, LintLevelMap};
599 pub struct LintBuffer {
600 map: NodeMap<Vec<BufferedEarlyLint>>,
604 pub fn add_lint(&mut self,
609 diagnostic: BuiltinLintDiagnostics) {
610 let early_lint = BufferedEarlyLint {
611 lint_id: LintId::of(lint),
614 msg: msg.to_string(),
617 let arr = self.map.entry(id).or_default();
618 if !arr.contains(&early_lint) {
619 arr.push(early_lint);
623 pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
624 self.map.remove(&id).unwrap_or_default()
627 pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
628 let key = self.map.keys().next().map(|k| *k);
629 key.map(|k| &self.map[&k][..])
633 pub fn struct_lint_level<'a>(sess: &'a Session,
637 span: Option<MultiSpan>,
639 -> DiagnosticBuilder<'a>
641 let mut err = match (level, span) {
642 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
643 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
644 (Level::Warn, None) => sess.struct_warn(msg),
645 (Level::Deny, Some(span)) |
646 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
647 (Level::Deny, None) |
648 (Level::Forbid, None) => sess.struct_err(msg),
651 // Check for future incompatibility lints and issue a stronger warning.
652 let lints = sess.lint_store.borrow();
653 let lint_id = LintId::of(lint);
654 let future_incompatible = lints.future_incompatible(lint_id);
656 // If this code originates in a foreign macro, aka something that this crate
657 // did not itself author, then it's likely that there's nothing this crate
658 // can do about it. We probably want to skip the lint entirely.
659 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
660 // Any suggestions made here are likely to be incorrect, so anything we
661 // emit shouldn't be automatically fixed by rustfix.
662 err.allow_suggestions(false);
664 // If this is a future incompatible lint it'll become a hard error, so
665 // we have to emit *something*. Also allow lints to whitelist themselves
666 // on a case-by-case basis for emission in a foreign macro.
667 if future_incompatible.is_none() && !lint.report_in_external_macro {
669 // Don't continue further, since we don't want to have
670 // `diag_span_note_once` called for a diagnostic that isn't emitted.
675 let name = lint.name_lower();
677 LintSource::Default => {
680 DiagnosticMessageId::from(lint),
681 &format!("`#[{}({})]` on by default", level.as_str(), name));
683 LintSource::CommandLine(lint_flag_val) => {
684 let flag = match level {
687 Level::Forbid => "-F",
688 Level::Allow => panic!(),
690 let hyphen_case_lint_name = name.replace("_", "-");
691 if lint_flag_val.as_str() == name {
694 DiagnosticMessageId::from(lint),
695 &format!("requested on the command line with `{} {}`",
696 flag, hyphen_case_lint_name));
698 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
701 DiagnosticMessageId::from(lint),
702 &format!("`{} {}` implied by `{} {}`",
703 flag, hyphen_case_lint_name, flag,
704 hyphen_case_flag_val));
707 LintSource::Node(lint_attr_name, src, reason) => {
708 if let Some(rationale) = reason {
709 err.note(&rationale.as_str());
711 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
712 src, "lint level defined here");
713 if lint_attr_name.as_str() != name {
714 let level_str = level.as_str();
715 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
716 &format!("`#[{}({})]` implied by `#[{}({})]`",
717 level_str, name, level_str, lint_attr_name));
722 err.code(DiagnosticId::Lint(name));
724 if let Some(future_incompatible) = future_incompatible {
725 const STANDARD_MESSAGE: &str =
726 "this was previously accepted by the compiler but is being phased out; \
727 it will become a hard error";
729 let explanation = if lint_id == LintId::of(builtin::UNSTABLE_NAME_COLLISIONS) {
730 "once this method is added to the standard library, \
731 the ambiguity may cause an error or change in behavior!"
733 } else if lint_id == LintId::of(builtin::MUTABLE_BORROW_RESERVATION_CONFLICT) {
734 "this borrowing pattern was not meant to be accepted, \
735 and may become a hard error in the future"
737 } else if let Some(edition) = future_incompatible.edition {
738 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
740 format!("{} in a future release!", STANDARD_MESSAGE)
742 let citation = format!("for more information, see {}",
743 future_incompatible.reference);
744 err.warn(&explanation);
751 pub fn maybe_lint_level_root(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
752 let attrs = tcx.hir().attrs(id);
753 attrs.iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some())
756 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap {
757 assert_eq!(cnum, LOCAL_CRATE);
758 let mut builder = LintLevelMapBuilder {
759 levels: LintLevelSets::builder(tcx.sess),
762 let krate = tcx.hir().krate();
764 let push = builder.levels.push(&krate.attrs);
765 builder.levels.register_id(hir::CRATE_HIR_ID);
766 for macro_def in &krate.exported_macros {
767 builder.levels.register_id(macro_def.hir_id);
769 intravisit::walk_crate(&mut builder, krate);
770 builder.levels.pop(push);
772 tcx.arena.alloc(builder.levels.build_map())
775 struct LintLevelMapBuilder<'tcx> {
776 levels: levels::LintLevelsBuilder<'tcx>,
780 impl LintLevelMapBuilder<'tcx> {
781 fn with_lint_attrs<F>(&mut self,
783 attrs: &[ast::Attribute],
785 where F: FnOnce(&mut Self)
787 let push = self.levels.push(attrs);
789 self.levels.register_id(id);
792 self.levels.pop(push);
796 impl intravisit::Visitor<'tcx> for LintLevelMapBuilder<'tcx> {
797 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
798 intravisit::NestedVisitorMap::All(&self.tcx.hir())
801 fn visit_param(&mut self, param: &'tcx hir::Param) {
802 self.with_lint_attrs(param.hir_id, ¶m.attrs, |builder| {
803 intravisit::walk_param(builder, param);
807 fn visit_item(&mut self, it: &'tcx hir::Item) {
808 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
809 intravisit::walk_item(builder, it);
813 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
814 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
815 intravisit::walk_foreign_item(builder, it);
819 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
820 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
821 intravisit::walk_expr(builder, e);
825 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
826 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
827 intravisit::walk_struct_field(builder, s);
831 fn visit_variant(&mut self,
832 v: &'tcx hir::Variant,
833 g: &'tcx hir::Generics,
834 item_id: hir::HirId) {
835 self.with_lint_attrs(v.id, &v.attrs, |builder| {
836 intravisit::walk_variant(builder, v, g, item_id);
840 fn visit_local(&mut self, l: &'tcx hir::Local) {
841 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
842 intravisit::walk_local(builder, l);
846 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
847 self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
848 intravisit::walk_arm(builder, a);
852 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
853 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
854 intravisit::walk_trait_item(builder, trait_item);
858 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
859 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
860 intravisit::walk_impl_item(builder, impl_item);
865 pub fn provide(providers: &mut Providers<'_>) {
866 providers.lint_levels = lint_levels;
869 /// Returns whether `span` originates in a foreign crate's external macro.
871 /// This is used to test whether a lint should not even begin to figure out whether it should
872 /// be reported on the current node.
873 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
874 let expn_data = span.ctxt().outer_expn_data();
875 match expn_data.kind {
876 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
877 ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
878 ExpnKind::Macro(MacroKind::Bang, _) => {
879 if expn_data.def_site.is_dummy() {
880 // Dummy span for the `def_site` means it's an external macro.
883 match sess.source_map().span_to_snippet(expn_data.def_site) {
884 Ok(code) => !code.starts_with("macro_rules"),
885 // No snippet means external macro or compiler-builtin expansion.
889 ExpnKind::Macro(..) => true, // definitely a plugin
893 /// Returns `true` if `span` originates in a derive-macro's expansion.
894 pub fn in_derive_expansion(span: Span) -> bool {
895 if let ExpnKind::Macro(MacroKind::Derive, _) = span.ctxt().outer_expn_data().kind {