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 to_cmd_flag(self) -> &'static str {
260 Level::Forbid => "-F",
261 Level::Allow => "-A",
262 Level::ForceWarn(_) => "--force-warn",
263 Level::Expect(_) => {
264 unreachable!("the expect level does not have a commandline flag")
269 pub fn is_error(self) -> bool {
271 Level::Allow | Level::Expect(_) | Level::Warn | Level::ForceWarn(_) => false,
272 Level::Deny | Level::Forbid => true,
276 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
278 Level::Expect(id) | Level::ForceWarn(Some(id)) => Some(*id),
284 /// Specification of a single lint.
285 #[derive(Copy, Clone, Debug)]
287 /// A string identifier for the lint.
289 /// This identifies the lint in attributes and in command-line arguments.
290 /// In those contexts it is always lowercase, but this field is compared
291 /// in a way which is case-insensitive for ASCII characters. This allows
292 /// `declare_lint!()` invocations to follow the convention of upper-case
293 /// statics without repeating the name.
295 /// The name is written with underscores, e.g., "unused_imports".
296 /// On the command line, underscores become dashes.
298 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
299 /// for naming guidelines.
300 pub name: &'static str,
302 /// Default level for the lint.
304 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
305 /// for guidelines on choosing a default level.
306 pub default_level: Level,
308 /// Description of the lint or the issue it detects.
310 /// e.g., "imports that are never used"
311 pub desc: &'static str,
313 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
315 pub edition_lint_opts: Option<(Edition, Level)>,
317 /// `true` if this lint is reported even inside expansions of external macros.
318 pub report_in_external_macro: bool,
320 pub future_incompatible: Option<FutureIncompatibleInfo>,
324 /// `Some` if this lint is feature gated, otherwise `None`.
325 pub feature_gate: Option<Symbol>,
327 pub crate_level_only: bool,
330 /// Extra information for a future incompatibility lint.
331 #[derive(Copy, Clone, Debug)]
332 pub struct FutureIncompatibleInfo {
333 /// e.g., a URL for an issue/PR/RFC or error code
334 pub reference: &'static str,
335 /// The reason for the lint used by diagnostics to provide
336 /// the right help message
337 pub reason: FutureIncompatibilityReason,
338 /// Whether to explain the reason to the user.
340 /// Set to false for lints that already include a more detailed
342 pub explain_reason: bool,
345 /// The reason for future incompatibility
346 #[derive(Copy, Clone, Debug)]
347 pub enum FutureIncompatibilityReason {
348 /// This will be an error in a future release
351 /// This will be an error in a future release, and
352 /// Cargo should create a report even for dependencies
353 FutureReleaseErrorReportNow,
354 /// Code that changes meaning in some way in a
356 FutureReleaseSemanticsChange,
357 /// Previously accepted code that will become an
358 /// error in the provided edition
359 EditionError(Edition),
360 /// Code that changes meaning in some way in
361 /// the provided edition
362 EditionSemanticsChange(Edition),
364 Custom(&'static str),
367 impl FutureIncompatibilityReason {
368 pub fn edition(self) -> Option<Edition> {
370 Self::EditionError(e) => Some(e),
371 Self::EditionSemanticsChange(e) => Some(e),
377 impl FutureIncompatibleInfo {
378 pub const fn default_fields_for_macro() -> Self {
379 FutureIncompatibleInfo {
381 reason: FutureIncompatibilityReason::FutureReleaseError,
382 explain_reason: true,
388 pub const fn default_fields_for_macro() -> Self {
391 default_level: Level::Forbid,
393 edition_lint_opts: None,
395 report_in_external_macro: false,
396 future_incompatible: None,
398 crate_level_only: false,
402 /// Gets the lint's name, with ASCII letters converted to lowercase.
403 pub fn name_lower(&self) -> String {
404 self.name.to_ascii_lowercase()
407 pub fn default_level(&self, edition: Edition) -> Level {
408 self.edition_lint_opts
409 .filter(|(e, _)| *e <= edition)
411 .unwrap_or(self.default_level)
415 /// Identifies a lint known to the compiler.
416 #[derive(Clone, Copy, Debug)]
418 // Identity is based on pointer equality of this field.
419 pub lint: &'static Lint,
422 impl PartialEq for LintId {
423 fn eq(&self, other: &LintId) -> bool {
424 std::ptr::eq(self.lint, other.lint)
428 impl Eq for LintId {}
430 impl std::hash::Hash for LintId {
431 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
432 let ptr = self.lint as *const Lint;
438 /// Gets the `LintId` for a `Lint`.
439 pub fn of(lint: &'static Lint) -> LintId {
443 pub fn lint_name_raw(&self) -> &'static str {
447 /// Gets the name of the lint.
448 pub fn to_string(&self) -> String {
449 self.lint.name_lower()
453 impl<HCX> HashStable<HCX> for LintId {
455 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
456 self.lint_name_raw().hash_stable(hcx, hasher);
460 impl<HCX> ToStableHashKey<HCX> for LintId {
461 type KeyType = &'static str;
464 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
469 // This could be a closure, but then implementing derive trait
470 // becomes hacky (and it gets allocated).
472 pub enum BuiltinLintDiagnostics {
474 AbsPathWithModule(Span),
475 ProcMacroDeriveResolutionFallback(Span),
476 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
477 ElidedLifetimesInPaths(usize, Span, bool, Span),
478 UnknownCrateTypes(Span, String, String),
479 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
480 RedundantImport(Vec<(Span, bool)>, Ident),
481 DeprecatedMacro(Option<Symbol>, Span),
482 MissingAbi(Span, Abi),
483 UnusedDocComment(Span),
484 UnusedBuiltinAttribute {
489 PatternsInFnsWithoutBody(Span, Ident),
490 LegacyDeriveHelpers(Span),
491 ProcMacroBackCompat(String),
492 OrPatternsBackCompat(Span, String),
493 ReservedPrefix(Span),
494 TrailingMacro(bool, Ident),
495 BreakWithLabelAndLoop(Span),
496 NamedAsmLabel(String),
497 UnicodeTextFlow(Span, String),
498 UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
499 DeprecatedWhereclauseLocation(Span, String),
501 /// Span of the parameter which declares this lifetime.
503 /// Span of the code that should be removed when eliding this lifetime.
504 /// This span should include leading or trailing comma.
506 /// Span of the single use, or None if the lifetime is never used.
507 /// If true, the lifetime will be fully elided.
508 use_span: Option<(Span, bool)>,
510 NamedArgumentUsedPositionally {
511 /// Span where the named argument is used by position and will be replaced with the named
513 position_sp_to_replace: Option<Span>,
514 /// Span where the named argument is used by position and is used for lint messages
515 position_sp_for_msg: Option<Span>,
516 /// Span where the named argument's name is (so we know where to put the warning message)
518 /// String containing the named arguments name
519 named_arg_name: String,
520 /// Indicates if the named argument is used as a width/precision for formatting
521 is_formatting_arg: bool,
525 /// Lints that are buffered up early on in the `Session` before the
526 /// `LintLevels` is calculated.
527 pub struct BufferedEarlyLint {
528 /// The span of code that we are linting on.
531 /// The lint message.
532 pub msg: DiagnosticMessage,
534 /// The `NodeId` of the AST node that generated the lint.
537 /// A lint Id that can be passed to
538 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
541 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
542 pub diagnostic: BuiltinLintDiagnostics,
546 pub struct LintBuffer {
547 pub map: NodeMap<Vec<BufferedEarlyLint>>,
551 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
552 let arr = self.map.entry(early_lint.node_id).or_default();
553 arr.push(early_lint);
561 msg: impl Into<DiagnosticMessage>,
562 diagnostic: BuiltinLintDiagnostics,
564 let lint_id = LintId::of(lint);
565 let msg = msg.into();
566 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
569 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
570 self.map.remove(&id).unwrap_or_default()
577 sp: impl Into<MultiSpan>,
578 msg: impl Into<DiagnosticMessage>,
580 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
583 pub fn buffer_lint_with_diagnostic(
587 sp: impl Into<MultiSpan>,
588 msg: impl Into<DiagnosticMessage>,
589 diagnostic: BuiltinLintDiagnostics,
591 self.add_lint(lint, id, sp.into(), msg, diagnostic)
595 /// Declares a static item of type `&'static Lint`.
597 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
598 /// documentation and guidelines on writing lints.
600 /// The macro call should start with a doc comment explaining the lint
601 /// which will be embedded in the rustc user documentation book. It should
602 /// be written in markdown and have a format that looks like this:
604 /// ```rust,ignore (doc-example)
605 /// /// The `my_lint_name` lint detects [short explanation here].
610 /// /// [insert a concise example that triggers the lint]
615 /// /// ### Explanation
617 /// /// This should be a detailed explanation of *why* the lint exists,
618 /// /// and also include suggestions on how the user should fix the problem.
619 /// /// Try to keep the text simple enough that a beginner can understand,
620 /// /// and include links to other documentation for terminology that a
621 /// /// beginner may not be familiar with. If this is "allow" by default,
622 /// /// it should explain why (are there false positives or other issues?). If
623 /// /// this is a future-incompatible lint, it should say so, with text that
624 /// /// looks roughly like this:
626 /// /// This is a [future-incompatible] lint to transition this to a hard
627 /// /// error in the future. See [issue #xxxxx] for more details.
629 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
632 /// The `{{produces}}` tag will be automatically replaced with the output from
633 /// the example by the build system. If the lint example is too complex to run
634 /// as a simple example (for example, it needs an extern crate), mark the code
635 /// block with `ignore` and manually replace the `{{produces}}` line with the
636 /// expected output in a `text` code block.
638 /// If this is a rustdoc-only lint, then only include a brief introduction
639 /// with a link with the text `[rustdoc book]` so that the validator knows
640 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
642 /// Commands to view and test the documentation:
644 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
645 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
646 /// correct style, and that the code example actually emits the expected
649 /// If you have already built the compiler, and you want to make changes to
650 /// just the doc comments, then use the `--keep-stage=0` flag with the above
651 /// commands to avoid rebuilding the compiler.
653 macro_rules! declare_lint {
654 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
655 $crate::declare_lint!(
656 $(#[$attr])* $vis $NAME, $Level, $desc,
659 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
660 $(@feature_gate = $gate:expr;)?
661 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
664 $vis static $NAME: &$crate::Lint = &$crate::Lint {
665 name: stringify!($NAME),
666 default_level: $crate::$Level,
668 edition_lint_opts: None,
671 $(feature_gate: Some($gate),)*
672 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
674 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
676 ..$crate::Lint::default_fields_for_macro()
679 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
680 $lint_edition: expr => $edition_level: ident
683 $vis static $NAME: &$crate::Lint = &$crate::Lint {
684 name: stringify!($NAME),
685 default_level: $crate::$Level,
687 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
688 report_in_external_macro: false,
695 macro_rules! declare_tool_lint {
697 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
698 $(, @feature_gate = $gate:expr;)?
700 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?}
703 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
704 report_in_external_macro: $rep:expr
705 $(, @feature_gate = $gate:expr;)?
707 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?}
710 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
712 $(, @feature_gate = $gate:expr;)?
715 $vis static $NAME: &$crate::Lint = &$crate::Lint {
716 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
717 default_level: $crate::$Level,
719 edition_lint_opts: None,
720 report_in_external_macro: $external,
721 future_incompatible: None,
723 $(feature_gate: Some($gate),)?
724 crate_level_only: false,
725 ..$crate::Lint::default_fields_for_macro()
730 /// Declares a static `LintArray` and return it as an expression.
732 macro_rules! lint_array {
733 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
734 ($( $lint:expr ),*) => {{
739 pub type LintArray = Vec<&'static Lint>;
742 fn name(&self) -> &'static str;
745 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
747 macro_rules! impl_lint_pass {
748 ($ty:ty => [$($lint:expr),* $(,)?]) => {
749 impl $crate::LintPass for $ty {
750 fn name(&self) -> &'static str { stringify!($ty) }
753 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
758 /// Declares a type named `$name` which implements `LintPass`.
759 /// To the right of `=>` a comma separated list of `Lint` statics is given.
761 macro_rules! declare_lint_pass {
762 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
763 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
764 $crate::impl_lint_pass!($name => [$($lint),*]);