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_expand::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,
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,
80 pub future_incompatible: Option<FutureIncompatibleInfo>,
85 /// Extra information for a future incompatibility lint.
86 #[derive(Copy, Clone, Debug)]
87 pub struct FutureIncompatibleInfo {
88 /// e.g., a URL for an issue/PR/RFC or error code
89 pub reference: &'static str,
90 /// If this is an edition fixing lint, the edition in which
91 /// this lint becomes obsolete
92 pub edition: Option<Edition>,
96 pub const fn default_fields_for_macro() -> Self {
99 default_level: Level::Forbid,
101 edition_lint_opts: None,
103 report_in_external_macro: false,
104 future_incompatible: None,
108 /// Returns the `rust::lint::Lint` for a `syntax::early_buffered_lints::BufferedEarlyLintId`.
109 pub fn from_parser_lint_id(lint_id: BufferedEarlyLintId) -> &'static Self {
111 BufferedEarlyLintId::IllFormedAttributeInput => ILL_FORMED_ATTRIBUTE_INPUT,
112 BufferedEarlyLintId::MetaVariableMisuse => META_VARIABLE_MISUSE,
113 BufferedEarlyLintId::IncompleteInclude => INCOMPLETE_INCLUDE,
117 /// Gets the lint's name, with ASCII letters converted to lowercase.
118 pub fn name_lower(&self) -> String {
119 self.name.to_ascii_lowercase()
122 pub fn default_level(&self, session: &Session) -> Level {
123 self.edition_lint_opts
124 .filter(|(e, _)| *e <= session.edition())
126 .unwrap_or(self.default_level)
130 /// Declares a static item of type `&'static Lint`.
132 macro_rules! declare_lint {
133 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
135 $vis $NAME, $Level, $desc,
138 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
139 $(@future_incompatible = $fi:expr;)? $($v:ident),*) => (
140 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
141 name: stringify!($NAME),
142 default_level: $crate::lint::$Level,
144 edition_lint_opts: None,
147 $(future_incompatible: Some($fi),)*
148 ..$crate::lint::Lint::default_fields_for_macro()
151 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
152 $lint_edition: expr => $edition_level: ident
154 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
155 name: stringify!($NAME),
156 default_level: $crate::lint::$Level,
158 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
159 report_in_external_macro: false,
166 macro_rules! declare_tool_lint {
168 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
170 declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
173 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
174 report_in_external_macro: $rep:expr
176 declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
179 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
183 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
184 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
185 default_level: $crate::lint::$Level,
187 edition_lint_opts: None,
188 report_in_external_macro: $external,
189 future_incompatible: None,
195 /// Declares a static `LintArray` and return it as an expression.
197 macro_rules! lint_array {
198 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
199 ($( $lint:expr ),*) => {{
204 pub type LintArray = Vec<&'static Lint>;
207 fn name(&self) -> &'static str;
210 /// Implements `LintPass for $name` with the given list of `Lint` statics.
212 macro_rules! impl_lint_pass {
213 ($name:ident => [$($lint:expr),* $(,)?]) => {
214 impl LintPass for $name {
215 fn name(&self) -> &'static str { stringify!($name) }
218 pub fn get_lints() -> LintArray { $crate::lint_array!($($lint),*) }
223 /// Declares a type named `$name` which implements `LintPass`.
224 /// To the right of `=>` a comma separated list of `Lint` statics is given.
226 macro_rules! declare_lint_pass {
227 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
228 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
229 $crate::impl_lint_pass!($name => [$($lint),*]);
234 macro_rules! late_lint_methods {
235 ($macro:path, $args:tt, [$hir:tt]) => (
236 $macro!($args, [$hir], [
237 fn check_param(a: &$hir hir::Param);
238 fn check_body(a: &$hir hir::Body);
239 fn check_body_post(a: &$hir hir::Body);
240 fn check_name(a: Span, b: ast::Name);
241 fn check_crate(a: &$hir hir::Crate);
242 fn check_crate_post(a: &$hir hir::Crate);
243 fn check_mod(a: &$hir hir::Mod, b: Span, c: hir::HirId);
244 fn check_mod_post(a: &$hir hir::Mod, b: Span, c: hir::HirId);
245 fn check_foreign_item(a: &$hir hir::ForeignItem);
246 fn check_foreign_item_post(a: &$hir hir::ForeignItem);
247 fn check_item(a: &$hir hir::Item);
248 fn check_item_post(a: &$hir hir::Item);
249 fn check_local(a: &$hir hir::Local);
250 fn check_block(a: &$hir hir::Block);
251 fn check_block_post(a: &$hir hir::Block);
252 fn check_stmt(a: &$hir hir::Stmt);
253 fn check_arm(a: &$hir hir::Arm);
254 fn check_pat(a: &$hir hir::Pat);
255 fn check_expr(a: &$hir hir::Expr);
256 fn check_expr_post(a: &$hir hir::Expr);
257 fn check_ty(a: &$hir hir::Ty);
258 fn check_generic_param(a: &$hir hir::GenericParam);
259 fn check_generics(a: &$hir hir::Generics);
260 fn check_where_predicate(a: &$hir hir::WherePredicate);
261 fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
263 a: hir::intravisit::FnKind<$hir>,
264 b: &$hir hir::FnDecl,
269 a: hir::intravisit::FnKind<$hir>,
270 b: &$hir hir::FnDecl,
275 fn check_trait_item(a: &$hir hir::TraitItem);
276 fn check_trait_item_post(a: &$hir hir::TraitItem);
277 fn check_impl_item(a: &$hir hir::ImplItem);
278 fn check_impl_item_post(a: &$hir hir::ImplItem);
279 fn check_struct_def(a: &$hir hir::VariantData);
280 fn check_struct_def_post(a: &$hir hir::VariantData);
281 fn check_struct_field(a: &$hir hir::StructField);
282 fn check_variant(a: &$hir hir::Variant);
283 fn check_variant_post(a: &$hir hir::Variant);
284 fn check_lifetime(a: &$hir hir::Lifetime);
285 fn check_path(a: &$hir hir::Path, b: hir::HirId);
286 fn check_attribute(a: &$hir ast::Attribute);
288 /// Called when entering a syntax node that can have lint attributes such
289 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
290 fn enter_lint_attrs(a: &$hir [ast::Attribute]);
292 /// Counterpart to `enter_lint_attrs`.
293 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
298 /// Trait for types providing lint checks.
300 /// Each `check` method checks a single syntax node, and should not
301 /// invoke methods recursively (unlike `Visitor`). By default they
304 // FIXME: eliminate the duplication with `Visitor`. But this also
305 // contains a few lint-specific methods with no equivalent in `Visitor`.
307 macro_rules! expand_lint_pass_methods {
308 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
309 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
313 macro_rules! declare_late_lint_pass {
314 ([], [$hir:tt], [$($methods:tt)*]) => (
315 pub trait LateLintPass<'a, $hir>: LintPass {
316 expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
321 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
324 macro_rules! expand_combined_late_lint_pass_method {
325 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
326 $($self.$passes.$name $params;)*
331 macro_rules! expand_combined_late_lint_pass_methods {
332 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
333 $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
334 expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
340 macro_rules! declare_combined_late_lint_pass {
341 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
342 #[allow(non_snake_case)]
344 $($passes: $passes,)*
348 $v fn new() -> Self {
350 $($passes: $constructor,)*
354 $v fn get_lints() -> LintArray {
355 let mut lints = Vec::new();
356 $(lints.extend_from_slice(&$passes::get_lints());)*
361 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
362 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
365 impl LintPass for $name {
366 fn name(&self) -> &'static str {
374 macro_rules! early_lint_methods {
375 ($macro:path, $args:tt) => (
377 fn check_param(a: &ast::Param);
378 fn check_ident(a: ast::Ident);
379 fn check_crate(a: &ast::Crate);
380 fn check_crate_post(a: &ast::Crate);
381 fn check_mod(a: &ast::Mod, b: Span, c: ast::NodeId);
382 fn check_mod_post(a: &ast::Mod, b: Span, c: ast::NodeId);
383 fn check_foreign_item(a: &ast::ForeignItem);
384 fn check_foreign_item_post(a: &ast::ForeignItem);
385 fn check_item(a: &ast::Item);
386 fn check_item_post(a: &ast::Item);
387 fn check_local(a: &ast::Local);
388 fn check_block(a: &ast::Block);
389 fn check_block_post(a: &ast::Block);
390 fn check_stmt(a: &ast::Stmt);
391 fn check_arm(a: &ast::Arm);
392 fn check_pat(a: &ast::Pat);
393 fn check_pat_post(a: &ast::Pat);
394 fn check_expr(a: &ast::Expr);
395 fn check_expr_post(a: &ast::Expr);
396 fn check_ty(a: &ast::Ty);
397 fn check_generic_param(a: &ast::GenericParam);
398 fn check_generics(a: &ast::Generics);
399 fn check_where_predicate(a: &ast::WherePredicate);
400 fn check_poly_trait_ref(a: &ast::PolyTraitRef,
401 b: &ast::TraitBoundModifier);
402 fn check_fn(a: syntax::visit::FnKind<'_>, b: &ast::FnDecl, c: Span, d_: ast::NodeId);
404 a: syntax::visit::FnKind<'_>,
409 fn check_trait_item(a: &ast::TraitItem);
410 fn check_trait_item_post(a: &ast::TraitItem);
411 fn check_impl_item(a: &ast::ImplItem);
412 fn check_impl_item_post(a: &ast::ImplItem);
413 fn check_struct_def(a: &ast::VariantData);
414 fn check_struct_def_post(a: &ast::VariantData);
415 fn check_struct_field(a: &ast::StructField);
416 fn check_variant(a: &ast::Variant);
417 fn check_variant_post(a: &ast::Variant);
418 fn check_lifetime(a: &ast::Lifetime);
419 fn check_path(a: &ast::Path, b: ast::NodeId);
420 fn check_attribute(a: &ast::Attribute);
421 fn check_mac_def(a: &ast::MacroDef, b: ast::NodeId);
422 fn check_mac(a: &ast::Mac);
424 /// Called when entering a syntax node that can have lint attributes such
425 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
426 fn enter_lint_attrs(a: &[ast::Attribute]);
428 /// Counterpart to `enter_lint_attrs`.
429 fn exit_lint_attrs(a: &[ast::Attribute]);
434 macro_rules! expand_early_lint_pass_methods {
435 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
436 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
440 macro_rules! declare_early_lint_pass {
441 ([], [$($methods:tt)*]) => (
442 pub trait EarlyLintPass: LintPass {
443 expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]);
448 early_lint_methods!(declare_early_lint_pass, []);
451 macro_rules! expand_combined_early_lint_pass_method {
452 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
453 $($self.$passes.$name $params;)*
458 macro_rules! expand_combined_early_lint_pass_methods {
459 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
460 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
461 expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
467 macro_rules! declare_combined_early_lint_pass {
468 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
469 #[allow(non_snake_case)]
471 $($passes: $passes,)*
475 $v fn new() -> Self {
477 $($passes: $constructor,)*
481 $v fn get_lints() -> LintArray {
482 let mut lints = Vec::new();
483 $(lints.extend_from_slice(&$passes::get_lints());)*
488 impl EarlyLintPass for $name {
489 expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
492 impl LintPass for $name {
493 fn name(&self) -> &'static str {
500 /// A lint pass boxed up as a trait object.
501 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
502 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
503 + sync::Sync + 'static>;
505 /// Identifies a lint known to the compiler.
506 #[derive(Clone, Copy, Debug)]
508 // Identity is based on pointer equality of this field.
512 impl PartialEq for LintId {
513 fn eq(&self, other: &LintId) -> bool {
514 ptr::eq(self.lint, other.lint)
518 impl Eq for LintId { }
520 impl hash::Hash for LintId {
521 fn hash<H: hash::Hasher>(&self, state: &mut H) {
522 let ptr = self.lint as *const Lint;
528 /// Gets the `LintId` for a `Lint`.
529 pub fn of(lint: &'static Lint) -> LintId {
535 pub fn lint_name_raw(&self) -> &'static str {
539 /// Gets the name of the lint.
540 pub fn to_string(&self) -> String {
541 self.lint.name_lower()
545 /// Setting for how to handle a lint.
546 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
548 Allow, Warn, Deny, Forbid,
551 impl_stable_hash_for!(enum self::Level {
559 /// Converts a level to a lower-case string.
560 pub fn as_str(self) -> &'static str {
569 /// Converts a lower-case string to a level.
570 pub fn from_str(x: &str) -> Option<Level> {
572 "allow" => Some(Allow),
573 "warn" => Some(Warn),
574 "deny" => Some(Deny),
575 "forbid" => Some(Forbid),
580 /// Converts a symbol to a level.
581 pub fn from_symbol(x: Symbol) -> Option<Level> {
583 sym::allow => Some(Allow),
584 sym::warn => Some(Warn),
585 sym::deny => Some(Deny),
586 sym::forbid => Some(Forbid),
592 /// How a lint level was set.
593 #[derive(Clone, Copy, PartialEq, Eq)]
594 pub enum LintSource {
595 /// Lint is at the default level as declared
596 /// in rustc or a plugin.
599 /// Lint level was set by an attribute.
600 Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
602 /// Lint level was set by a command-line flag.
606 impl_stable_hash_for!(enum self::LintSource {
608 Node(name, span, reason),
612 pub type LevelSource = (Level, LintSource);
619 pub use self::levels::{LintLevelSets, LintLevelMap};
622 pub struct LintBuffer {
623 map: NodeMap<Vec<BufferedEarlyLint>>,
627 pub fn add_lint(&mut self,
632 diagnostic: BuiltinLintDiagnostics) {
633 let early_lint = BufferedEarlyLint {
634 lint_id: LintId::of(lint),
637 msg: msg.to_string(),
640 let arr = self.map.entry(id).or_default();
641 if !arr.contains(&early_lint) {
642 arr.push(early_lint);
646 pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
647 self.map.remove(&id).unwrap_or_default()
650 pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
651 let key = self.map.keys().next().map(|k| *k);
652 key.map(|k| &self.map[&k][..])
656 pub fn struct_lint_level<'a>(sess: &'a Session,
660 span: Option<MultiSpan>,
662 -> DiagnosticBuilder<'a>
664 let mut err = match (level, span) {
665 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
666 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
667 (Level::Warn, None) => sess.struct_warn(msg),
668 (Level::Deny, Some(span)) |
669 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
670 (Level::Deny, None) |
671 (Level::Forbid, None) => sess.struct_err(msg),
674 // Check for future incompatibility lints and issue a stronger warning.
675 let lints = sess.lint_store.borrow();
676 let lint_id = LintId::of(lint);
677 let future_incompatible = lints.future_incompatible(lint_id);
679 // If this code originates in a foreign macro, aka something that this crate
680 // did not itself author, then it's likely that there's nothing this crate
681 // can do about it. We probably want to skip the lint entirely.
682 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
683 // Any suggestions made here are likely to be incorrect, so anything we
684 // emit shouldn't be automatically fixed by rustfix.
685 err.allow_suggestions(false);
687 // If this is a future incompatible lint it'll become a hard error, so
688 // we have to emit *something*. Also allow lints to whitelist themselves
689 // on a case-by-case basis for emission in a foreign macro.
690 if future_incompatible.is_none() && !lint.report_in_external_macro {
692 // Don't continue further, since we don't want to have
693 // `diag_span_note_once` called for a diagnostic that isn't emitted.
698 let name = lint.name_lower();
700 LintSource::Default => {
703 DiagnosticMessageId::from(lint),
704 &format!("`#[{}({})]` on by default", level.as_str(), name));
706 LintSource::CommandLine(lint_flag_val) => {
707 let flag = match level {
710 Level::Forbid => "-F",
711 Level::Allow => panic!(),
713 let hyphen_case_lint_name = name.replace("_", "-");
714 if lint_flag_val.as_str() == name {
717 DiagnosticMessageId::from(lint),
718 &format!("requested on the command line with `{} {}`",
719 flag, hyphen_case_lint_name));
721 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
724 DiagnosticMessageId::from(lint),
725 &format!("`{} {}` implied by `{} {}`",
726 flag, hyphen_case_lint_name, flag,
727 hyphen_case_flag_val));
730 LintSource::Node(lint_attr_name, src, reason) => {
731 if let Some(rationale) = reason {
732 err.note(&rationale.as_str());
734 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
735 src, "lint level defined here");
736 if lint_attr_name.as_str() != name {
737 let level_str = level.as_str();
738 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
739 &format!("`#[{}({})]` implied by `#[{}({})]`",
740 level_str, name, level_str, lint_attr_name));
745 err.code(DiagnosticId::Lint(name));
747 if let Some(future_incompatible) = future_incompatible {
748 const STANDARD_MESSAGE: &str =
749 "this was previously accepted by the compiler but is being phased out; \
750 it will become a hard error";
752 let explanation = if lint_id == LintId::of(builtin::UNSTABLE_NAME_COLLISIONS) {
753 "once this method is added to the standard library, \
754 the ambiguity may cause an error or change in behavior!"
756 } else if lint_id == LintId::of(builtin::MUTABLE_BORROW_RESERVATION_CONFLICT) {
757 "this borrowing pattern was not meant to be accepted, \
758 and may become a hard error in the future"
760 } else if let Some(edition) = future_incompatible.edition {
761 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
763 format!("{} in a future release!", STANDARD_MESSAGE)
765 let citation = format!("for more information, see {}",
766 future_incompatible.reference);
767 err.warn(&explanation);
774 pub fn maybe_lint_level_root(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
775 let attrs = tcx.hir().attrs(id);
776 attrs.iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some())
779 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap {
780 assert_eq!(cnum, LOCAL_CRATE);
781 let mut builder = LintLevelMapBuilder {
782 levels: LintLevelSets::builder(tcx.sess),
785 let krate = tcx.hir().krate();
787 let push = builder.levels.push(&krate.attrs);
788 builder.levels.register_id(hir::CRATE_HIR_ID);
789 for macro_def in &krate.exported_macros {
790 builder.levels.register_id(macro_def.hir_id);
792 intravisit::walk_crate(&mut builder, krate);
793 builder.levels.pop(push);
795 tcx.arena.alloc(builder.levels.build_map())
798 struct LintLevelMapBuilder<'tcx> {
799 levels: levels::LintLevelsBuilder<'tcx>,
803 impl LintLevelMapBuilder<'tcx> {
804 fn with_lint_attrs<F>(&mut self,
806 attrs: &[ast::Attribute],
808 where F: FnOnce(&mut Self)
810 let push = self.levels.push(attrs);
812 self.levels.register_id(id);
815 self.levels.pop(push);
819 impl intravisit::Visitor<'tcx> for LintLevelMapBuilder<'tcx> {
820 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
821 intravisit::NestedVisitorMap::All(&self.tcx.hir())
824 fn visit_param(&mut self, param: &'tcx hir::Param) {
825 self.with_lint_attrs(param.hir_id, ¶m.attrs, |builder| {
826 intravisit::walk_param(builder, param);
830 fn visit_item(&mut self, it: &'tcx hir::Item) {
831 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
832 intravisit::walk_item(builder, it);
836 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
837 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
838 intravisit::walk_foreign_item(builder, it);
842 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
843 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
844 intravisit::walk_expr(builder, e);
848 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
849 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
850 intravisit::walk_struct_field(builder, s);
854 fn visit_variant(&mut self,
855 v: &'tcx hir::Variant,
856 g: &'tcx hir::Generics,
857 item_id: hir::HirId) {
858 self.with_lint_attrs(v.id, &v.attrs, |builder| {
859 intravisit::walk_variant(builder, v, g, item_id);
863 fn visit_local(&mut self, l: &'tcx hir::Local) {
864 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
865 intravisit::walk_local(builder, l);
869 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
870 self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
871 intravisit::walk_arm(builder, a);
875 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
876 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
877 intravisit::walk_trait_item(builder, trait_item);
881 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
882 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
883 intravisit::walk_impl_item(builder, impl_item);
888 pub fn provide(providers: &mut Providers<'_>) {
889 providers.lint_levels = lint_levels;
892 /// Returns whether `span` originates in a foreign crate's external macro.
894 /// This is used to test whether a lint should not even begin to figure out whether it should
895 /// be reported on the current node.
896 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
897 let expn_data = span.ctxt().outer_expn_data();
898 match expn_data.kind {
899 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
900 ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
901 ExpnKind::Macro(MacroKind::Bang, _) => {
902 if expn_data.def_site.is_dummy() {
903 // Dummy span for the `def_site` means it's an external macro.
906 match sess.source_map().span_to_snippet(expn_data.def_site) {
907 Ok(code) => !code.starts_with("macro_rules"),
908 // No snippet means external macro or compiler-builtin expansion.
912 ExpnKind::Macro(..) => true, // definitely a plugin
916 /// Returns `true` if `span` originates in a derive-macro's expansion.
917 pub fn in_derive_expansion(span: Span) -> bool {
918 if let ExpnKind::Macro(MacroKind::Derive, _) = span.ctxt().outer_expn_data().kind {