2 extern crate rustc_macros;
4 pub use self::Level::*;
5 use rustc_ast::node_id::{NodeId, NodeMap};
6 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
7 use rustc_serialize::json::Json;
8 use rustc_span::edition::Edition;
9 use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
10 use rustc_target::spec::abi::Abi;
15 macro_rules! pluralize {
17 if $x != 1 { "s" } else { "" }
21 /// Indicates the confidence in the correctness of a suggestion.
23 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
24 /// to determine whether it should be automatically applied or if the user should be consulted
25 /// before applying the suggestion.
26 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
27 pub enum Applicability {
28 /// The suggestion is definitely what the user intended. This suggestion should be
29 /// automatically applied.
32 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
33 /// result in valid Rust code if it is applied.
36 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
37 /// cannot be applied automatically because it will not result in valid Rust code. The user
38 /// will need to fill in the placeholders.
41 /// The applicability of the suggestion is unknown.
45 /// Setting for how to handle a lint.
46 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
54 rustc_data_structures::impl_stable_hash_via_hash!(Level);
57 /// Converts a level to a lower-case string.
58 pub fn as_str(self) -> &'static str {
60 Level::Allow => "allow",
61 Level::Warn => "warn",
62 Level::Deny => "deny",
63 Level::Forbid => "forbid",
67 /// Converts a lower-case string to a level.
68 pub fn from_str(x: &str) -> Option<Level> {
70 "allow" => Some(Level::Allow),
71 "warn" => Some(Level::Warn),
72 "deny" => Some(Level::Deny),
73 "forbid" => Some(Level::Forbid),
78 /// Converts a symbol to a level.
79 pub fn from_symbol(x: Symbol) -> Option<Level> {
81 sym::allow => Some(Level::Allow),
82 sym::warn => Some(Level::Warn),
83 sym::deny => Some(Level::Deny),
84 sym::forbid => Some(Level::Forbid),
90 /// Specification of a single lint.
91 #[derive(Copy, Clone, Debug)]
93 /// A string identifier for the lint.
95 /// This identifies the lint in attributes and in command-line arguments.
96 /// In those contexts it is always lowercase, but this field is compared
97 /// in a way which is case-insensitive for ASCII characters. This allows
98 /// `declare_lint!()` invocations to follow the convention of upper-case
99 /// statics without repeating the name.
101 /// The name is written with underscores, e.g., "unused_imports".
102 /// On the command line, underscores become dashes.
104 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
105 /// for naming guidelines.
106 pub name: &'static str,
108 /// Default level for the lint.
110 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
111 /// for guidelines on choosing a default level.
112 pub default_level: Level,
114 /// Description of the lint or the issue it detects.
116 /// e.g., "imports that are never used"
117 pub desc: &'static str,
119 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
121 pub edition_lint_opts: Option<(Edition, Level)>,
123 /// `true` if this lint is reported even inside expansions of external macros.
124 pub report_in_external_macro: bool,
126 pub future_incompatible: Option<FutureIncompatibleInfo>,
130 /// `Some` if this lint is feature gated, otherwise `None`.
131 pub feature_gate: Option<Symbol>,
133 pub crate_level_only: bool,
136 /// Extra information for a future incompatibility lint.
137 #[derive(Copy, Clone, Debug)]
138 pub struct FutureIncompatibleInfo {
139 /// e.g., a URL for an issue/PR/RFC or error code
140 pub reference: &'static str,
141 /// If this is an edition fixing lint, the edition in which
142 /// this lint becomes obsolete
143 pub edition: Option<Edition>,
144 /// Information about a future breakage, which will
145 /// be emitted in JSON messages to be displayed by Cargo
146 /// for upstream deps
147 pub future_breakage: Option<FutureBreakage>,
150 #[derive(Copy, Clone, Debug)]
151 pub struct FutureBreakage {
152 pub date: Option<&'static str>,
155 impl FutureIncompatibleInfo {
156 pub const fn default_fields_for_macro() -> Self {
157 FutureIncompatibleInfo { reference: "", edition: None, future_breakage: None }
162 pub const fn default_fields_for_macro() -> Self {
165 default_level: Level::Forbid,
167 edition_lint_opts: None,
169 report_in_external_macro: false,
170 future_incompatible: None,
172 crate_level_only: false,
176 /// Gets the lint's name, with ASCII letters converted to lowercase.
177 pub fn name_lower(&self) -> String {
178 self.name.to_ascii_lowercase()
181 pub fn default_level(&self, edition: Edition) -> Level {
182 self.edition_lint_opts
183 .filter(|(e, _)| *e <= edition)
185 .unwrap_or(self.default_level)
189 /// Identifies a lint known to the compiler.
190 #[derive(Clone, Copy, Debug)]
192 // Identity is based on pointer equality of this field.
193 pub lint: &'static Lint,
196 impl PartialEq for LintId {
197 fn eq(&self, other: &LintId) -> bool {
198 std::ptr::eq(self.lint, other.lint)
202 impl Eq for LintId {}
204 impl std::hash::Hash for LintId {
205 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
206 let ptr = self.lint as *const Lint;
212 /// Gets the `LintId` for a `Lint`.
213 pub fn of(lint: &'static Lint) -> LintId {
217 pub fn lint_name_raw(&self) -> &'static str {
221 /// Gets the name of the lint.
222 pub fn to_string(&self) -> String {
223 self.lint.name_lower()
227 impl<HCX> HashStable<HCX> for LintId {
229 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
230 self.lint_name_raw().hash_stable(hcx, hasher);
234 impl<HCX> ToStableHashKey<HCX> for LintId {
235 type KeyType = &'static str;
238 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
243 // Duplicated from rustc_session::config::ExternDepSpec to avoid cyclic dependency
245 pub enum ExternDepSpec {
250 // This could be a closure, but then implementing derive trait
251 // becomes hacky (and it gets allocated).
253 pub enum BuiltinLintDiagnostics {
255 BareTraitObject(Span, /* is_global */ bool),
256 AbsPathWithModule(Span),
257 ProcMacroDeriveResolutionFallback(Span),
258 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
259 ElidedLifetimesInPaths(usize, Span, bool, Span, String),
260 UnknownCrateTypes(Span, String, String),
261 UnusedImports(String, Vec<(Span, String)>),
262 RedundantImport(Vec<(Span, bool)>, Ident),
263 DeprecatedMacro(Option<Symbol>, Span),
264 MissingAbi(Span, Abi),
265 UnusedDocComment(Span),
266 PatternsInFnsWithoutBody(Span, Ident),
267 LegacyDeriveHelpers(Span),
268 ExternDepSpec(String, ExternDepSpec),
271 /// Lints that are buffered up early on in the `Session` before the
272 /// `LintLevels` is calculated.
274 pub struct BufferedEarlyLint {
275 /// The span of code that we are linting on.
278 /// The lint message.
281 /// The `NodeId` of the AST node that generated the lint.
284 /// A lint Id that can be passed to
285 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
288 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
289 pub diagnostic: BuiltinLintDiagnostics,
293 pub struct LintBuffer {
294 pub map: NodeMap<Vec<BufferedEarlyLint>>,
298 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
299 let arr = self.map.entry(early_lint.node_id).or_default();
300 if !arr.contains(&early_lint) {
301 arr.push(early_lint);
311 diagnostic: BuiltinLintDiagnostics,
313 let lint_id = LintId::of(lint);
314 let msg = msg.to_string();
315 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
318 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
319 self.map.remove(&id).unwrap_or_default()
326 sp: impl Into<MultiSpan>,
329 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
332 pub fn buffer_lint_with_diagnostic(
336 sp: impl Into<MultiSpan>,
338 diagnostic: BuiltinLintDiagnostics,
340 self.add_lint(lint, id, sp.into(), msg, diagnostic)
344 /// Declares a static item of type `&'static Lint`.
346 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
347 /// documentation and guidelines on writing lints.
349 /// The macro call should start with a doc comment explaining the lint
350 /// which will be embedded in the rustc user documentation book. It should
351 /// be written in markdown and have a format that looks like this:
353 /// ```rust,ignore (doc-example)
354 /// /// The `my_lint_name` lint detects [short explanation here].
359 /// /// [insert a concise example that triggers the lint]
364 /// /// ### Explanation
366 /// /// This should be a detailed explanation of *why* the lint exists,
367 /// /// and also include suggestions on how the user should fix the problem.
368 /// /// Try to keep the text simple enough that a beginner can understand,
369 /// /// and include links to other documentation for terminology that a
370 /// /// beginner may not be familiar with. If this is "allow" by default,
371 /// /// it should explain why (are there false positives or other issues?). If
372 /// /// this is a future-incompatible lint, it should say so, with text that
373 /// /// looks roughly like this:
375 /// /// This is a [future-incompatible] lint to transition this to a hard
376 /// /// error in the future. See [issue #xxxxx] for more details.
378 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
381 /// The `{{produces}}` tag will be automatically replaced with the output from
382 /// the example by the build system. If the lint example is too complex to run
383 /// as a simple example (for example, it needs an extern crate), mark the code
384 /// block with `ignore` and manually replace the `{{produces}}` line with the
385 /// expected output in a `text` code block.
387 /// If this is a rustdoc-only lint, then only include a brief introduction
388 /// with a link with the text `[rustdoc book]` so that the validator knows
389 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
391 /// Commands to view and test the documentation:
393 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
394 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
395 /// correct style, and that the code example actually emits the expected
398 /// If you have already built the compiler, and you want to make changes to
399 /// just the doc comments, then use the `--keep-stage=0` flag with the above
400 /// commands to avoid rebuilding the compiler.
402 macro_rules! declare_lint {
403 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
404 $crate::declare_lint!(
405 $(#[$attr])* $vis $NAME, $Level, $desc,
408 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
409 $(@feature_gate = $gate:expr;)?
410 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
413 $vis static $NAME: &$crate::Lint = &$crate::Lint {
414 name: stringify!($NAME),
415 default_level: $crate::$Level,
417 edition_lint_opts: None,
420 $(feature_gate: Some($gate),)*
421 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
423 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
425 ..$crate::Lint::default_fields_for_macro()
428 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
429 $lint_edition: expr => $edition_level: ident
432 $vis static $NAME: &$crate::Lint = &$crate::Lint {
433 name: stringify!($NAME),
434 default_level: $crate::$Level,
436 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
437 report_in_external_macro: false,
444 macro_rules! declare_tool_lint {
446 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
448 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
451 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
452 report_in_external_macro: $rep:expr
454 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
457 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
461 $vis static $NAME: &$crate::Lint = &$crate::Lint {
462 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
463 default_level: $crate::$Level,
465 edition_lint_opts: None,
466 report_in_external_macro: $external,
467 future_incompatible: None,
470 crate_level_only: false,
475 /// Declares a static `LintArray` and return it as an expression.
477 macro_rules! lint_array {
478 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
479 ($( $lint:expr ),*) => {{
484 pub type LintArray = Vec<&'static Lint>;
487 fn name(&self) -> &'static str;
490 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
492 macro_rules! impl_lint_pass {
493 ($ty:ty => [$($lint:expr),* $(,)?]) => {
494 impl $crate::LintPass for $ty {
495 fn name(&self) -> &'static str { stringify!($ty) }
498 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
503 /// Declares a type named `$name` which implements `LintPass`.
504 /// To the right of `=>` a comma separated list of `Lint` statics is given.
506 macro_rules! declare_lint_pass {
507 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
508 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
509 $crate::impl_lint_pass!($name => [$($lint),*]);