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;
10 use rustc_ast::{AttrId, Attribute};
11 use rustc_data_structures::fx::FxIndexMap;
12 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
13 use rustc_error_messages::{DiagnosticMessage, MultiSpan};
14 use rustc_hir::HashStableContext;
16 use rustc_span::edition::Edition;
17 use rustc_span::{sym, symbol::Ident, Span, Symbol};
18 use rustc_target::spec::abi::Abi;
20 use serde::{Deserialize, Serialize};
25 macro_rules! pluralize {
27 if $x != 1 { "s" } else { "" }
30 if $x == 1 { "has" } else { "have" }
33 if $x == 1 { "is" } else { "are" }
36 if $x == 1 { "was" } else { "were" }
38 ("this", $x:expr) => {
39 if $x == 1 { "this" } else { "these" }
43 /// Indicates the confidence in the correctness of a suggestion.
45 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
46 /// to determine whether it should be automatically applied or if the user should be consulted
47 /// before applying the suggestion.
48 #[derive(Copy, Clone, Debug, Hash, Encodable, Decodable, Serialize, Deserialize)]
49 #[derive(PartialEq, Eq, PartialOrd, Ord)]
50 pub enum Applicability {
51 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
52 /// This suggestion should be automatically applied.
54 /// In case of multiple `MachineApplicable` suggestions (whether as part of
55 /// the same `multipart_suggestion` or not), all of them should be
56 /// automatically applied.
59 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
60 /// result in valid Rust code if it is applied.
63 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
64 /// cannot be applied automatically because it will not result in valid Rust code. The user
65 /// will need to fill in the placeholders.
68 /// The applicability of the suggestion is unknown.
72 /// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
73 /// Expected `Diagnostic`s get the lint level `Expect` which stores the `LintExpectationId`
74 /// to match it with the actual expectation later on.
76 /// The `LintExpectationId` has to be stable between compilations, as diagnostic
77 /// instances might be loaded from cache. Lint messages can be emitted during an
78 /// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
79 /// HIR tree. The AST doesn't have enough information to create a stable id. The
80 /// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
81 /// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
82 /// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
84 /// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
85 /// identifies the lint inside the attribute and ensures that the IDs are unique.
87 /// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
88 /// It's reasonable to assume that no user will define 2^16 attributes on one node or
89 /// have that amount of lints listed. `u16` values should therefore suffice.
90 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Encodable, Decodable)]
91 pub enum LintExpectationId {
92 /// Used for lints emitted during the `EarlyLintPass`. This id is not
93 /// hash stable and should not be cached.
94 Unstable { attr_id: AttrId, lint_index: Option<u16> },
95 /// The [`HirId`] that the lint expectation is attached to. This id is
96 /// stable and can be cached. The additional index ensures that nodes with
97 /// several expectations can correctly match diagnostics to the individual
99 Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16>, attr_id: Option<AttrId> },
102 impl LintExpectationId {
103 pub fn is_stable(&self) -> bool {
105 LintExpectationId::Unstable { .. } => false,
106 LintExpectationId::Stable { .. } => true,
110 pub fn get_lint_index(&self) -> Option<u16> {
111 let (LintExpectationId::Unstable { lint_index, .. }
112 | LintExpectationId::Stable { lint_index, .. }) = self;
117 pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
118 let (LintExpectationId::Unstable { ref mut lint_index, .. }
119 | LintExpectationId::Stable { ref mut lint_index, .. }) = self;
121 *lint_index = new_lint_index
124 /// Prepares the id for hashing. Removes references to the ast.
125 /// Should only be called when the id is stable.
126 pub fn normalize(self) -> Self {
128 Self::Stable { hir_id, attr_index, lint_index, .. } => {
129 Self::Stable { hir_id, attr_index, lint_index, attr_id: None }
131 Self::Unstable { .. } => {
132 unreachable!("`normalize` called when `ExpectationId` is unstable")
138 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId {
140 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
142 LintExpectationId::Stable {
145 lint_index: Some(lint_index),
148 hir_id.hash_stable(hcx, hasher);
149 attr_index.hash_stable(hcx, hasher);
150 lint_index.hash_stable(hcx, hasher);
154 "HashStable should only be called for filled and stable `LintExpectationId`"
161 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
162 type KeyType = (HirId, u16, u16);
165 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
167 LintExpectationId::Stable {
170 lint_index: Some(lint_index),
172 } => (*hir_id, *attr_index, *lint_index),
174 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
180 /// Setting for how to handle a lint.
182 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
183 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, HashStable_Generic)]
185 /// The `allow` level will not issue any message.
187 /// The `expect` level will suppress the lint message but in turn produce a message
188 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
189 /// an initial level for a lint.
191 /// Note that this still means that the lint is enabled in this position and should
192 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
196 /// The [`LintExpectationId`] is used to later link a lint emission to the actual
197 /// expectation. It can be ignored in most cases.
198 Expect(LintExpectationId),
199 /// The `warn` level will produce a warning if the lint was violated, however the
200 /// compiler will continue with its execution.
202 /// This lint level is a special case of [`Warn`], that can't be overridden. This is used
203 /// to ensure that a lint can't be suppressed. This lint level can currently only be set
204 /// via the console and is therefore session specific.
206 /// The [`LintExpectationId`] is intended to fulfill expectations marked via the
207 /// `#[expect]` attribute, that will still be suppressed due to the level.
208 ForceWarn(Option<LintExpectationId>),
209 /// The `deny` level will produce an error and stop further execution after the lint
210 /// pass is complete.
212 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
218 /// Converts a level to a lower-case string.
219 pub fn as_str(self) -> &'static str {
221 Level::Allow => "allow",
222 Level::Expect(_) => "expect",
223 Level::Warn => "warn",
224 Level::ForceWarn(_) => "force-warn",
225 Level::Deny => "deny",
226 Level::Forbid => "forbid",
230 /// Converts a lower-case string to a level. This will never construct the expect
231 /// level as that would require a [`LintExpectationId`]
232 pub fn from_str(x: &str) -> Option<Level> {
234 "allow" => Some(Level::Allow),
235 "warn" => Some(Level::Warn),
236 "deny" => Some(Level::Deny),
237 "forbid" => Some(Level::Forbid),
238 "expect" | _ => None,
242 /// Converts a symbol to a level.
243 pub fn from_attr(attr: &Attribute) -> Option<Level> {
244 match attr.name_or_empty() {
245 sym::allow => Some(Level::Allow),
246 sym::expect => Some(Level::Expect(LintExpectationId::Unstable {
250 sym::warn => Some(Level::Warn),
251 sym::deny => Some(Level::Deny),
252 sym::forbid => Some(Level::Forbid),
257 pub fn to_cmd_flag(self) -> &'static str {
261 Level::Forbid => "-F",
262 Level::Allow => "-A",
263 Level::ForceWarn(_) => "--force-warn",
264 Level::Expect(_) => {
265 unreachable!("the expect level does not have a commandline flag")
270 pub fn is_error(self) -> bool {
272 Level::Allow | Level::Expect(_) | Level::Warn | Level::ForceWarn(_) => false,
273 Level::Deny | Level::Forbid => true,
277 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
279 Level::Expect(id) | Level::ForceWarn(Some(id)) => Some(*id),
285 /// Specification of a single lint.
286 #[derive(Copy, Clone, Debug)]
288 /// A string identifier for the lint.
290 /// This identifies the lint in attributes and in command-line arguments.
291 /// In those contexts it is always lowercase, but this field is compared
292 /// in a way which is case-insensitive for ASCII characters. This allows
293 /// `declare_lint!()` invocations to follow the convention of upper-case
294 /// statics without repeating the name.
296 /// The name is written with underscores, e.g., "unused_imports".
297 /// On the command line, underscores become dashes.
299 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
300 /// for naming guidelines.
301 pub name: &'static str,
303 /// Default level for the lint.
305 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
306 /// for guidelines on choosing a default level.
307 pub default_level: Level,
309 /// Description of the lint or the issue it detects.
311 /// e.g., "imports that are never used"
312 pub desc: &'static str,
314 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
316 pub edition_lint_opts: Option<(Edition, Level)>,
318 /// `true` if this lint is reported even inside expansions of external macros.
319 pub report_in_external_macro: bool,
321 pub future_incompatible: Option<FutureIncompatibleInfo>,
325 /// `Some` if this lint is feature gated, otherwise `None`.
326 pub feature_gate: Option<Symbol>,
328 pub crate_level_only: bool,
331 /// Extra information for a future incompatibility lint.
332 #[derive(Copy, Clone, Debug)]
333 pub struct FutureIncompatibleInfo {
334 /// e.g., a URL for an issue/PR/RFC or error code
335 pub reference: &'static str,
336 /// The reason for the lint used by diagnostics to provide
337 /// the right help message
338 pub reason: FutureIncompatibilityReason,
339 /// Whether to explain the reason to the user.
341 /// Set to false for lints that already include a more detailed
343 pub explain_reason: bool,
346 /// The reason for future incompatibility
347 #[derive(Copy, Clone, Debug)]
348 pub enum FutureIncompatibilityReason {
349 /// This will be an error in a future release
352 /// This will be an error in a future release, and
353 /// Cargo should create a report even for dependencies
354 FutureReleaseErrorReportNow,
355 /// Code that changes meaning in some way in a
357 FutureReleaseSemanticsChange,
358 /// Previously accepted code that will become an
359 /// error in the provided edition
360 EditionError(Edition),
361 /// Code that changes meaning in some way in
362 /// the provided edition
363 EditionSemanticsChange(Edition),
365 Custom(&'static str),
368 impl FutureIncompatibilityReason {
369 pub fn edition(self) -> Option<Edition> {
371 Self::EditionError(e) => Some(e),
372 Self::EditionSemanticsChange(e) => Some(e),
378 impl FutureIncompatibleInfo {
379 pub const fn default_fields_for_macro() -> Self {
380 FutureIncompatibleInfo {
382 reason: FutureIncompatibilityReason::FutureReleaseError,
383 explain_reason: true,
389 pub const fn default_fields_for_macro() -> Self {
392 default_level: Level::Forbid,
394 edition_lint_opts: None,
396 report_in_external_macro: false,
397 future_incompatible: None,
399 crate_level_only: false,
403 /// Gets the lint's name, with ASCII letters converted to lowercase.
404 pub fn name_lower(&self) -> String {
405 self.name.to_ascii_lowercase()
408 pub fn default_level(&self, edition: Edition) -> Level {
409 self.edition_lint_opts
410 .filter(|(e, _)| *e <= edition)
412 .unwrap_or(self.default_level)
416 /// Identifies a lint known to the compiler.
417 #[derive(Clone, Copy, Debug)]
419 // Identity is based on pointer equality of this field.
420 pub lint: &'static Lint,
423 impl PartialEq for LintId {
424 fn eq(&self, other: &LintId) -> bool {
425 std::ptr::eq(self.lint, other.lint)
429 impl Eq for LintId {}
431 impl std::hash::Hash for LintId {
432 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
433 let ptr = self.lint as *const Lint;
439 /// Gets the `LintId` for a `Lint`.
440 pub fn of(lint: &'static Lint) -> LintId {
444 pub fn lint_name_raw(&self) -> &'static str {
448 /// Gets the name of the lint.
449 pub fn to_string(&self) -> String {
450 self.lint.name_lower()
454 impl<HCX> HashStable<HCX> for LintId {
456 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
457 self.lint_name_raw().hash_stable(hcx, hasher);
461 impl<HCX> ToStableHashKey<HCX> for LintId {
462 type KeyType = &'static str;
465 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
470 // This could be a closure, but then implementing derive trait
471 // becomes hacky (and it gets allocated).
473 pub enum BuiltinLintDiagnostics {
475 AbsPathWithModule(Span),
476 ProcMacroDeriveResolutionFallback(Span),
477 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
478 ElidedLifetimesInPaths(usize, Span, bool, Span),
479 UnknownCrateTypes(Span, String, String),
480 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
481 RedundantImport(Vec<(Span, bool)>, Ident),
482 DeprecatedMacro(Option<Symbol>, Span),
483 MissingAbi(Span, Abi),
484 UnusedDocComment(Span),
485 UnusedBuiltinAttribute {
490 PatternsInFnsWithoutBody(Span, Ident),
491 LegacyDeriveHelpers(Span),
492 ProcMacroBackCompat(String),
493 OrPatternsBackCompat(Span, String),
494 ReservedPrefix(Span),
495 TrailingMacro(bool, Ident),
496 BreakWithLabelAndLoop(Span),
497 NamedAsmLabel(String),
498 UnicodeTextFlow(Span, String),
499 UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
500 DeprecatedWhereclauseLocation(Span, String),
502 /// Span of the parameter which declares this lifetime.
504 /// Span of the code that should be removed when eliding this lifetime.
505 /// This span should include leading or trailing comma.
506 deletion_span: Option<Span>,
507 /// Span of the single use, or None if the lifetime is never used.
508 /// If true, the lifetime will be fully elided.
509 use_span: Option<(Span, bool)>,
511 NamedArgumentUsedPositionally {
512 /// Span where the named argument is used by position and will be replaced with the named
514 position_sp_to_replace: Option<Span>,
515 /// Span where the named argument is used by position and is used for lint messages
516 position_sp_for_msg: Option<Span>,
517 /// Span where the named argument's name is (so we know where to put the warning message)
519 /// String containing the named arguments name
520 named_arg_name: String,
521 /// Indicates if the named argument is used as a width/precision for formatting
522 is_formatting_arg: bool,
524 ByteSliceInPackedStructWithDerive,
527 /// Lints that are buffered up early on in the `Session` before the
528 /// `LintLevels` is calculated.
529 pub struct BufferedEarlyLint {
530 /// The span of code that we are linting on.
533 /// The lint message.
534 pub msg: DiagnosticMessage,
536 /// The `NodeId` of the AST node that generated the lint.
539 /// A lint Id that can be passed to
540 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
543 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
544 pub diagnostic: BuiltinLintDiagnostics,
548 pub struct LintBuffer {
549 pub map: FxIndexMap<NodeId, Vec<BufferedEarlyLint>>,
553 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
554 let arr = self.map.entry(early_lint.node_id).or_default();
555 arr.push(early_lint);
563 msg: impl Into<DiagnosticMessage>,
564 diagnostic: BuiltinLintDiagnostics,
566 let lint_id = LintId::of(lint);
567 let msg = msg.into();
568 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
571 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
572 self.map.remove(&id).unwrap_or_default()
579 sp: impl Into<MultiSpan>,
580 msg: impl Into<DiagnosticMessage>,
582 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
585 pub fn buffer_lint_with_diagnostic(
589 sp: impl Into<MultiSpan>,
590 msg: impl Into<DiagnosticMessage>,
591 diagnostic: BuiltinLintDiagnostics,
593 self.add_lint(lint, id, sp.into(), msg, diagnostic)
597 /// Declares a static item of type `&'static Lint`.
599 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
600 /// documentation and guidelines on writing lints.
602 /// The macro call should start with a doc comment explaining the lint
603 /// which will be embedded in the rustc user documentation book. It should
604 /// be written in markdown and have a format that looks like this:
606 /// ```rust,ignore (doc-example)
607 /// /// The `my_lint_name` lint detects [short explanation here].
612 /// /// [insert a concise example that triggers the lint]
617 /// /// ### Explanation
619 /// /// This should be a detailed explanation of *why* the lint exists,
620 /// /// and also include suggestions on how the user should fix the problem.
621 /// /// Try to keep the text simple enough that a beginner can understand,
622 /// /// and include links to other documentation for terminology that a
623 /// /// beginner may not be familiar with. If this is "allow" by default,
624 /// /// it should explain why (are there false positives or other issues?). If
625 /// /// this is a future-incompatible lint, it should say so, with text that
626 /// /// looks roughly like this:
628 /// /// This is a [future-incompatible] lint to transition this to a hard
629 /// /// error in the future. See [issue #xxxxx] for more details.
631 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
634 /// The `{{produces}}` tag will be automatically replaced with the output from
635 /// the example by the build system. If the lint example is too complex to run
636 /// as a simple example (for example, it needs an extern crate), mark the code
637 /// block with `ignore` and manually replace the `{{produces}}` line with the
638 /// expected output in a `text` code block.
640 /// If this is a rustdoc-only lint, then only include a brief introduction
641 /// with a link with the text `[rustdoc book]` so that the validator knows
642 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
644 /// Commands to view and test the documentation:
646 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
647 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
648 /// correct style, and that the code example actually emits the expected
651 /// If you have already built the compiler, and you want to make changes to
652 /// just the doc comments, then use the `--keep-stage=0` flag with the above
653 /// commands to avoid rebuilding the compiler.
655 macro_rules! declare_lint {
656 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
657 $crate::declare_lint!(
658 $(#[$attr])* $vis $NAME, $Level, $desc,
661 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
662 $(@feature_gate = $gate:expr;)?
663 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
666 $vis static $NAME: &$crate::Lint = &$crate::Lint {
667 name: stringify!($NAME),
668 default_level: $crate::$Level,
670 edition_lint_opts: None,
673 $(feature_gate: Some($gate),)*
674 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
676 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
678 ..$crate::Lint::default_fields_for_macro()
681 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
682 $lint_edition: expr => $edition_level: ident
685 $vis static $NAME: &$crate::Lint = &$crate::Lint {
686 name: stringify!($NAME),
687 default_level: $crate::$Level,
689 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
690 report_in_external_macro: false,
697 macro_rules! declare_tool_lint {
699 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
700 $(, @feature_gate = $gate:expr;)?
702 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?}
705 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
706 report_in_external_macro: $rep:expr
707 $(, @feature_gate = $gate:expr;)?
709 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?}
712 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
714 $(, @feature_gate = $gate:expr;)?
717 $vis static $NAME: &$crate::Lint = &$crate::Lint {
718 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
719 default_level: $crate::$Level,
721 edition_lint_opts: None,
722 report_in_external_macro: $external,
723 future_incompatible: None,
725 $(feature_gate: Some($gate),)?
726 crate_level_only: false,
727 ..$crate::Lint::default_fields_for_macro()
732 /// Declares a static `LintArray` and return it as an expression.
734 macro_rules! lint_array {
735 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
736 ($( $lint:expr ),*) => {{
741 pub type LintArray = Vec<&'static Lint>;
744 fn name(&self) -> &'static str;
747 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
749 macro_rules! impl_lint_pass {
750 ($ty:ty => [$($lint:expr),* $(,)?]) => {
751 impl $crate::LintPass for $ty {
752 fn name(&self) -> &'static str { stringify!($ty) }
755 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
760 /// Declares a type named `$name` which implements `LintPass`.
761 /// To the right of `=>` a comma separated list of `Lint` statics is given.
763 macro_rules! declare_lint_pass {
764 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
765 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
766 $crate::impl_lint_pass!($name => [$($lint),*]);