1 #![feature(min_specialization)]
4 extern crate rustc_macros;
6 pub use self::Level::*;
7 use rustc_ast::node_id::{NodeId, NodeMap};
8 use rustc_ast::{AttrId, Attribute};
9 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
10 use rustc_error_messages::MultiSpan;
11 use rustc_hir::HashStableContext;
13 use rustc_span::edition::Edition;
14 use rustc_span::{sym, symbol::Ident, Span, Symbol};
15 use rustc_target::spec::abi::Abi;
17 use serde::{Deserialize, Serialize};
22 macro_rules! pluralize {
24 if $x != 1 { "s" } else { "" }
27 if $x == 1 { "is" } else { "are" }
30 if $x == 1 { "was" } else { "were" }
32 ("this", $x:expr) => {
33 if $x == 1 { "this" } else { "these" }
37 /// Indicates the confidence in the correctness of a suggestion.
39 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
40 /// to determine whether it should be automatically applied or if the user should be consulted
41 /// before applying the suggestion.
42 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable, Serialize, Deserialize)]
43 pub enum Applicability {
44 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
45 /// This suggestion should be automatically applied.
47 /// In case of multiple `MachineApplicable` suggestions (whether as part of
48 /// the same `multipart_suggestion` or not), all of them should be
49 /// automatically applied.
52 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
53 /// result in valid Rust code if it is applied.
56 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
57 /// cannot be applied automatically because it will not result in valid Rust code. The user
58 /// will need to fill in the placeholders.
61 /// The applicability of the suggestion is unknown.
65 /// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
66 /// Expected `Diagnostic`s get the lint level `Expect` which stores the `LintExpectationId`
67 /// to match it with the actual expectation later on.
69 /// The `LintExpectationId` has to be stable between compilations, as diagnostic
70 /// instances might be loaded from cache. Lint messages can be emitted during an
71 /// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
72 /// HIR tree. The AST doesn't have enough information to create a stable id. The
73 /// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
74 /// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
75 /// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
77 /// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
78 /// identifies the lint inside the attribute and ensures that the IDs are unique.
80 /// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
81 /// It's reasonable to assume that no user will define 2^16 attributes on one node or
82 /// have that amount of lints listed. `u16` values should therefore suffice.
83 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Encodable, Decodable)]
84 pub enum LintExpectationId {
85 /// Used for lints emitted during the `EarlyLintPass`. This id is not
86 /// hash stable and should not be cached.
87 Unstable { attr_id: AttrId, lint_index: Option<u16> },
88 /// The [`HirId`] that the lint expectation is attached to. This id is
89 /// stable and can be cached. The additional index ensures that nodes with
90 /// several expectations can correctly match diagnostics to the individual
92 Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16> },
95 impl LintExpectationId {
96 pub fn is_stable(&self) -> bool {
98 LintExpectationId::Unstable { .. } => false,
99 LintExpectationId::Stable { .. } => true,
103 pub fn get_lint_index(&self) -> Option<u16> {
104 let (LintExpectationId::Unstable { lint_index, .. }
105 | LintExpectationId::Stable { lint_index, .. }) = self;
110 pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
111 let (LintExpectationId::Unstable { ref mut lint_index, .. }
112 | LintExpectationId::Stable { ref mut lint_index, .. }) = self;
114 *lint_index = new_lint_index
118 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId {
120 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
122 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
123 hir_id.hash_stable(hcx, hasher);
124 attr_index.hash_stable(hcx, hasher);
125 lint_index.hash_stable(hcx, hasher);
129 "HashStable should only be called for filled and stable `LintExpectationId`"
136 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
137 type KeyType = (HirId, u16, u16);
140 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
142 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
143 (*hir_id, *attr_index, *lint_index)
146 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
152 /// Setting for how to handle a lint.
154 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
155 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, HashStable_Generic)]
157 /// The `allow` level will not issue any message.
159 /// The `expect` level will suppress the lint message but in turn produce a message
160 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
161 /// an initial level for a lint.
163 /// Note that this still means that the lint is enabled in this position and should
164 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
168 /// The [`LintExpectationId`] is used to later link a lint emission to the actual
169 /// expectation. It can be ignored in most cases.
170 Expect(LintExpectationId),
171 /// The `warn` level will produce a warning if the lint was violated, however the
172 /// compiler will continue with its execution.
174 /// This lint level is a special case of [`Warn`], that can't be overridden. This is used
175 /// to ensure that a lint can't be suppressed. This lint level can currently only be set
176 /// via the console and is therefore session specific.
178 /// The [`LintExpectationId`] is intended to fulfill expectations marked via the
179 /// `#[expect]` attribute, that will still be suppressed due to the level.
180 ForceWarn(Option<LintExpectationId>),
181 /// The `deny` level will produce an error and stop further execution after the lint
182 /// pass is complete.
184 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
190 /// Converts a level to a lower-case string.
191 pub fn as_str(self) -> &'static str {
193 Level::Allow => "allow",
194 Level::Expect(_) => "expect",
195 Level::Warn => "warn",
196 Level::ForceWarn(_) => "force-warn",
197 Level::Deny => "deny",
198 Level::Forbid => "forbid",
202 /// Converts a lower-case string to a level. This will never construct the expect
203 /// level as that would require a [`LintExpectationId`]
204 pub fn from_str(x: &str) -> Option<Level> {
206 "allow" => Some(Level::Allow),
207 "warn" => Some(Level::Warn),
208 "deny" => Some(Level::Deny),
209 "forbid" => Some(Level::Forbid),
210 "expect" | _ => None,
214 /// Converts a symbol to a level.
215 pub fn from_attr(attr: &Attribute) -> Option<Level> {
216 match attr.name_or_empty() {
217 sym::allow => Some(Level::Allow),
218 sym::expect => Some(Level::Expect(LintExpectationId::Unstable {
222 sym::warn => Some(Level::Warn),
223 sym::deny => Some(Level::Deny),
224 sym::forbid => Some(Level::Forbid),
229 pub fn is_error(self) -> bool {
231 Level::Allow | Level::Expect(_) | Level::Warn | Level::ForceWarn(_) => false,
232 Level::Deny | Level::Forbid => true,
236 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
238 Level::Expect(id) | Level::ForceWarn(Some(id)) => Some(*id),
244 /// Specification of a single lint.
245 #[derive(Copy, Clone, Debug)]
247 /// A string identifier for the lint.
249 /// This identifies the lint in attributes and in command-line arguments.
250 /// In those contexts it is always lowercase, but this field is compared
251 /// in a way which is case-insensitive for ASCII characters. This allows
252 /// `declare_lint!()` invocations to follow the convention of upper-case
253 /// statics without repeating the name.
255 /// The name is written with underscores, e.g., "unused_imports".
256 /// On the command line, underscores become dashes.
258 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
259 /// for naming guidelines.
260 pub name: &'static str,
262 /// Default level for the lint.
264 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
265 /// for guidelines on choosing a default level.
266 pub default_level: Level,
268 /// Description of the lint or the issue it detects.
270 /// e.g., "imports that are never used"
271 pub desc: &'static str,
273 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
275 pub edition_lint_opts: Option<(Edition, Level)>,
277 /// `true` if this lint is reported even inside expansions of external macros.
278 pub report_in_external_macro: bool,
280 pub future_incompatible: Option<FutureIncompatibleInfo>,
284 /// `Some` if this lint is feature gated, otherwise `None`.
285 pub feature_gate: Option<Symbol>,
287 pub crate_level_only: bool,
290 /// Extra information for a future incompatibility lint.
291 #[derive(Copy, Clone, Debug)]
292 pub struct FutureIncompatibleInfo {
293 /// e.g., a URL for an issue/PR/RFC or error code
294 pub reference: &'static str,
295 /// The reason for the lint used by diagnostics to provide
296 /// the right help message
297 pub reason: FutureIncompatibilityReason,
298 /// Whether to explain the reason to the user.
300 /// Set to false for lints that already include a more detailed
302 pub explain_reason: bool,
305 /// The reason for future incompatibility
306 #[derive(Copy, Clone, Debug)]
307 pub enum FutureIncompatibilityReason {
308 /// This will be an error in a future release
311 /// This will be an error in a future release, and
312 /// Cargo should create a report even for dependencies
313 FutureReleaseErrorReportNow,
314 /// Code that changes meaning in some way in a
316 FutureReleaseSemanticsChange,
317 /// Previously accepted code that will become an
318 /// error in the provided edition
319 EditionError(Edition),
320 /// Code that changes meaning in some way in
321 /// the provided edition
322 EditionSemanticsChange(Edition),
324 Custom(&'static str),
327 impl FutureIncompatibilityReason {
328 pub fn edition(self) -> Option<Edition> {
330 Self::EditionError(e) => Some(e),
331 Self::EditionSemanticsChange(e) => Some(e),
337 impl FutureIncompatibleInfo {
338 pub const fn default_fields_for_macro() -> Self {
339 FutureIncompatibleInfo {
341 reason: FutureIncompatibilityReason::FutureReleaseError,
342 explain_reason: true,
348 pub const fn default_fields_for_macro() -> Self {
351 default_level: Level::Forbid,
353 edition_lint_opts: None,
355 report_in_external_macro: false,
356 future_incompatible: None,
358 crate_level_only: false,
362 /// Gets the lint's name, with ASCII letters converted to lowercase.
363 pub fn name_lower(&self) -> String {
364 self.name.to_ascii_lowercase()
367 pub fn default_level(&self, edition: Edition) -> Level {
368 self.edition_lint_opts
369 .filter(|(e, _)| *e <= edition)
371 .unwrap_or(self.default_level)
375 /// Identifies a lint known to the compiler.
376 #[derive(Clone, Copy, Debug)]
378 // Identity is based on pointer equality of this field.
379 pub lint: &'static Lint,
382 impl PartialEq for LintId {
383 fn eq(&self, other: &LintId) -> bool {
384 std::ptr::eq(self.lint, other.lint)
388 impl Eq for LintId {}
390 impl std::hash::Hash for LintId {
391 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
392 let ptr = self.lint as *const Lint;
398 /// Gets the `LintId` for a `Lint`.
399 pub fn of(lint: &'static Lint) -> LintId {
403 pub fn lint_name_raw(&self) -> &'static str {
407 /// Gets the name of the lint.
408 pub fn to_string(&self) -> String {
409 self.lint.name_lower()
413 impl<HCX> HashStable<HCX> for LintId {
415 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
416 self.lint_name_raw().hash_stable(hcx, hasher);
420 impl<HCX> ToStableHashKey<HCX> for LintId {
421 type KeyType = &'static str;
424 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
429 // This could be a closure, but then implementing derive trait
430 // becomes hacky (and it gets allocated).
432 pub enum BuiltinLintDiagnostics {
434 AbsPathWithModule(Span),
435 ProcMacroDeriveResolutionFallback(Span),
436 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
437 ElidedLifetimesInPaths(usize, Span, bool, Span),
438 UnknownCrateTypes(Span, String, String),
439 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
440 RedundantImport(Vec<(Span, bool)>, Ident),
441 DeprecatedMacro(Option<Symbol>, Span),
442 MissingAbi(Span, Abi),
443 UnusedDocComment(Span),
444 UnusedBuiltinAttribute {
449 PatternsInFnsWithoutBody(Span, Ident),
450 LegacyDeriveHelpers(Span),
451 ProcMacroBackCompat(String),
452 OrPatternsBackCompat(Span, String),
453 ReservedPrefix(Span),
454 TrailingMacro(bool, Ident),
455 BreakWithLabelAndLoop(Span),
456 NamedAsmLabel(String),
457 UnicodeTextFlow(Span, String),
458 UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
459 DeprecatedWhereclauseLocation(Span, String),
461 /// Span of the parameter which declares this lifetime.
463 /// Span of the code that should be removed when eliding this lifetime.
464 /// This span should include leading or trailing comma.
466 /// Span of the single use, or None if the lifetime is never used.
467 /// If true, the lifetime will be fully elided.
468 use_span: Option<(Span, bool)>,
470 NamedArgumentUsedPositionally(Option<Span>, Span, Symbol),
473 /// Lints that are buffered up early on in the `Session` before the
474 /// `LintLevels` is calculated.
475 pub struct BufferedEarlyLint {
476 /// The span of code that we are linting on.
479 /// The lint message.
482 /// The `NodeId` of the AST node that generated the lint.
485 /// A lint Id that can be passed to
486 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
489 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
490 pub diagnostic: BuiltinLintDiagnostics,
494 pub struct LintBuffer {
495 pub map: NodeMap<Vec<BufferedEarlyLint>>,
499 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
500 let arr = self.map.entry(early_lint.node_id).or_default();
501 arr.push(early_lint);
510 diagnostic: BuiltinLintDiagnostics,
512 let lint_id = LintId::of(lint);
513 let msg = msg.to_string();
514 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
517 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
518 self.map.remove(&id).unwrap_or_default()
525 sp: impl Into<MultiSpan>,
528 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
531 pub fn buffer_lint_with_diagnostic(
535 sp: impl Into<MultiSpan>,
537 diagnostic: BuiltinLintDiagnostics,
539 self.add_lint(lint, id, sp.into(), msg, diagnostic)
543 /// Declares a static item of type `&'static Lint`.
545 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
546 /// documentation and guidelines on writing lints.
548 /// The macro call should start with a doc comment explaining the lint
549 /// which will be embedded in the rustc user documentation book. It should
550 /// be written in markdown and have a format that looks like this:
552 /// ```rust,ignore (doc-example)
553 /// /// The `my_lint_name` lint detects [short explanation here].
558 /// /// [insert a concise example that triggers the lint]
563 /// /// ### Explanation
565 /// /// This should be a detailed explanation of *why* the lint exists,
566 /// /// and also include suggestions on how the user should fix the problem.
567 /// /// Try to keep the text simple enough that a beginner can understand,
568 /// /// and include links to other documentation for terminology that a
569 /// /// beginner may not be familiar with. If this is "allow" by default,
570 /// /// it should explain why (are there false positives or other issues?). If
571 /// /// this is a future-incompatible lint, it should say so, with text that
572 /// /// looks roughly like this:
574 /// /// This is a [future-incompatible] lint to transition this to a hard
575 /// /// error in the future. See [issue #xxxxx] for more details.
577 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
580 /// The `{{produces}}` tag will be automatically replaced with the output from
581 /// the example by the build system. If the lint example is too complex to run
582 /// as a simple example (for example, it needs an extern crate), mark the code
583 /// block with `ignore` and manually replace the `{{produces}}` line with the
584 /// expected output in a `text` code block.
586 /// If this is a rustdoc-only lint, then only include a brief introduction
587 /// with a link with the text `[rustdoc book]` so that the validator knows
588 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
590 /// Commands to view and test the documentation:
592 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
593 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
594 /// correct style, and that the code example actually emits the expected
597 /// If you have already built the compiler, and you want to make changes to
598 /// just the doc comments, then use the `--keep-stage=0` flag with the above
599 /// commands to avoid rebuilding the compiler.
601 macro_rules! declare_lint {
602 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
603 $crate::declare_lint!(
604 $(#[$attr])* $vis $NAME, $Level, $desc,
607 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
608 $(@feature_gate = $gate:expr;)?
609 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
612 $vis static $NAME: &$crate::Lint = &$crate::Lint {
613 name: stringify!($NAME),
614 default_level: $crate::$Level,
616 edition_lint_opts: None,
619 $(feature_gate: Some($gate),)*
620 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
622 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
624 ..$crate::Lint::default_fields_for_macro()
627 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
628 $lint_edition: expr => $edition_level: ident
631 $vis static $NAME: &$crate::Lint = &$crate::Lint {
632 name: stringify!($NAME),
633 default_level: $crate::$Level,
635 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
636 report_in_external_macro: false,
643 macro_rules! declare_tool_lint {
645 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
647 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
650 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
651 report_in_external_macro: $rep:expr
653 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
656 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
660 $vis static $NAME: &$crate::Lint = &$crate::Lint {
661 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
662 default_level: $crate::$Level,
664 edition_lint_opts: None,
665 report_in_external_macro: $external,
666 future_incompatible: None,
669 crate_level_only: false,
674 /// Declares a static `LintArray` and return it as an expression.
676 macro_rules! lint_array {
677 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
678 ($( $lint:expr ),*) => {{
683 pub type LintArray = Vec<&'static Lint>;
686 fn name(&self) -> &'static str;
689 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
691 macro_rules! impl_lint_pass {
692 ($ty:ty => [$($lint:expr),* $(,)?]) => {
693 impl $crate::LintPass for $ty {
694 fn name(&self) -> &'static str { stringify!($ty) }
697 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
702 /// Declares a type named `$name` which implements `LintPass`.
703 /// To the right of `=>` a comma separated list of `Lint` statics is given.
705 macro_rules! declare_lint_pass {
706 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
707 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
708 $crate::impl_lint_pass!($name => [$($lint),*]);