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};
11 use rustc_serialize::json::Json;
12 use rustc_span::edition::Edition;
13 use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
14 use rustc_target::spec::abi::Abi;
19 macro_rules! pluralize {
21 if $x != 1 { "s" } else { "" }
25 /// Indicates the confidence in the correctness of a suggestion.
27 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
28 /// to determine whether it should be automatically applied or if the user should be consulted
29 /// before applying the suggestion.
30 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
31 pub enum Applicability {
32 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
33 /// This suggestion should be automatically applied.
35 /// In case of multiple `MachineApplicable` suggestions (whether as part of
36 /// the same `multipart_suggestion` or not), all of them should be
37 /// automatically applied.
40 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
41 /// result in valid Rust code if it is applied.
44 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
45 /// cannot be applied automatically because it will not result in valid Rust code. The user
46 /// will need to fill in the placeholders.
49 /// The applicability of the suggestion is unknown.
53 /// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
54 /// Expected `Diagnostic`s get the lint level `Expect` which stores the `LintExpectationId`
55 /// to match it with the actual expectation later on.
57 /// The `LintExpectationId` has to be has stable between compilations, as diagnostic
58 /// instances might be loaded from cache. Lint messages can be emitted during an
59 /// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
60 /// HIR tree. The AST doesn't have enough information to create a stable id. The
61 /// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
62 /// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
63 /// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
65 /// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
66 /// identifies the lint inside the attribute and ensures that the IDs are unique.
68 /// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
69 /// It's reasonable to assume that no user will define 2^16 attributes on one node or
70 /// have that amount of lints listed. `u16` values should therefore suffice.
71 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Encodable, Decodable)]
72 pub enum LintExpectationId {
73 /// Used for lints emitted during the `EarlyLintPass`. This id is not
74 /// has stable and should not be cached.
75 Unstable { attr_id: AttrId, lint_index: Option<u16> },
76 /// The [`HirId`] that the lint expectation is attached to. This id is
77 /// stable and can be cached. The additional index ensures that nodes with
78 /// several expectations can correctly match diagnostics to the individual
80 Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16> },
83 impl LintExpectationId {
84 pub fn is_stable(&self) -> bool {
86 LintExpectationId::Unstable { .. } => false,
87 LintExpectationId::Stable { .. } => true,
91 pub fn get_lint_index(&self) -> Option<u16> {
92 let (LintExpectationId::Unstable { lint_index, .. }
93 | LintExpectationId::Stable { lint_index, .. }) = self;
98 pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
99 let (LintExpectationId::Unstable { ref mut lint_index, .. }
100 | LintExpectationId::Stable { ref mut lint_index, .. }) = self;
102 *lint_index = new_lint_index
106 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId {
108 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
110 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
111 hir_id.hash_stable(hcx, hasher);
112 attr_index.hash_stable(hcx, hasher);
113 lint_index.hash_stable(hcx, hasher);
116 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
122 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
123 type KeyType = (HirId, u16, u16);
126 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
128 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
129 (*hir_id, *attr_index, *lint_index)
132 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
138 /// Setting for how to handle a lint.
140 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
141 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
143 /// The `allow` level will not issue any message.
145 /// The `expect` level will suppress the lint message but in turn produce a message
146 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
147 /// an initial level for a lint.
149 /// Note that this still means that the lint is enabled in this position and should
150 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
154 /// The `LintExpectationId` is used to later link a lint emission to the actual
155 /// expectation. It can be ignored in most cases.
156 Expect(LintExpectationId),
157 /// The `warn` level will produce a warning if the lint was violated, however the
158 /// compiler will continue with its execution.
161 /// The `deny` level will produce an error and stop further execution after the lint
162 /// pass is complete.
164 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
169 rustc_data_structures::impl_stable_hash_via_hash!(Level);
172 /// Converts a level to a lower-case string.
173 pub fn as_str(self) -> &'static str {
175 Level::Allow => "allow",
176 Level::Expect(_) => "expect",
177 Level::Warn => "warn",
178 Level::ForceWarn => "force-warn",
179 Level::Deny => "deny",
180 Level::Forbid => "forbid",
184 /// Converts a lower-case string to a level. This will never construct the expect
185 /// level as that would require a [`LintExpectationId`]
186 pub fn from_str(x: &str) -> Option<Level> {
188 "allow" => Some(Level::Allow),
189 "warn" => Some(Level::Warn),
190 "deny" => Some(Level::Deny),
191 "forbid" => Some(Level::Forbid),
192 "expect" | _ => None,
196 /// Converts a symbol to a level.
197 pub fn from_attr(attr: &Attribute) -> Option<Level> {
198 match attr.name_or_empty() {
199 sym::allow => Some(Level::Allow),
200 sym::expect => Some(Level::Expect(LintExpectationId::Unstable {
204 sym::warn => Some(Level::Warn),
205 sym::deny => Some(Level::Deny),
206 sym::forbid => Some(Level::Forbid),
212 /// Specification of a single lint.
213 #[derive(Copy, Clone, Debug)]
215 /// A string identifier for the lint.
217 /// This identifies the lint in attributes and in command-line arguments.
218 /// In those contexts it is always lowercase, but this field is compared
219 /// in a way which is case-insensitive for ASCII characters. This allows
220 /// `declare_lint!()` invocations to follow the convention of upper-case
221 /// statics without repeating the name.
223 /// The name is written with underscores, e.g., "unused_imports".
224 /// On the command line, underscores become dashes.
226 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
227 /// for naming guidelines.
228 pub name: &'static str,
230 /// Default level for the lint.
232 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
233 /// for guidelines on choosing a default level.
234 pub default_level: Level,
236 /// Description of the lint or the issue it detects.
238 /// e.g., "imports that are never used"
239 pub desc: &'static str,
241 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
243 pub edition_lint_opts: Option<(Edition, Level)>,
245 /// `true` if this lint is reported even inside expansions of external macros.
246 pub report_in_external_macro: bool,
248 pub future_incompatible: Option<FutureIncompatibleInfo>,
252 /// `Some` if this lint is feature gated, otherwise `None`.
253 pub feature_gate: Option<Symbol>,
255 pub crate_level_only: bool,
258 /// Extra information for a future incompatibility lint.
259 #[derive(Copy, Clone, Debug)]
260 pub struct FutureIncompatibleInfo {
261 /// e.g., a URL for an issue/PR/RFC or error code
262 pub reference: &'static str,
263 /// The reason for the lint used by diagnostics to provide
264 /// the right help message
265 pub reason: FutureIncompatibilityReason,
266 /// Whether to explain the reason to the user.
268 /// Set to false for lints that already include a more detailed
270 pub explain_reason: bool,
273 /// The reason for future incompatibility
274 #[derive(Copy, Clone, Debug)]
275 pub enum FutureIncompatibilityReason {
276 /// This will be an error in a future release
279 /// This will be an error in a future release, and
280 /// Cargo should create a report even for dependencies
281 FutureReleaseErrorReportNow,
282 /// Code that changes meaning in some way in a
284 FutureReleaseSemanticsChange,
285 /// Previously accepted code that will become an
286 /// error in the provided edition
287 EditionError(Edition),
288 /// Code that changes meaning in some way in
289 /// the provided edition
290 EditionSemanticsChange(Edition),
292 Custom(&'static str),
295 impl FutureIncompatibilityReason {
296 pub fn edition(self) -> Option<Edition> {
298 Self::EditionError(e) => Some(e),
299 Self::EditionSemanticsChange(e) => Some(e),
305 impl FutureIncompatibleInfo {
306 pub const fn default_fields_for_macro() -> Self {
307 FutureIncompatibleInfo {
309 reason: FutureIncompatibilityReason::FutureReleaseError,
310 explain_reason: true,
316 pub const fn default_fields_for_macro() -> Self {
319 default_level: Level::Forbid,
321 edition_lint_opts: None,
323 report_in_external_macro: false,
324 future_incompatible: None,
326 crate_level_only: false,
330 /// Gets the lint's name, with ASCII letters converted to lowercase.
331 pub fn name_lower(&self) -> String {
332 self.name.to_ascii_lowercase()
335 pub fn default_level(&self, edition: Edition) -> Level {
336 self.edition_lint_opts
337 .filter(|(e, _)| *e <= edition)
339 .unwrap_or(self.default_level)
343 /// Identifies a lint known to the compiler.
344 #[derive(Clone, Copy, Debug)]
346 // Identity is based on pointer equality of this field.
347 pub lint: &'static Lint,
350 impl PartialEq for LintId {
351 fn eq(&self, other: &LintId) -> bool {
352 std::ptr::eq(self.lint, other.lint)
356 impl Eq for LintId {}
358 impl std::hash::Hash for LintId {
359 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
360 let ptr = self.lint as *const Lint;
366 /// Gets the `LintId` for a `Lint`.
367 pub fn of(lint: &'static Lint) -> LintId {
371 pub fn lint_name_raw(&self) -> &'static str {
375 /// Gets the name of the lint.
376 pub fn to_string(&self) -> String {
377 self.lint.name_lower()
381 impl<HCX> HashStable<HCX> for LintId {
383 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
384 self.lint_name_raw().hash_stable(hcx, hasher);
388 impl<HCX> ToStableHashKey<HCX> for LintId {
389 type KeyType = &'static str;
392 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
397 // Duplicated from rustc_session::config::ExternDepSpec to avoid cyclic dependency
398 #[derive(PartialEq, Debug)]
399 pub enum ExternDepSpec {
404 // This could be a closure, but then implementing derive trait
405 // becomes hacky (and it gets allocated).
407 pub enum BuiltinLintDiagnostics {
409 AbsPathWithModule(Span),
410 ProcMacroDeriveResolutionFallback(Span),
411 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
412 UnknownCrateTypes(Span, String, String),
413 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
414 RedundantImport(Vec<(Span, bool)>, Ident),
415 DeprecatedMacro(Option<Symbol>, Span),
416 MissingAbi(Span, Abi),
417 UnusedDocComment(Span),
418 UnusedBuiltinAttribute { attr_name: Symbol, macro_name: String, invoc_span: Span },
419 PatternsInFnsWithoutBody(Span, Ident),
420 LegacyDeriveHelpers(Span),
421 ExternDepSpec(String, ExternDepSpec),
422 ProcMacroBackCompat(String),
423 OrPatternsBackCompat(Span, String),
424 ReservedPrefix(Span),
425 TrailingMacro(bool, Ident),
426 BreakWithLabelAndLoop(Span),
427 NamedAsmLabel(String),
428 UnicodeTextFlow(Span, String),
429 UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
430 DeprecatedWhereclauseLocation(Span, String),
433 /// Lints that are buffered up early on in the `Session` before the
434 /// `LintLevels` is calculated.
435 pub struct BufferedEarlyLint {
436 /// The span of code that we are linting on.
439 /// The lint message.
442 /// The `NodeId` of the AST node that generated the lint.
445 /// A lint Id that can be passed to
446 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
449 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
450 pub diagnostic: BuiltinLintDiagnostics,
454 pub struct LintBuffer {
455 pub map: NodeMap<Vec<BufferedEarlyLint>>,
459 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
460 let arr = self.map.entry(early_lint.node_id).or_default();
461 arr.push(early_lint);
470 diagnostic: BuiltinLintDiagnostics,
472 let lint_id = LintId::of(lint);
473 let msg = msg.to_string();
474 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
477 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
478 self.map.remove(&id).unwrap_or_default()
485 sp: impl Into<MultiSpan>,
488 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
491 pub fn buffer_lint_with_diagnostic(
495 sp: impl Into<MultiSpan>,
497 diagnostic: BuiltinLintDiagnostics,
499 self.add_lint(lint, id, sp.into(), msg, diagnostic)
503 /// Declares a static item of type `&'static Lint`.
505 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
506 /// documentation and guidelines on writing lints.
508 /// The macro call should start with a doc comment explaining the lint
509 /// which will be embedded in the rustc user documentation book. It should
510 /// be written in markdown and have a format that looks like this:
512 /// ```rust,ignore (doc-example)
513 /// /// The `my_lint_name` lint detects [short explanation here].
518 /// /// [insert a concise example that triggers the lint]
523 /// /// ### Explanation
525 /// /// This should be a detailed explanation of *why* the lint exists,
526 /// /// and also include suggestions on how the user should fix the problem.
527 /// /// Try to keep the text simple enough that a beginner can understand,
528 /// /// and include links to other documentation for terminology that a
529 /// /// beginner may not be familiar with. If this is "allow" by default,
530 /// /// it should explain why (are there false positives or other issues?). If
531 /// /// this is a future-incompatible lint, it should say so, with text that
532 /// /// looks roughly like this:
534 /// /// This is a [future-incompatible] lint to transition this to a hard
535 /// /// error in the future. See [issue #xxxxx] for more details.
537 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
540 /// The `{{produces}}` tag will be automatically replaced with the output from
541 /// the example by the build system. If the lint example is too complex to run
542 /// as a simple example (for example, it needs an extern crate), mark the code
543 /// block with `ignore` and manually replace the `{{produces}}` line with the
544 /// expected output in a `text` code block.
546 /// If this is a rustdoc-only lint, then only include a brief introduction
547 /// with a link with the text `[rustdoc book]` so that the validator knows
548 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
550 /// Commands to view and test the documentation:
552 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
553 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
554 /// correct style, and that the code example actually emits the expected
557 /// If you have already built the compiler, and you want to make changes to
558 /// just the doc comments, then use the `--keep-stage=0` flag with the above
559 /// commands to avoid rebuilding the compiler.
561 macro_rules! declare_lint {
562 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
563 $crate::declare_lint!(
564 $(#[$attr])* $vis $NAME, $Level, $desc,
567 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
568 $(@feature_gate = $gate:expr;)?
569 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
572 $vis static $NAME: &$crate::Lint = &$crate::Lint {
573 name: stringify!($NAME),
574 default_level: $crate::$Level,
576 edition_lint_opts: None,
579 $(feature_gate: Some($gate),)*
580 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
582 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
584 ..$crate::Lint::default_fields_for_macro()
587 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
588 $lint_edition: expr => $edition_level: ident
591 $vis static $NAME: &$crate::Lint = &$crate::Lint {
592 name: stringify!($NAME),
593 default_level: $crate::$Level,
595 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
596 report_in_external_macro: false,
603 macro_rules! declare_tool_lint {
605 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
607 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
610 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
611 report_in_external_macro: $rep:expr
613 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
616 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
620 $vis static $NAME: &$crate::Lint = &$crate::Lint {
621 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
622 default_level: $crate::$Level,
624 edition_lint_opts: None,
625 report_in_external_macro: $external,
626 future_incompatible: None,
629 crate_level_only: false,
634 /// Declares a static `LintArray` and return it as an expression.
636 macro_rules! lint_array {
637 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
638 ($( $lint:expr ),*) => {{
643 pub type LintArray = Vec<&'static Lint>;
646 fn name(&self) -> &'static str;
649 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
651 macro_rules! impl_lint_pass {
652 ($ty:ty => [$($lint:expr),* $(,)?]) => {
653 impl $crate::LintPass for $ty {
654 fn name(&self) -> &'static str { stringify!($ty) }
657 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
662 /// Declares a type named `$name` which implements `LintPass`.
663 /// To the right of `=>` a comma separated list of `Lint` statics is given.
665 macro_rules! declare_lint_pass {
666 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
667 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
668 $crate::impl_lint_pass!($name => [$($lint),*]);