1 #![feature(min_specialization)]
2 #![deny(rustc::untranslatable_diagnostic)]
3 #![deny(rustc::diagnostic_outside_of_impl)]
6 extern crate rustc_macros;
8 pub use self::Level::*;
9 use rustc_ast::node_id::{NodeId, NodeMap};
10 use rustc_ast::{AttrId, Attribute};
11 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
12 use rustc_error_messages::{DiagnosticMessage, MultiSpan};
13 use rustc_hir::HashStableContext;
15 use rustc_span::edition::Edition;
16 use rustc_span::{sym, symbol::Ident, Span, Symbol};
17 use rustc_target::spec::abi::Abi;
19 use serde::{Deserialize, Serialize};
24 macro_rules! pluralize {
26 if $x != 1 { "s" } else { "" }
29 if $x == 1 { "has" } else { "have" }
32 if $x == 1 { "is" } else { "are" }
35 if $x == 1 { "was" } else { "were" }
37 ("this", $x:expr) => {
38 if $x == 1 { "this" } else { "these" }
42 /// Indicates the confidence in the correctness of a suggestion.
44 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
45 /// to determine whether it should be automatically applied or if the user should be consulted
46 /// before applying the suggestion.
47 #[derive(Copy, Clone, Debug, Hash, Encodable, Decodable, Serialize, Deserialize)]
48 #[derive(PartialEq, Eq, PartialOrd, Ord)]
49 pub enum Applicability {
50 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
51 /// This suggestion should be automatically applied.
53 /// In case of multiple `MachineApplicable` suggestions (whether as part of
54 /// the same `multipart_suggestion` or not), all of them should be
55 /// automatically applied.
58 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
59 /// result in valid Rust code if it is applied.
62 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
63 /// cannot be applied automatically because it will not result in valid Rust code. The user
64 /// will need to fill in the placeholders.
67 /// The applicability of the suggestion is unknown.
71 /// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
72 /// Expected `Diagnostic`s get the lint level `Expect` which stores the `LintExpectationId`
73 /// to match it with the actual expectation later on.
75 /// The `LintExpectationId` has to be stable between compilations, as diagnostic
76 /// instances might be loaded from cache. Lint messages can be emitted during an
77 /// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
78 /// HIR tree. The AST doesn't have enough information to create a stable id. The
79 /// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
80 /// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
81 /// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
83 /// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
84 /// identifies the lint inside the attribute and ensures that the IDs are unique.
86 /// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
87 /// It's reasonable to assume that no user will define 2^16 attributes on one node or
88 /// have that amount of lints listed. `u16` values should therefore suffice.
89 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Encodable, Decodable)]
90 pub enum LintExpectationId {
91 /// Used for lints emitted during the `EarlyLintPass`. This id is not
92 /// hash stable and should not be cached.
93 Unstable { attr_id: AttrId, lint_index: Option<u16> },
94 /// The [`HirId`] that the lint expectation is attached to. This id is
95 /// stable and can be cached. The additional index ensures that nodes with
96 /// several expectations can correctly match diagnostics to the individual
98 Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16>, attr_id: Option<AttrId> },
101 impl LintExpectationId {
102 pub fn is_stable(&self) -> bool {
104 LintExpectationId::Unstable { .. } => false,
105 LintExpectationId::Stable { .. } => true,
109 pub fn get_lint_index(&self) -> Option<u16> {
110 let (LintExpectationId::Unstable { lint_index, .. }
111 | LintExpectationId::Stable { lint_index, .. }) = self;
116 pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
117 let (LintExpectationId::Unstable { ref mut lint_index, .. }
118 | LintExpectationId::Stable { ref mut lint_index, .. }) = self;
120 *lint_index = new_lint_index
123 /// Prepares the id for hashing. Removes references to the ast.
124 /// Should only be called when the id is stable.
125 pub fn normalize(self) -> Self {
127 Self::Stable { hir_id, attr_index, lint_index, .. } => {
128 Self::Stable { hir_id, attr_index, lint_index, attr_id: None }
130 Self::Unstable { .. } => {
131 unreachable!("`normalize` called when `ExpectationId` is unstable")
137 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId {
139 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
141 LintExpectationId::Stable {
144 lint_index: Some(lint_index),
147 hir_id.hash_stable(hcx, hasher);
148 attr_index.hash_stable(hcx, hasher);
149 lint_index.hash_stable(hcx, hasher);
153 "HashStable should only be called for filled and stable `LintExpectationId`"
160 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
161 type KeyType = (HirId, u16, u16);
164 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
166 LintExpectationId::Stable {
169 lint_index: Some(lint_index),
171 } => (*hir_id, *attr_index, *lint_index),
173 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
179 /// Setting for how to handle a lint.
181 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
182 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, HashStable_Generic)]
184 /// The `allow` level will not issue any message.
186 /// The `expect` level will suppress the lint message but in turn produce a message
187 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
188 /// an initial level for a lint.
190 /// Note that this still means that the lint is enabled in this position and should
191 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
195 /// The [`LintExpectationId`] is used to later link a lint emission to the actual
196 /// expectation. It can be ignored in most cases.
197 Expect(LintExpectationId),
198 /// The `warn` level will produce a warning if the lint was violated, however the
199 /// compiler will continue with its execution.
201 /// This lint level is a special case of [`Warn`], that can't be overridden. This is used
202 /// to ensure that a lint can't be suppressed. This lint level can currently only be set
203 /// via the console and is therefore session specific.
205 /// The [`LintExpectationId`] is intended to fulfill expectations marked via the
206 /// `#[expect]` attribute, that will still be suppressed due to the level.
207 ForceWarn(Option<LintExpectationId>),
208 /// The `deny` level will produce an error and stop further execution after the lint
209 /// pass is complete.
211 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
217 /// Converts a level to a lower-case string.
218 pub fn as_str(self) -> &'static str {
220 Level::Allow => "allow",
221 Level::Expect(_) => "expect",
222 Level::Warn => "warn",
223 Level::ForceWarn(_) => "force-warn",
224 Level::Deny => "deny",
225 Level::Forbid => "forbid",
229 /// Converts a lower-case string to a level. This will never construct the expect
230 /// level as that would require a [`LintExpectationId`]
231 pub fn from_str(x: &str) -> Option<Level> {
233 "allow" => Some(Level::Allow),
234 "warn" => Some(Level::Warn),
235 "deny" => Some(Level::Deny),
236 "forbid" => Some(Level::Forbid),
237 "expect" | _ => None,
241 /// Converts a symbol to a level.
242 pub fn from_attr(attr: &Attribute) -> Option<Level> {
243 match attr.name_or_empty() {
244 sym::allow => Some(Level::Allow),
245 sym::expect => Some(Level::Expect(LintExpectationId::Unstable {
249 sym::warn => Some(Level::Warn),
250 sym::deny => Some(Level::Deny),
251 sym::forbid => Some(Level::Forbid),
256 pub fn is_error(self) -> bool {
258 Level::Allow | Level::Expect(_) | Level::Warn | Level::ForceWarn(_) => false,
259 Level::Deny | Level::Forbid => true,
263 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
265 Level::Expect(id) | Level::ForceWarn(Some(id)) => Some(*id),
271 /// Specification of a single lint.
272 #[derive(Copy, Clone, Debug)]
274 /// A string identifier for the lint.
276 /// This identifies the lint in attributes and in command-line arguments.
277 /// In those contexts it is always lowercase, but this field is compared
278 /// in a way which is case-insensitive for ASCII characters. This allows
279 /// `declare_lint!()` invocations to follow the convention of upper-case
280 /// statics without repeating the name.
282 /// The name is written with underscores, e.g., "unused_imports".
283 /// On the command line, underscores become dashes.
285 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
286 /// for naming guidelines.
287 pub name: &'static str,
289 /// Default level for the lint.
291 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
292 /// for guidelines on choosing a default level.
293 pub default_level: Level,
295 /// Description of the lint or the issue it detects.
297 /// e.g., "imports that are never used"
298 pub desc: &'static str,
300 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
302 pub edition_lint_opts: Option<(Edition, Level)>,
304 /// `true` if this lint is reported even inside expansions of external macros.
305 pub report_in_external_macro: bool,
307 pub future_incompatible: Option<FutureIncompatibleInfo>,
311 /// `Some` if this lint is feature gated, otherwise `None`.
312 pub feature_gate: Option<Symbol>,
314 pub crate_level_only: bool,
317 /// Extra information for a future incompatibility lint.
318 #[derive(Copy, Clone, Debug)]
319 pub struct FutureIncompatibleInfo {
320 /// e.g., a URL for an issue/PR/RFC or error code
321 pub reference: &'static str,
322 /// The reason for the lint used by diagnostics to provide
323 /// the right help message
324 pub reason: FutureIncompatibilityReason,
325 /// Whether to explain the reason to the user.
327 /// Set to false for lints that already include a more detailed
329 pub explain_reason: bool,
332 /// The reason for future incompatibility
333 #[derive(Copy, Clone, Debug)]
334 pub enum FutureIncompatibilityReason {
335 /// This will be an error in a future release
338 /// This will be an error in a future release, and
339 /// Cargo should create a report even for dependencies
340 FutureReleaseErrorReportNow,
341 /// Code that changes meaning in some way in a
343 FutureReleaseSemanticsChange,
344 /// Previously accepted code that will become an
345 /// error in the provided edition
346 EditionError(Edition),
347 /// Code that changes meaning in some way in
348 /// the provided edition
349 EditionSemanticsChange(Edition),
351 Custom(&'static str),
354 impl FutureIncompatibilityReason {
355 pub fn edition(self) -> Option<Edition> {
357 Self::EditionError(e) => Some(e),
358 Self::EditionSemanticsChange(e) => Some(e),
364 impl FutureIncompatibleInfo {
365 pub const fn default_fields_for_macro() -> Self {
366 FutureIncompatibleInfo {
368 reason: FutureIncompatibilityReason::FutureReleaseError,
369 explain_reason: true,
375 pub const fn default_fields_for_macro() -> Self {
378 default_level: Level::Forbid,
380 edition_lint_opts: None,
382 report_in_external_macro: false,
383 future_incompatible: None,
385 crate_level_only: false,
389 /// Gets the lint's name, with ASCII letters converted to lowercase.
390 pub fn name_lower(&self) -> String {
391 self.name.to_ascii_lowercase()
394 pub fn default_level(&self, edition: Edition) -> Level {
395 self.edition_lint_opts
396 .filter(|(e, _)| *e <= edition)
398 .unwrap_or(self.default_level)
402 /// Identifies a lint known to the compiler.
403 #[derive(Clone, Copy, Debug)]
405 // Identity is based on pointer equality of this field.
406 pub lint: &'static Lint,
409 impl PartialEq for LintId {
410 fn eq(&self, other: &LintId) -> bool {
411 std::ptr::eq(self.lint, other.lint)
415 impl Eq for LintId {}
417 impl std::hash::Hash for LintId {
418 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
419 let ptr = self.lint as *const Lint;
425 /// Gets the `LintId` for a `Lint`.
426 pub fn of(lint: &'static Lint) -> LintId {
430 pub fn lint_name_raw(&self) -> &'static str {
434 /// Gets the name of the lint.
435 pub fn to_string(&self) -> String {
436 self.lint.name_lower()
440 impl<HCX> HashStable<HCX> for LintId {
442 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
443 self.lint_name_raw().hash_stable(hcx, hasher);
447 impl<HCX> ToStableHashKey<HCX> for LintId {
448 type KeyType = &'static str;
451 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
456 // This could be a closure, but then implementing derive trait
457 // becomes hacky (and it gets allocated).
459 pub enum BuiltinLintDiagnostics {
461 AbsPathWithModule(Span),
462 ProcMacroDeriveResolutionFallback(Span),
463 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
464 ElidedLifetimesInPaths(usize, Span, bool, Span),
465 UnknownCrateTypes(Span, String, String),
466 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
467 RedundantImport(Vec<(Span, bool)>, Ident),
468 DeprecatedMacro(Option<Symbol>, Span),
469 MissingAbi(Span, Abi),
470 UnusedDocComment(Span),
471 UnusedBuiltinAttribute {
476 PatternsInFnsWithoutBody(Span, Ident),
477 LegacyDeriveHelpers(Span),
478 ProcMacroBackCompat(String),
479 OrPatternsBackCompat(Span, String),
480 ReservedPrefix(Span),
481 TrailingMacro(bool, Ident),
482 BreakWithLabelAndLoop(Span),
483 NamedAsmLabel(String),
484 UnicodeTextFlow(Span, String),
485 UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
486 DeprecatedWhereclauseLocation(Span, String),
488 /// Span of the parameter which declares this lifetime.
490 /// Span of the code that should be removed when eliding this lifetime.
491 /// This span should include leading or trailing comma.
493 /// Span of the single use, or None if the lifetime is never used.
494 /// If true, the lifetime will be fully elided.
495 use_span: Option<(Span, bool)>,
497 NamedArgumentUsedPositionally {
498 /// Span where the named argument is used by position and will be replaced with the named
500 position_sp_to_replace: Option<Span>,
501 /// Span where the named argument is used by position and is used for lint messages
502 position_sp_for_msg: Option<Span>,
503 /// Span where the named argument's name is (so we know where to put the warning message)
505 /// String containing the named arguments name
506 named_arg_name: String,
507 /// Indicates if the named argument is used as a width/precision for formatting
508 is_formatting_arg: bool,
512 /// Lints that are buffered up early on in the `Session` before the
513 /// `LintLevels` is calculated.
514 pub struct BufferedEarlyLint {
515 /// The span of code that we are linting on.
518 /// The lint message.
519 pub msg: DiagnosticMessage,
521 /// The `NodeId` of the AST node that generated the lint.
524 /// A lint Id that can be passed to
525 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
528 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
529 pub diagnostic: BuiltinLintDiagnostics,
533 pub struct LintBuffer {
534 pub map: NodeMap<Vec<BufferedEarlyLint>>,
538 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
539 let arr = self.map.entry(early_lint.node_id).or_default();
540 arr.push(early_lint);
548 msg: impl Into<DiagnosticMessage>,
549 diagnostic: BuiltinLintDiagnostics,
551 let lint_id = LintId::of(lint);
552 let msg = msg.into();
553 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
556 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
557 self.map.remove(&id).unwrap_or_default()
564 sp: impl Into<MultiSpan>,
565 msg: impl Into<DiagnosticMessage>,
567 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
570 pub fn buffer_lint_with_diagnostic(
574 sp: impl Into<MultiSpan>,
575 msg: impl Into<DiagnosticMessage>,
576 diagnostic: BuiltinLintDiagnostics,
578 self.add_lint(lint, id, sp.into(), msg, diagnostic)
582 /// Declares a static item of type `&'static Lint`.
584 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
585 /// documentation and guidelines on writing lints.
587 /// The macro call should start with a doc comment explaining the lint
588 /// which will be embedded in the rustc user documentation book. It should
589 /// be written in markdown and have a format that looks like this:
591 /// ```rust,ignore (doc-example)
592 /// /// The `my_lint_name` lint detects [short explanation here].
597 /// /// [insert a concise example that triggers the lint]
602 /// /// ### Explanation
604 /// /// This should be a detailed explanation of *why* the lint exists,
605 /// /// and also include suggestions on how the user should fix the problem.
606 /// /// Try to keep the text simple enough that a beginner can understand,
607 /// /// and include links to other documentation for terminology that a
608 /// /// beginner may not be familiar with. If this is "allow" by default,
609 /// /// it should explain why (are there false positives or other issues?). If
610 /// /// this is a future-incompatible lint, it should say so, with text that
611 /// /// looks roughly like this:
613 /// /// This is a [future-incompatible] lint to transition this to a hard
614 /// /// error in the future. See [issue #xxxxx] for more details.
616 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
619 /// The `{{produces}}` tag will be automatically replaced with the output from
620 /// the example by the build system. If the lint example is too complex to run
621 /// as a simple example (for example, it needs an extern crate), mark the code
622 /// block with `ignore` and manually replace the `{{produces}}` line with the
623 /// expected output in a `text` code block.
625 /// If this is a rustdoc-only lint, then only include a brief introduction
626 /// with a link with the text `[rustdoc book]` so that the validator knows
627 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
629 /// Commands to view and test the documentation:
631 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
632 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
633 /// correct style, and that the code example actually emits the expected
636 /// If you have already built the compiler, and you want to make changes to
637 /// just the doc comments, then use the `--keep-stage=0` flag with the above
638 /// commands to avoid rebuilding the compiler.
640 macro_rules! declare_lint {
641 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
642 $crate::declare_lint!(
643 $(#[$attr])* $vis $NAME, $Level, $desc,
646 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
647 $(@feature_gate = $gate:expr;)?
648 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
651 $vis static $NAME: &$crate::Lint = &$crate::Lint {
652 name: stringify!($NAME),
653 default_level: $crate::$Level,
655 edition_lint_opts: None,
658 $(feature_gate: Some($gate),)*
659 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
661 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
663 ..$crate::Lint::default_fields_for_macro()
666 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
667 $lint_edition: expr => $edition_level: ident
670 $vis static $NAME: &$crate::Lint = &$crate::Lint {
671 name: stringify!($NAME),
672 default_level: $crate::$Level,
674 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
675 report_in_external_macro: false,
682 macro_rules! declare_tool_lint {
684 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
685 $(, @feature_gate = $gate:expr;)?
687 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?}
690 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
691 report_in_external_macro: $rep:expr
692 $(, @feature_gate = $gate:expr;)?
694 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?}
697 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
699 $(, @feature_gate = $gate:expr;)?
702 $vis static $NAME: &$crate::Lint = &$crate::Lint {
703 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
704 default_level: $crate::$Level,
706 edition_lint_opts: None,
707 report_in_external_macro: $external,
708 future_incompatible: None,
710 $(feature_gate: Some($gate),)?
711 crate_level_only: false,
712 ..$crate::Lint::default_fields_for_macro()
717 /// Declares a static `LintArray` and return it as an expression.
719 macro_rules! lint_array {
720 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
721 ($( $lint:expr ),*) => {{
726 pub type LintArray = Vec<&'static Lint>;
729 fn name(&self) -> &'static str;
732 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
734 macro_rules! impl_lint_pass {
735 ($ty:ty => [$($lint:expr),* $(,)?]) => {
736 impl $crate::LintPass for $ty {
737 fn name(&self) -> &'static str { stringify!($ty) }
740 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
745 /// Declares a type named `$name` which implements `LintPass`.
746 /// To the right of `=>` a comma separated list of `Lint` statics is given.
748 macro_rules! declare_lint_pass {
749 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
750 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
751 $crate::impl_lint_pass!($name => [$($lint),*]);