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> },
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
121 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId {
123 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
125 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
126 hir_id.hash_stable(hcx, hasher);
127 attr_index.hash_stable(hcx, hasher);
128 lint_index.hash_stable(hcx, hasher);
132 "HashStable should only be called for filled and stable `LintExpectationId`"
139 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
140 type KeyType = (HirId, u16, u16);
143 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
145 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
146 (*hir_id, *attr_index, *lint_index)
149 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
155 /// Setting for how to handle a lint.
157 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
158 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, HashStable_Generic)]
160 /// The `allow` level will not issue any message.
162 /// The `expect` level will suppress the lint message but in turn produce a message
163 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
164 /// an initial level for a lint.
166 /// Note that this still means that the lint is enabled in this position and should
167 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
171 /// The [`LintExpectationId`] is used to later link a lint emission to the actual
172 /// expectation. It can be ignored in most cases.
173 Expect(LintExpectationId),
174 /// The `warn` level will produce a warning if the lint was violated, however the
175 /// compiler will continue with its execution.
177 /// This lint level is a special case of [`Warn`], that can't be overridden. This is used
178 /// to ensure that a lint can't be suppressed. This lint level can currently only be set
179 /// via the console and is therefore session specific.
181 /// The [`LintExpectationId`] is intended to fulfill expectations marked via the
182 /// `#[expect]` attribute, that will still be suppressed due to the level.
183 ForceWarn(Option<LintExpectationId>),
184 /// The `deny` level will produce an error and stop further execution after the lint
185 /// pass is complete.
187 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
193 /// Converts a level to a lower-case string.
194 pub fn as_str(self) -> &'static str {
196 Level::Allow => "allow",
197 Level::Expect(_) => "expect",
198 Level::Warn => "warn",
199 Level::ForceWarn(_) => "force-warn",
200 Level::Deny => "deny",
201 Level::Forbid => "forbid",
205 /// Converts a lower-case string to a level. This will never construct the expect
206 /// level as that would require a [`LintExpectationId`]
207 pub fn from_str(x: &str) -> Option<Level> {
209 "allow" => Some(Level::Allow),
210 "warn" => Some(Level::Warn),
211 "deny" => Some(Level::Deny),
212 "forbid" => Some(Level::Forbid),
213 "expect" | _ => None,
217 /// Converts a symbol to a level.
218 pub fn from_attr(attr: &Attribute) -> Option<Level> {
219 match attr.name_or_empty() {
220 sym::allow => Some(Level::Allow),
221 sym::expect => Some(Level::Expect(LintExpectationId::Unstable {
225 sym::warn => Some(Level::Warn),
226 sym::deny => Some(Level::Deny),
227 sym::forbid => Some(Level::Forbid),
232 pub fn is_error(self) -> bool {
234 Level::Allow | Level::Expect(_) | Level::Warn | Level::ForceWarn(_) => false,
235 Level::Deny | Level::Forbid => true,
239 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
241 Level::Expect(id) | Level::ForceWarn(Some(id)) => Some(*id),
247 /// Specification of a single lint.
248 #[derive(Copy, Clone, Debug)]
250 /// A string identifier for the lint.
252 /// This identifies the lint in attributes and in command-line arguments.
253 /// In those contexts it is always lowercase, but this field is compared
254 /// in a way which is case-insensitive for ASCII characters. This allows
255 /// `declare_lint!()` invocations to follow the convention of upper-case
256 /// statics without repeating the name.
258 /// The name is written with underscores, e.g., "unused_imports".
259 /// On the command line, underscores become dashes.
261 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
262 /// for naming guidelines.
263 pub name: &'static str,
265 /// Default level for the lint.
267 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
268 /// for guidelines on choosing a default level.
269 pub default_level: Level,
271 /// Description of the lint or the issue it detects.
273 /// e.g., "imports that are never used"
274 pub desc: &'static str,
276 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
278 pub edition_lint_opts: Option<(Edition, Level)>,
280 /// `true` if this lint is reported even inside expansions of external macros.
281 pub report_in_external_macro: bool,
283 pub future_incompatible: Option<FutureIncompatibleInfo>,
287 /// `Some` if this lint is feature gated, otherwise `None`.
288 pub feature_gate: Option<Symbol>,
290 pub crate_level_only: bool,
293 /// Extra information for a future incompatibility lint.
294 #[derive(Copy, Clone, Debug)]
295 pub struct FutureIncompatibleInfo {
296 /// e.g., a URL for an issue/PR/RFC or error code
297 pub reference: &'static str,
298 /// The reason for the lint used by diagnostics to provide
299 /// the right help message
300 pub reason: FutureIncompatibilityReason,
301 /// Whether to explain the reason to the user.
303 /// Set to false for lints that already include a more detailed
305 pub explain_reason: bool,
308 /// The reason for future incompatibility
309 #[derive(Copy, Clone, Debug)]
310 pub enum FutureIncompatibilityReason {
311 /// This will be an error in a future release
314 /// This will be an error in a future release, and
315 /// Cargo should create a report even for dependencies
316 FutureReleaseErrorReportNow,
317 /// Code that changes meaning in some way in a
319 FutureReleaseSemanticsChange,
320 /// Previously accepted code that will become an
321 /// error in the provided edition
322 EditionError(Edition),
323 /// Code that changes meaning in some way in
324 /// the provided edition
325 EditionSemanticsChange(Edition),
327 Custom(&'static str),
330 impl FutureIncompatibilityReason {
331 pub fn edition(self) -> Option<Edition> {
333 Self::EditionError(e) => Some(e),
334 Self::EditionSemanticsChange(e) => Some(e),
340 impl FutureIncompatibleInfo {
341 pub const fn default_fields_for_macro() -> Self {
342 FutureIncompatibleInfo {
344 reason: FutureIncompatibilityReason::FutureReleaseError,
345 explain_reason: true,
351 pub const fn default_fields_for_macro() -> Self {
354 default_level: Level::Forbid,
356 edition_lint_opts: None,
358 report_in_external_macro: false,
359 future_incompatible: None,
361 crate_level_only: false,
365 /// Gets the lint's name, with ASCII letters converted to lowercase.
366 pub fn name_lower(&self) -> String {
367 self.name.to_ascii_lowercase()
370 pub fn default_level(&self, edition: Edition) -> Level {
371 self.edition_lint_opts
372 .filter(|(e, _)| *e <= edition)
374 .unwrap_or(self.default_level)
378 /// Identifies a lint known to the compiler.
379 #[derive(Clone, Copy, Debug)]
381 // Identity is based on pointer equality of this field.
382 pub lint: &'static Lint,
385 impl PartialEq for LintId {
386 fn eq(&self, other: &LintId) -> bool {
387 std::ptr::eq(self.lint, other.lint)
391 impl Eq for LintId {}
393 impl std::hash::Hash for LintId {
394 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
395 let ptr = self.lint as *const Lint;
401 /// Gets the `LintId` for a `Lint`.
402 pub fn of(lint: &'static Lint) -> LintId {
406 pub fn lint_name_raw(&self) -> &'static str {
410 /// Gets the name of the lint.
411 pub fn to_string(&self) -> String {
412 self.lint.name_lower()
416 impl<HCX> HashStable<HCX> for LintId {
418 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
419 self.lint_name_raw().hash_stable(hcx, hasher);
423 impl<HCX> ToStableHashKey<HCX> for LintId {
424 type KeyType = &'static str;
427 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
432 // This could be a closure, but then implementing derive trait
433 // becomes hacky (and it gets allocated).
435 pub enum BuiltinLintDiagnostics {
437 AbsPathWithModule(Span),
438 ProcMacroDeriveResolutionFallback(Span),
439 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
440 ElidedLifetimesInPaths(usize, Span, bool, Span),
441 UnknownCrateTypes(Span, String, String),
442 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
443 RedundantImport(Vec<(Span, bool)>, Ident),
444 DeprecatedMacro(Option<Symbol>, Span),
445 MissingAbi(Span, Abi),
446 UnusedDocComment(Span),
447 UnusedBuiltinAttribute {
452 PatternsInFnsWithoutBody(Span, Ident),
453 LegacyDeriveHelpers(Span),
454 ProcMacroBackCompat(String),
455 OrPatternsBackCompat(Span, String),
456 ReservedPrefix(Span),
457 TrailingMacro(bool, Ident),
458 BreakWithLabelAndLoop(Span),
459 NamedAsmLabel(String),
460 UnicodeTextFlow(Span, String),
461 UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
462 DeprecatedWhereclauseLocation(Span, String),
464 /// Span of the parameter which declares this lifetime.
466 /// Span of the code that should be removed when eliding this lifetime.
467 /// This span should include leading or trailing comma.
469 /// Span of the single use, or None if the lifetime is never used.
470 /// If true, the lifetime will be fully elided.
471 use_span: Option<(Span, bool)>,
473 NamedArgumentUsedPositionally {
474 /// Span where the named argument is used by position and will be replaced with the named
476 position_sp_to_replace: Option<Span>,
477 /// Span where the named argument is used by position and is used for lint messages
478 position_sp_for_msg: Option<Span>,
479 /// Span where the named argument's name is (so we know where to put the warning message)
481 /// String containing the named arguments name
482 named_arg_name: String,
483 /// Indicates if the named argument is used as a width/precision for formatting
484 is_formatting_arg: bool,
488 /// Lints that are buffered up early on in the `Session` before the
489 /// `LintLevels` is calculated.
490 pub struct BufferedEarlyLint {
491 /// The span of code that we are linting on.
494 /// The lint message.
495 pub msg: DiagnosticMessage,
497 /// The `NodeId` of the AST node that generated the lint.
500 /// A lint Id that can be passed to
501 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
504 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
505 pub diagnostic: BuiltinLintDiagnostics,
509 pub struct LintBuffer {
510 pub map: NodeMap<Vec<BufferedEarlyLint>>,
514 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
515 let arr = self.map.entry(early_lint.node_id).or_default();
516 arr.push(early_lint);
524 msg: impl Into<DiagnosticMessage>,
525 diagnostic: BuiltinLintDiagnostics,
527 let lint_id = LintId::of(lint);
528 let msg = msg.into();
529 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
532 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
533 self.map.remove(&id).unwrap_or_default()
540 sp: impl Into<MultiSpan>,
541 msg: impl Into<DiagnosticMessage>,
543 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
546 pub fn buffer_lint_with_diagnostic(
550 sp: impl Into<MultiSpan>,
551 msg: impl Into<DiagnosticMessage>,
552 diagnostic: BuiltinLintDiagnostics,
554 self.add_lint(lint, id, sp.into(), msg, diagnostic)
558 /// Declares a static item of type `&'static Lint`.
560 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
561 /// documentation and guidelines on writing lints.
563 /// The macro call should start with a doc comment explaining the lint
564 /// which will be embedded in the rustc user documentation book. It should
565 /// be written in markdown and have a format that looks like this:
567 /// ```rust,ignore (doc-example)
568 /// /// The `my_lint_name` lint detects [short explanation here].
573 /// /// [insert a concise example that triggers the lint]
578 /// /// ### Explanation
580 /// /// This should be a detailed explanation of *why* the lint exists,
581 /// /// and also include suggestions on how the user should fix the problem.
582 /// /// Try to keep the text simple enough that a beginner can understand,
583 /// /// and include links to other documentation for terminology that a
584 /// /// beginner may not be familiar with. If this is "allow" by default,
585 /// /// it should explain why (are there false positives or other issues?). If
586 /// /// this is a future-incompatible lint, it should say so, with text that
587 /// /// looks roughly like this:
589 /// /// This is a [future-incompatible] lint to transition this to a hard
590 /// /// error in the future. See [issue #xxxxx] for more details.
592 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
595 /// The `{{produces}}` tag will be automatically replaced with the output from
596 /// the example by the build system. If the lint example is too complex to run
597 /// as a simple example (for example, it needs an extern crate), mark the code
598 /// block with `ignore` and manually replace the `{{produces}}` line with the
599 /// expected output in a `text` code block.
601 /// If this is a rustdoc-only lint, then only include a brief introduction
602 /// with a link with the text `[rustdoc book]` so that the validator knows
603 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
605 /// Commands to view and test the documentation:
607 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
608 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
609 /// correct style, and that the code example actually emits the expected
612 /// If you have already built the compiler, and you want to make changes to
613 /// just the doc comments, then use the `--keep-stage=0` flag with the above
614 /// commands to avoid rebuilding the compiler.
616 macro_rules! declare_lint {
617 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
618 $crate::declare_lint!(
619 $(#[$attr])* $vis $NAME, $Level, $desc,
622 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
623 $(@feature_gate = $gate:expr;)?
624 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
627 $vis static $NAME: &$crate::Lint = &$crate::Lint {
628 name: stringify!($NAME),
629 default_level: $crate::$Level,
631 edition_lint_opts: None,
634 $(feature_gate: Some($gate),)*
635 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
637 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
639 ..$crate::Lint::default_fields_for_macro()
642 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
643 $lint_edition: expr => $edition_level: ident
646 $vis static $NAME: &$crate::Lint = &$crate::Lint {
647 name: stringify!($NAME),
648 default_level: $crate::$Level,
650 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
651 report_in_external_macro: false,
658 macro_rules! declare_tool_lint {
660 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
662 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
665 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
666 report_in_external_macro: $rep:expr
668 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
671 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
675 $vis static $NAME: &$crate::Lint = &$crate::Lint {
676 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
677 default_level: $crate::$Level,
679 edition_lint_opts: None,
680 report_in_external_macro: $external,
681 future_incompatible: None,
684 crate_level_only: false,
689 /// Declares a static `LintArray` and return it as an expression.
691 macro_rules! lint_array {
692 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
693 ($( $lint:expr ),*) => {{
698 pub type LintArray = Vec<&'static Lint>;
701 fn name(&self) -> &'static str;
704 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
706 macro_rules! impl_lint_pass {
707 ($ty:ty => [$($lint:expr),* $(,)?]) => {
708 impl $crate::LintPass for $ty {
709 fn name(&self) -> &'static str { stringify!($ty) }
712 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
717 /// Declares a type named `$name` which implements `LintPass`.
718 /// To the right of `=>` a comma separated list of `Lint` statics is given.
720 macro_rules! declare_lint_pass {
721 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
722 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
723 $crate::impl_lint_pass!($name => [$($lint),*]);