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;
12 use rustc_serialize::json::Json;
13 use rustc_span::edition::Edition;
14 use rustc_span::{sym, symbol::Ident, Span, Symbol};
15 use rustc_target::spec::abi::Abi;
20 macro_rules! pluralize {
22 if $x != 1 { "s" } else { "" }
25 if $x == 1 { "is" } else { "are" }
27 ("this", $x:expr) => {
28 if $x == 1 { "this" } else { "these" }
32 /// Indicates the confidence in the correctness of a suggestion.
34 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
35 /// to determine whether it should be automatically applied or if the user should be consulted
36 /// before applying the suggestion.
37 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
38 pub enum Applicability {
39 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
40 /// This suggestion should be automatically applied.
42 /// In case of multiple `MachineApplicable` suggestions (whether as part of
43 /// the same `multipart_suggestion` or not), all of them should be
44 /// automatically applied.
47 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
48 /// result in valid Rust code if it is applied.
51 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
52 /// cannot be applied automatically because it will not result in valid Rust code. The user
53 /// will need to fill in the placeholders.
56 /// The applicability of the suggestion is unknown.
60 /// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
61 /// Expected `Diagnostic`s get the lint level `Expect` which stores the `LintExpectationId`
62 /// to match it with the actual expectation later on.
64 /// The `LintExpectationId` has to be stable between compilations, as diagnostic
65 /// instances might be loaded from cache. Lint messages can be emitted during an
66 /// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
67 /// HIR tree. The AST doesn't have enough information to create a stable id. The
68 /// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
69 /// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
70 /// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
72 /// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
73 /// identifies the lint inside the attribute and ensures that the IDs are unique.
75 /// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
76 /// It's reasonable to assume that no user will define 2^16 attributes on one node or
77 /// have that amount of lints listed. `u16` values should therefore suffice.
78 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Encodable, Decodable)]
79 pub enum LintExpectationId {
80 /// Used for lints emitted during the `EarlyLintPass`. This id is not
81 /// hash stable and should not be cached.
82 Unstable { attr_id: AttrId, lint_index: Option<u16> },
83 /// The [`HirId`] that the lint expectation is attached to. This id is
84 /// stable and can be cached. The additional index ensures that nodes with
85 /// several expectations can correctly match diagnostics to the individual
87 Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16> },
90 impl LintExpectationId {
91 pub fn is_stable(&self) -> bool {
93 LintExpectationId::Unstable { .. } => false,
94 LintExpectationId::Stable { .. } => true,
98 pub fn get_lint_index(&self) -> Option<u16> {
99 let (LintExpectationId::Unstable { lint_index, .. }
100 | LintExpectationId::Stable { lint_index, .. }) = self;
105 pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
106 let (LintExpectationId::Unstable { ref mut lint_index, .. }
107 | LintExpectationId::Stable { ref mut lint_index, .. }) = self;
109 *lint_index = new_lint_index
113 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId {
115 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
117 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
118 hir_id.hash_stable(hcx, hasher);
119 attr_index.hash_stable(hcx, hasher);
120 lint_index.hash_stable(hcx, hasher);
124 "HashStable should only be called for filled and stable `LintExpectationId`"
131 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
132 type KeyType = (HirId, u16, u16);
135 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
137 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
138 (*hir_id, *attr_index, *lint_index)
141 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
147 /// Setting for how to handle a lint.
149 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
150 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
152 /// The `allow` level will not issue any message.
154 /// The `expect` level will suppress the lint message but in turn produce a message
155 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
156 /// an initial level for a lint.
158 /// Note that this still means that the lint is enabled in this position and should
159 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
163 /// The `LintExpectationId` is used to later link a lint emission to the actual
164 /// expectation. It can be ignored in most cases.
165 Expect(LintExpectationId),
166 /// The `warn` level will produce a warning if the lint was violated, however the
167 /// compiler will continue with its execution.
170 /// The `deny` level will produce an error and stop further execution after the lint
171 /// pass is complete.
173 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
178 rustc_data_structures::impl_stable_hash_via_hash!(Level);
181 /// Converts a level to a lower-case string.
182 pub fn as_str(self) -> &'static str {
184 Level::Allow => "allow",
185 Level::Expect(_) => "expect",
186 Level::Warn => "warn",
187 Level::ForceWarn => "force-warn",
188 Level::Deny => "deny",
189 Level::Forbid => "forbid",
193 /// Converts a lower-case string to a level. This will never construct the expect
194 /// level as that would require a [`LintExpectationId`]
195 pub fn from_str(x: &str) -> Option<Level> {
197 "allow" => Some(Level::Allow),
198 "warn" => Some(Level::Warn),
199 "deny" => Some(Level::Deny),
200 "forbid" => Some(Level::Forbid),
201 "expect" | _ => None,
205 /// Converts a symbol to a level.
206 pub fn from_attr(attr: &Attribute) -> Option<Level> {
207 match attr.name_or_empty() {
208 sym::allow => Some(Level::Allow),
209 sym::expect => Some(Level::Expect(LintExpectationId::Unstable {
213 sym::warn => Some(Level::Warn),
214 sym::deny => Some(Level::Deny),
215 sym::forbid => Some(Level::Forbid),
221 /// Specification of a single lint.
222 #[derive(Copy, Clone, Debug)]
224 /// A string identifier for the lint.
226 /// This identifies the lint in attributes and in command-line arguments.
227 /// In those contexts it is always lowercase, but this field is compared
228 /// in a way which is case-insensitive for ASCII characters. This allows
229 /// `declare_lint!()` invocations to follow the convention of upper-case
230 /// statics without repeating the name.
232 /// The name is written with underscores, e.g., "unused_imports".
233 /// On the command line, underscores become dashes.
235 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
236 /// for naming guidelines.
237 pub name: &'static str,
239 /// Default level for the lint.
241 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
242 /// for guidelines on choosing a default level.
243 pub default_level: Level,
245 /// Description of the lint or the issue it detects.
247 /// e.g., "imports that are never used"
248 pub desc: &'static str,
250 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
252 pub edition_lint_opts: Option<(Edition, Level)>,
254 /// `true` if this lint is reported even inside expansions of external macros.
255 pub report_in_external_macro: bool,
257 pub future_incompatible: Option<FutureIncompatibleInfo>,
261 /// `Some` if this lint is feature gated, otherwise `None`.
262 pub feature_gate: Option<Symbol>,
264 pub crate_level_only: bool,
267 /// Extra information for a future incompatibility lint.
268 #[derive(Copy, Clone, Debug)]
269 pub struct FutureIncompatibleInfo {
270 /// e.g., a URL for an issue/PR/RFC or error code
271 pub reference: &'static str,
272 /// The reason for the lint used by diagnostics to provide
273 /// the right help message
274 pub reason: FutureIncompatibilityReason,
275 /// Whether to explain the reason to the user.
277 /// Set to false for lints that already include a more detailed
279 pub explain_reason: bool,
282 /// The reason for future incompatibility
283 #[derive(Copy, Clone, Debug)]
284 pub enum FutureIncompatibilityReason {
285 /// This will be an error in a future release
288 /// This will be an error in a future release, and
289 /// Cargo should create a report even for dependencies
290 FutureReleaseErrorReportNow,
291 /// Code that changes meaning in some way in a
293 FutureReleaseSemanticsChange,
294 /// Previously accepted code that will become an
295 /// error in the provided edition
296 EditionError(Edition),
297 /// Code that changes meaning in some way in
298 /// the provided edition
299 EditionSemanticsChange(Edition),
301 Custom(&'static str),
304 impl FutureIncompatibilityReason {
305 pub fn edition(self) -> Option<Edition> {
307 Self::EditionError(e) => Some(e),
308 Self::EditionSemanticsChange(e) => Some(e),
314 impl FutureIncompatibleInfo {
315 pub const fn default_fields_for_macro() -> Self {
316 FutureIncompatibleInfo {
318 reason: FutureIncompatibilityReason::FutureReleaseError,
319 explain_reason: true,
325 pub const fn default_fields_for_macro() -> Self {
328 default_level: Level::Forbid,
330 edition_lint_opts: None,
332 report_in_external_macro: false,
333 future_incompatible: None,
335 crate_level_only: false,
339 /// Gets the lint's name, with ASCII letters converted to lowercase.
340 pub fn name_lower(&self) -> String {
341 self.name.to_ascii_lowercase()
344 pub fn default_level(&self, edition: Edition) -> Level {
345 self.edition_lint_opts
346 .filter(|(e, _)| *e <= edition)
348 .unwrap_or(self.default_level)
352 /// Identifies a lint known to the compiler.
353 #[derive(Clone, Copy, Debug)]
355 // Identity is based on pointer equality of this field.
356 pub lint: &'static Lint,
359 impl PartialEq for LintId {
360 fn eq(&self, other: &LintId) -> bool {
361 std::ptr::eq(self.lint, other.lint)
365 impl Eq for LintId {}
367 impl std::hash::Hash for LintId {
368 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
369 let ptr = self.lint as *const Lint;
375 /// Gets the `LintId` for a `Lint`.
376 pub fn of(lint: &'static Lint) -> LintId {
380 pub fn lint_name_raw(&self) -> &'static str {
384 /// Gets the name of the lint.
385 pub fn to_string(&self) -> String {
386 self.lint.name_lower()
390 impl<HCX> HashStable<HCX> for LintId {
392 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
393 self.lint_name_raw().hash_stable(hcx, hasher);
397 impl<HCX> ToStableHashKey<HCX> for LintId {
398 type KeyType = &'static str;
401 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
406 // Duplicated from rustc_session::config::ExternDepSpec to avoid cyclic dependency
407 #[derive(PartialEq, Debug)]
408 pub enum ExternDepSpec {
413 // This could be a closure, but then implementing derive trait
414 // becomes hacky (and it gets allocated).
416 pub enum BuiltinLintDiagnostics {
418 AbsPathWithModule(Span),
419 ProcMacroDeriveResolutionFallback(Span),
420 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
421 UnknownCrateTypes(Span, String, String),
422 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
423 RedundantImport(Vec<(Span, bool)>, Ident),
424 DeprecatedMacro(Option<Symbol>, Span),
425 MissingAbi(Span, Abi),
426 UnusedDocComment(Span),
427 UnusedBuiltinAttribute { attr_name: Symbol, macro_name: String, invoc_span: Span },
428 PatternsInFnsWithoutBody(Span, Ident),
429 LegacyDeriveHelpers(Span),
430 ExternDepSpec(String, ExternDepSpec),
431 ProcMacroBackCompat(String),
432 OrPatternsBackCompat(Span, String),
433 ReservedPrefix(Span),
434 TrailingMacro(bool, Ident),
435 BreakWithLabelAndLoop(Span),
436 NamedAsmLabel(String),
437 UnicodeTextFlow(Span, String),
438 UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
439 DeprecatedWhereclauseLocation(Span, String),
442 /// Lints that are buffered up early on in the `Session` before the
443 /// `LintLevels` is calculated.
444 pub struct BufferedEarlyLint {
445 /// The span of code that we are linting on.
448 /// The lint message.
451 /// The `NodeId` of the AST node that generated the lint.
454 /// A lint Id that can be passed to
455 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
458 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
459 pub diagnostic: BuiltinLintDiagnostics,
463 pub struct LintBuffer {
464 pub map: NodeMap<Vec<BufferedEarlyLint>>,
468 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
469 let arr = self.map.entry(early_lint.node_id).or_default();
470 arr.push(early_lint);
479 diagnostic: BuiltinLintDiagnostics,
481 let lint_id = LintId::of(lint);
482 let msg = msg.to_string();
483 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
486 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
487 self.map.remove(&id).unwrap_or_default()
494 sp: impl Into<MultiSpan>,
497 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
500 pub fn buffer_lint_with_diagnostic(
504 sp: impl Into<MultiSpan>,
506 diagnostic: BuiltinLintDiagnostics,
508 self.add_lint(lint, id, sp.into(), msg, diagnostic)
512 /// Declares a static item of type `&'static Lint`.
514 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
515 /// documentation and guidelines on writing lints.
517 /// The macro call should start with a doc comment explaining the lint
518 /// which will be embedded in the rustc user documentation book. It should
519 /// be written in markdown and have a format that looks like this:
521 /// ```rust,ignore (doc-example)
522 /// /// The `my_lint_name` lint detects [short explanation here].
527 /// /// [insert a concise example that triggers the lint]
532 /// /// ### Explanation
534 /// /// This should be a detailed explanation of *why* the lint exists,
535 /// /// and also include suggestions on how the user should fix the problem.
536 /// /// Try to keep the text simple enough that a beginner can understand,
537 /// /// and include links to other documentation for terminology that a
538 /// /// beginner may not be familiar with. If this is "allow" by default,
539 /// /// it should explain why (are there false positives or other issues?). If
540 /// /// this is a future-incompatible lint, it should say so, with text that
541 /// /// looks roughly like this:
543 /// /// This is a [future-incompatible] lint to transition this to a hard
544 /// /// error in the future. See [issue #xxxxx] for more details.
546 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
549 /// The `{{produces}}` tag will be automatically replaced with the output from
550 /// the example by the build system. If the lint example is too complex to run
551 /// as a simple example (for example, it needs an extern crate), mark the code
552 /// block with `ignore` and manually replace the `{{produces}}` line with the
553 /// expected output in a `text` code block.
555 /// If this is a rustdoc-only lint, then only include a brief introduction
556 /// with a link with the text `[rustdoc book]` so that the validator knows
557 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
559 /// Commands to view and test the documentation:
561 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
562 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
563 /// correct style, and that the code example actually emits the expected
566 /// If you have already built the compiler, and you want to make changes to
567 /// just the doc comments, then use the `--keep-stage=0` flag with the above
568 /// commands to avoid rebuilding the compiler.
570 macro_rules! declare_lint {
571 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
572 $crate::declare_lint!(
573 $(#[$attr])* $vis $NAME, $Level, $desc,
576 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
577 $(@feature_gate = $gate:expr;)?
578 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
581 $vis static $NAME: &$crate::Lint = &$crate::Lint {
582 name: stringify!($NAME),
583 default_level: $crate::$Level,
585 edition_lint_opts: None,
588 $(feature_gate: Some($gate),)*
589 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
591 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
593 ..$crate::Lint::default_fields_for_macro()
596 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
597 $lint_edition: expr => $edition_level: ident
600 $vis static $NAME: &$crate::Lint = &$crate::Lint {
601 name: stringify!($NAME),
602 default_level: $crate::$Level,
604 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
605 report_in_external_macro: false,
612 macro_rules! declare_tool_lint {
614 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
616 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
619 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
620 report_in_external_macro: $rep:expr
622 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
625 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
629 $vis static $NAME: &$crate::Lint = &$crate::Lint {
630 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
631 default_level: $crate::$Level,
633 edition_lint_opts: None,
634 report_in_external_macro: $external,
635 future_incompatible: None,
638 crate_level_only: false,
643 /// Declares a static `LintArray` and return it as an expression.
645 macro_rules! lint_array {
646 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
647 ($( $lint:expr ),*) => {{
652 pub type LintArray = Vec<&'static Lint>;
655 fn name(&self) -> &'static str;
658 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
660 macro_rules! impl_lint_pass {
661 ($ty:ty => [$($lint:expr),* $(,)?]) => {
662 impl $crate::LintPass for $ty {
663 fn name(&self) -> &'static str { stringify!($ty) }
666 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
671 /// Declares a type named `$name` which implements `LintPass`.
672 /// To the right of `=>` a comma separated list of `Lint` statics is given.
674 macro_rules! declare_lint_pass {
675 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
676 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
677 $crate::impl_lint_pass!($name => [$($lint),*]);