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 { "is" } else { "are" }
32 if $x == 1 { "was" } else { "were" }
34 ("this", $x:expr) => {
35 if $x == 1 { "this" } else { "these" }
39 /// Indicates the confidence in the correctness of a suggestion.
41 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
42 /// to determine whether it should be automatically applied or if the user should be consulted
43 /// before applying the suggestion.
44 #[derive(Copy, Clone, Debug, Hash, Encodable, Decodable, Serialize, Deserialize)]
45 #[derive(PartialEq, Eq, PartialOrd, Ord)]
46 pub enum Applicability {
47 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
48 /// This suggestion should be automatically applied.
50 /// In case of multiple `MachineApplicable` suggestions (whether as part of
51 /// the same `multipart_suggestion` or not), all of them should be
52 /// automatically applied.
55 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
56 /// result in valid Rust code if it is applied.
59 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
60 /// cannot be applied automatically because it will not result in valid Rust code. The user
61 /// will need to fill in the placeholders.
64 /// The applicability of the suggestion is unknown.
68 /// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
69 /// Expected `Diagnostic`s get the lint level `Expect` which stores the `LintExpectationId`
70 /// to match it with the actual expectation later on.
72 /// The `LintExpectationId` has to be stable between compilations, as diagnostic
73 /// instances might be loaded from cache. Lint messages can be emitted during an
74 /// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
75 /// HIR tree. The AST doesn't have enough information to create a stable id. The
76 /// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
77 /// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
78 /// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
80 /// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
81 /// identifies the lint inside the attribute and ensures that the IDs are unique.
83 /// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
84 /// It's reasonable to assume that no user will define 2^16 attributes on one node or
85 /// have that amount of lints listed. `u16` values should therefore suffice.
86 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Encodable, Decodable)]
87 pub enum LintExpectationId {
88 /// Used for lints emitted during the `EarlyLintPass`. This id is not
89 /// hash stable and should not be cached.
90 Unstable { attr_id: AttrId, lint_index: Option<u16> },
91 /// The [`HirId`] that the lint expectation is attached to. This id is
92 /// stable and can be cached. The additional index ensures that nodes with
93 /// several expectations can correctly match diagnostics to the individual
95 Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16>, attr_id: Option<AttrId> },
98 impl LintExpectationId {
99 pub fn is_stable(&self) -> bool {
101 LintExpectationId::Unstable { .. } => false,
102 LintExpectationId::Stable { .. } => true,
106 pub fn get_lint_index(&self) -> Option<u16> {
107 let (LintExpectationId::Unstable { lint_index, .. }
108 | LintExpectationId::Stable { lint_index, .. }) = self;
113 pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
114 let (LintExpectationId::Unstable { ref mut lint_index, .. }
115 | LintExpectationId::Stable { ref mut lint_index, .. }) = self;
117 *lint_index = new_lint_index
120 /// Prepares the id for hashing. Removes references to the ast.
121 /// Should only be called when the id is stable.
122 pub fn normalize(self) -> Self {
124 Self::Stable { hir_id, attr_index, lint_index, .. } => {
125 Self::Stable { hir_id, attr_index, lint_index, attr_id: None }
127 Self::Unstable { .. } => {
128 unreachable!("`normalize` called when `ExpectationId` is unstable")
134 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId {
136 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
138 LintExpectationId::Stable {
141 lint_index: Some(lint_index),
144 hir_id.hash_stable(hcx, hasher);
145 attr_index.hash_stable(hcx, hasher);
146 lint_index.hash_stable(hcx, hasher);
150 "HashStable should only be called for filled and stable `LintExpectationId`"
157 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
158 type KeyType = (HirId, u16, u16);
161 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
163 LintExpectationId::Stable {
166 lint_index: Some(lint_index),
168 } => (*hir_id, *attr_index, *lint_index),
170 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
176 /// Setting for how to handle a lint.
178 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
179 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, HashStable_Generic)]
181 /// The `allow` level will not issue any message.
183 /// The `expect` level will suppress the lint message but in turn produce a message
184 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
185 /// an initial level for a lint.
187 /// Note that this still means that the lint is enabled in this position and should
188 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
192 /// The [`LintExpectationId`] is used to later link a lint emission to the actual
193 /// expectation. It can be ignored in most cases.
194 Expect(LintExpectationId),
195 /// The `warn` level will produce a warning if the lint was violated, however the
196 /// compiler will continue with its execution.
198 /// This lint level is a special case of [`Warn`], that can't be overridden. This is used
199 /// to ensure that a lint can't be suppressed. This lint level can currently only be set
200 /// via the console and is therefore session specific.
202 /// The [`LintExpectationId`] is intended to fulfill expectations marked via the
203 /// `#[expect]` attribute, that will still be suppressed due to the level.
204 ForceWarn(Option<LintExpectationId>),
205 /// The `deny` level will produce an error and stop further execution after the lint
206 /// pass is complete.
208 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
214 /// Converts a level to a lower-case string.
215 pub fn as_str(self) -> &'static str {
217 Level::Allow => "allow",
218 Level::Expect(_) => "expect",
219 Level::Warn => "warn",
220 Level::ForceWarn(_) => "force-warn",
221 Level::Deny => "deny",
222 Level::Forbid => "forbid",
226 /// Converts a lower-case string to a level. This will never construct the expect
227 /// level as that would require a [`LintExpectationId`]
228 pub fn from_str(x: &str) -> Option<Level> {
230 "allow" => Some(Level::Allow),
231 "warn" => Some(Level::Warn),
232 "deny" => Some(Level::Deny),
233 "forbid" => Some(Level::Forbid),
234 "expect" | _ => None,
238 /// Converts a symbol to a level.
239 pub fn from_attr(attr: &Attribute) -> Option<Level> {
240 match attr.name_or_empty() {
241 sym::allow => Some(Level::Allow),
242 sym::expect => Some(Level::Expect(LintExpectationId::Unstable {
246 sym::warn => Some(Level::Warn),
247 sym::deny => Some(Level::Deny),
248 sym::forbid => Some(Level::Forbid),
253 pub fn is_error(self) -> bool {
255 Level::Allow | Level::Expect(_) | Level::Warn | Level::ForceWarn(_) => false,
256 Level::Deny | Level::Forbid => true,
260 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
262 Level::Expect(id) | Level::ForceWarn(Some(id)) => Some(*id),
268 /// Specification of a single lint.
269 #[derive(Copy, Clone, Debug)]
271 /// A string identifier for the lint.
273 /// This identifies the lint in attributes and in command-line arguments.
274 /// In those contexts it is always lowercase, but this field is compared
275 /// in a way which is case-insensitive for ASCII characters. This allows
276 /// `declare_lint!()` invocations to follow the convention of upper-case
277 /// statics without repeating the name.
279 /// The name is written with underscores, e.g., "unused_imports".
280 /// On the command line, underscores become dashes.
282 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
283 /// for naming guidelines.
284 pub name: &'static str,
286 /// Default level for the lint.
288 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
289 /// for guidelines on choosing a default level.
290 pub default_level: Level,
292 /// Description of the lint or the issue it detects.
294 /// e.g., "imports that are never used"
295 pub desc: &'static str,
297 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
299 pub edition_lint_opts: Option<(Edition, Level)>,
301 /// `true` if this lint is reported even inside expansions of external macros.
302 pub report_in_external_macro: bool,
304 pub future_incompatible: Option<FutureIncompatibleInfo>,
308 /// `Some` if this lint is feature gated, otherwise `None`.
309 pub feature_gate: Option<Symbol>,
311 pub crate_level_only: bool,
314 /// Extra information for a future incompatibility lint.
315 #[derive(Copy, Clone, Debug)]
316 pub struct FutureIncompatibleInfo {
317 /// e.g., a URL for an issue/PR/RFC or error code
318 pub reference: &'static str,
319 /// The reason for the lint used by diagnostics to provide
320 /// the right help message
321 pub reason: FutureIncompatibilityReason,
322 /// Whether to explain the reason to the user.
324 /// Set to false for lints that already include a more detailed
326 pub explain_reason: bool,
329 /// The reason for future incompatibility
330 #[derive(Copy, Clone, Debug)]
331 pub enum FutureIncompatibilityReason {
332 /// This will be an error in a future release
335 /// This will be an error in a future release, and
336 /// Cargo should create a report even for dependencies
337 FutureReleaseErrorReportNow,
338 /// Code that changes meaning in some way in a
340 FutureReleaseSemanticsChange,
341 /// Previously accepted code that will become an
342 /// error in the provided edition
343 EditionError(Edition),
344 /// Code that changes meaning in some way in
345 /// the provided edition
346 EditionSemanticsChange(Edition),
348 Custom(&'static str),
351 impl FutureIncompatibilityReason {
352 pub fn edition(self) -> Option<Edition> {
354 Self::EditionError(e) => Some(e),
355 Self::EditionSemanticsChange(e) => Some(e),
361 impl FutureIncompatibleInfo {
362 pub const fn default_fields_for_macro() -> Self {
363 FutureIncompatibleInfo {
365 reason: FutureIncompatibilityReason::FutureReleaseError,
366 explain_reason: true,
372 pub const fn default_fields_for_macro() -> Self {
375 default_level: Level::Forbid,
377 edition_lint_opts: None,
379 report_in_external_macro: false,
380 future_incompatible: None,
382 crate_level_only: false,
386 /// Gets the lint's name, with ASCII letters converted to lowercase.
387 pub fn name_lower(&self) -> String {
388 self.name.to_ascii_lowercase()
391 pub fn default_level(&self, edition: Edition) -> Level {
392 self.edition_lint_opts
393 .filter(|(e, _)| *e <= edition)
395 .unwrap_or(self.default_level)
399 /// Identifies a lint known to the compiler.
400 #[derive(Clone, Copy, Debug)]
402 // Identity is based on pointer equality of this field.
403 pub lint: &'static Lint,
406 impl PartialEq for LintId {
407 fn eq(&self, other: &LintId) -> bool {
408 std::ptr::eq(self.lint, other.lint)
412 impl Eq for LintId {}
414 impl std::hash::Hash for LintId {
415 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
416 let ptr = self.lint as *const Lint;
422 /// Gets the `LintId` for a `Lint`.
423 pub fn of(lint: &'static Lint) -> LintId {
427 pub fn lint_name_raw(&self) -> &'static str {
431 /// Gets the name of the lint.
432 pub fn to_string(&self) -> String {
433 self.lint.name_lower()
437 impl<HCX> HashStable<HCX> for LintId {
439 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
440 self.lint_name_raw().hash_stable(hcx, hasher);
444 impl<HCX> ToStableHashKey<HCX> for LintId {
445 type KeyType = &'static str;
448 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
453 // This could be a closure, but then implementing derive trait
454 // becomes hacky (and it gets allocated).
456 pub enum BuiltinLintDiagnostics {
458 AbsPathWithModule(Span),
459 ProcMacroDeriveResolutionFallback(Span),
460 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
461 ElidedLifetimesInPaths(usize, Span, bool, Span),
462 UnknownCrateTypes(Span, String, String),
463 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
464 RedundantImport(Vec<(Span, bool)>, Ident),
465 DeprecatedMacro(Option<Symbol>, Span),
466 MissingAbi(Span, Abi),
467 UnusedDocComment(Span),
468 UnusedBuiltinAttribute {
473 PatternsInFnsWithoutBody(Span, Ident),
474 LegacyDeriveHelpers(Span),
475 ProcMacroBackCompat(String),
476 OrPatternsBackCompat(Span, String),
477 ReservedPrefix(Span),
478 TrailingMacro(bool, Ident),
479 BreakWithLabelAndLoop(Span),
480 NamedAsmLabel(String),
481 UnicodeTextFlow(Span, String),
482 UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
483 DeprecatedWhereclauseLocation(Span, String),
485 /// Span of the parameter which declares this lifetime.
487 /// Span of the code that should be removed when eliding this lifetime.
488 /// This span should include leading or trailing comma.
490 /// Span of the single use, or None if the lifetime is never used.
491 /// If true, the lifetime will be fully elided.
492 use_span: Option<(Span, bool)>,
494 NamedArgumentUsedPositionally {
495 /// Span where the named argument is used by position and will be replaced with the named
497 position_sp_to_replace: Option<Span>,
498 /// Span where the named argument is used by position and is used for lint messages
499 position_sp_for_msg: Option<Span>,
500 /// Span where the named argument's name is (so we know where to put the warning message)
502 /// String containing the named arguments name
503 named_arg_name: String,
504 /// Indicates if the named argument is used as a width/precision for formatting
505 is_formatting_arg: bool,
509 /// Lints that are buffered up early on in the `Session` before the
510 /// `LintLevels` is calculated.
511 pub struct BufferedEarlyLint {
512 /// The span of code that we are linting on.
515 /// The lint message.
516 pub msg: DiagnosticMessage,
518 /// The `NodeId` of the AST node that generated the lint.
521 /// A lint Id that can be passed to
522 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
525 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
526 pub diagnostic: BuiltinLintDiagnostics,
530 pub struct LintBuffer {
531 pub map: NodeMap<Vec<BufferedEarlyLint>>,
535 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
536 let arr = self.map.entry(early_lint.node_id).or_default();
537 arr.push(early_lint);
545 msg: impl Into<DiagnosticMessage>,
546 diagnostic: BuiltinLintDiagnostics,
548 let lint_id = LintId::of(lint);
549 let msg = msg.into();
550 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
553 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
554 self.map.remove(&id).unwrap_or_default()
561 sp: impl Into<MultiSpan>,
562 msg: impl Into<DiagnosticMessage>,
564 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
567 pub fn buffer_lint_with_diagnostic(
571 sp: impl Into<MultiSpan>,
572 msg: impl Into<DiagnosticMessage>,
573 diagnostic: BuiltinLintDiagnostics,
575 self.add_lint(lint, id, sp.into(), msg, diagnostic)
579 /// Declares a static item of type `&'static Lint`.
581 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
582 /// documentation and guidelines on writing lints.
584 /// The macro call should start with a doc comment explaining the lint
585 /// which will be embedded in the rustc user documentation book. It should
586 /// be written in markdown and have a format that looks like this:
588 /// ```rust,ignore (doc-example)
589 /// /// The `my_lint_name` lint detects [short explanation here].
594 /// /// [insert a concise example that triggers the lint]
599 /// /// ### Explanation
601 /// /// This should be a detailed explanation of *why* the lint exists,
602 /// /// and also include suggestions on how the user should fix the problem.
603 /// /// Try to keep the text simple enough that a beginner can understand,
604 /// /// and include links to other documentation for terminology that a
605 /// /// beginner may not be familiar with. If this is "allow" by default,
606 /// /// it should explain why (are there false positives or other issues?). If
607 /// /// this is a future-incompatible lint, it should say so, with text that
608 /// /// looks roughly like this:
610 /// /// This is a [future-incompatible] lint to transition this to a hard
611 /// /// error in the future. See [issue #xxxxx] for more details.
613 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
616 /// The `{{produces}}` tag will be automatically replaced with the output from
617 /// the example by the build system. If the lint example is too complex to run
618 /// as a simple example (for example, it needs an extern crate), mark the code
619 /// block with `ignore` and manually replace the `{{produces}}` line with the
620 /// expected output in a `text` code block.
622 /// If this is a rustdoc-only lint, then only include a brief introduction
623 /// with a link with the text `[rustdoc book]` so that the validator knows
624 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
626 /// Commands to view and test the documentation:
628 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
629 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
630 /// correct style, and that the code example actually emits the expected
633 /// If you have already built the compiler, and you want to make changes to
634 /// just the doc comments, then use the `--keep-stage=0` flag with the above
635 /// commands to avoid rebuilding the compiler.
637 macro_rules! declare_lint {
638 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
639 $crate::declare_lint!(
640 $(#[$attr])* $vis $NAME, $Level, $desc,
643 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
644 $(@feature_gate = $gate:expr;)?
645 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
648 $vis static $NAME: &$crate::Lint = &$crate::Lint {
649 name: stringify!($NAME),
650 default_level: $crate::$Level,
652 edition_lint_opts: None,
655 $(feature_gate: Some($gate),)*
656 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
658 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
660 ..$crate::Lint::default_fields_for_macro()
663 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
664 $lint_edition: expr => $edition_level: ident
667 $vis static $NAME: &$crate::Lint = &$crate::Lint {
668 name: stringify!($NAME),
669 default_level: $crate::$Level,
671 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
672 report_in_external_macro: false,
679 macro_rules! declare_tool_lint {
681 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
682 $(, @feature_gate = $gate:expr;)?
684 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?}
687 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
688 report_in_external_macro: $rep:expr
689 $(, @feature_gate = $gate:expr;)?
691 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?}
694 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
696 $(, @feature_gate = $gate:expr;)?
699 $vis static $NAME: &$crate::Lint = &$crate::Lint {
700 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
701 default_level: $crate::$Level,
703 edition_lint_opts: None,
704 report_in_external_macro: $external,
705 future_incompatible: None,
707 $(feature_gate: Some($gate),)?
708 crate_level_only: false,
709 ..$crate::Lint::default_fields_for_macro()
714 /// Declares a static `LintArray` and return it as an expression.
716 macro_rules! lint_array {
717 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
718 ($( $lint:expr ),*) => {{
723 pub type LintArray = Vec<&'static Lint>;
726 fn name(&self) -> &'static str;
729 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
731 macro_rules! impl_lint_pass {
732 ($ty:ty => [$($lint:expr),* $(,)?]) => {
733 impl $crate::LintPass for $ty {
734 fn name(&self) -> &'static str { stringify!($ty) }
737 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
742 /// Declares a type named `$name` which implements `LintPass`.
743 /// To the right of `=>` a comma separated list of `Lint` statics is given.
745 macro_rules! declare_lint_pass {
746 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
747 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
748 $crate::impl_lint_pass!($name => [$($lint),*]);