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_span::edition::Edition;
8 use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
9 use rustc_target::spec::abi::Abi;
14 macro_rules! pluralize {
16 if $x != 1 { "s" } else { "" }
20 /// Indicates the confidence in the correctness of a suggestion.
22 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
23 /// to determine whether it should be automatically applied or if the user should be consulted
24 /// before applying the suggestion.
25 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
26 pub enum Applicability {
27 /// The suggestion is definitely what the user intended. This suggestion should be
28 /// automatically applied.
31 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
32 /// result in valid Rust code if it is applied.
35 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
36 /// cannot be applied automatically because it will not result in valid Rust code. The user
37 /// will need to fill in the placeholders.
40 /// The applicability of the suggestion is unknown.
44 /// Setting for how to handle a lint.
45 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
53 rustc_data_structures::impl_stable_hash_via_hash!(Level);
56 /// Converts a level to a lower-case string.
57 pub fn as_str(self) -> &'static str {
59 Level::Allow => "allow",
60 Level::Warn => "warn",
61 Level::Deny => "deny",
62 Level::Forbid => "forbid",
66 /// Converts a lower-case string to a level.
67 pub fn from_str(x: &str) -> Option<Level> {
69 "allow" => Some(Level::Allow),
70 "warn" => Some(Level::Warn),
71 "deny" => Some(Level::Deny),
72 "forbid" => Some(Level::Forbid),
77 /// Converts a symbol to a level.
78 pub fn from_symbol(x: Symbol) -> Option<Level> {
80 sym::allow => Some(Level::Allow),
81 sym::warn => Some(Level::Warn),
82 sym::deny => Some(Level::Deny),
83 sym::forbid => Some(Level::Forbid),
89 /// Specification of a single lint.
90 #[derive(Copy, Clone, Debug)]
92 /// A string identifier for the lint.
94 /// This identifies the lint in attributes and in command-line arguments.
95 /// In those contexts it is always lowercase, but this field is compared
96 /// in a way which is case-insensitive for ASCII characters. This allows
97 /// `declare_lint!()` invocations to follow the convention of upper-case
98 /// statics without repeating the name.
100 /// The name is written with underscores, e.g., "unused_imports".
101 /// On the command line, underscores become dashes.
103 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
104 /// for naming guidelines.
105 pub name: &'static str,
107 /// Default level for the lint.
109 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
110 /// for guidelines on choosing a default level.
111 pub default_level: Level,
113 /// Description of the lint or the issue it detects.
115 /// e.g., "imports that are never used"
116 pub desc: &'static str,
118 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
120 pub edition_lint_opts: Option<(Edition, Level)>,
122 /// `true` if this lint is reported even inside expansions of external macros.
123 pub report_in_external_macro: bool,
125 pub future_incompatible: Option<FutureIncompatibleInfo>,
129 /// `Some` if this lint is feature gated, otherwise `None`.
130 pub feature_gate: Option<Symbol>,
132 pub crate_level_only: bool,
135 /// Extra information for a future incompatibility lint.
136 #[derive(Copy, Clone, Debug)]
137 pub struct FutureIncompatibleInfo {
138 /// e.g., a URL for an issue/PR/RFC or error code
139 pub reference: &'static str,
140 /// If this is an edition fixing lint, the edition in which
141 /// this lint becomes obsolete
142 pub edition: Option<Edition>,
143 /// Information about a future breakage, which will
144 /// be emitted in JSON messages to be displayed by Cargo
145 /// for upstream deps
146 pub future_breakage: Option<FutureBreakage>,
149 #[derive(Copy, Clone, Debug)]
150 pub struct FutureBreakage {
151 pub date: Option<&'static str>,
154 impl FutureIncompatibleInfo {
155 pub const fn default_fields_for_macro() -> Self {
156 FutureIncompatibleInfo { reference: "", edition: None, future_breakage: None }
161 pub const fn default_fields_for_macro() -> Self {
164 default_level: Level::Forbid,
166 edition_lint_opts: None,
168 report_in_external_macro: false,
169 future_incompatible: None,
171 crate_level_only: false,
175 /// Gets the lint's name, with ASCII letters converted to lowercase.
176 pub fn name_lower(&self) -> String {
177 self.name.to_ascii_lowercase()
180 pub fn default_level(&self, edition: Edition) -> Level {
181 self.edition_lint_opts
182 .filter(|(e, _)| *e <= edition)
184 .unwrap_or(self.default_level)
188 /// Identifies a lint known to the compiler.
189 #[derive(Clone, Copy, Debug)]
191 // Identity is based on pointer equality of this field.
192 pub lint: &'static Lint,
195 impl PartialEq for LintId {
196 fn eq(&self, other: &LintId) -> bool {
197 std::ptr::eq(self.lint, other.lint)
201 impl Eq for LintId {}
203 impl std::hash::Hash for LintId {
204 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
205 let ptr = self.lint as *const Lint;
211 /// Gets the `LintId` for a `Lint`.
212 pub fn of(lint: &'static Lint) -> LintId {
216 pub fn lint_name_raw(&self) -> &'static str {
220 /// Gets the name of the lint.
221 pub fn to_string(&self) -> String {
222 self.lint.name_lower()
226 impl<HCX> HashStable<HCX> for LintId {
228 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
229 self.lint_name_raw().hash_stable(hcx, hasher);
233 impl<HCX> ToStableHashKey<HCX> for LintId {
234 type KeyType = &'static str;
237 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
242 // This could be a closure, but then implementing derive trait
243 // becomes hacky (and it gets allocated).
245 pub enum BuiltinLintDiagnostics {
247 BareTraitObject(Span, /* is_global */ bool),
248 AbsPathWithModule(Span),
249 ProcMacroDeriveResolutionFallback(Span),
250 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
251 ElidedLifetimesInPaths(usize, Span, bool, Span, String),
252 UnknownCrateTypes(Span, String, String),
253 UnusedImports(String, Vec<(Span, String)>),
254 RedundantImport(Vec<(Span, bool)>, Ident),
255 DeprecatedMacro(Option<Symbol>, Span),
256 MissingAbi(Span, Abi),
257 UnusedDocComment(Span),
258 PatternsInFnsWithoutBody(Span, Ident),
261 /// Lints that are buffered up early on in the `Session` before the
262 /// `LintLevels` is calculated.
264 pub struct BufferedEarlyLint {
265 /// The span of code that we are linting on.
268 /// The lint message.
271 /// The `NodeId` of the AST node that generated the lint.
274 /// A lint Id that can be passed to
275 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
278 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
279 pub diagnostic: BuiltinLintDiagnostics,
283 pub struct LintBuffer {
284 pub map: NodeMap<Vec<BufferedEarlyLint>>,
288 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
289 let arr = self.map.entry(early_lint.node_id).or_default();
290 if !arr.contains(&early_lint) {
291 arr.push(early_lint);
301 diagnostic: BuiltinLintDiagnostics,
303 let lint_id = LintId::of(lint);
304 let msg = msg.to_string();
305 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
308 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
309 self.map.remove(&id).unwrap_or_default()
316 sp: impl Into<MultiSpan>,
319 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
322 pub fn buffer_lint_with_diagnostic(
326 sp: impl Into<MultiSpan>,
328 diagnostic: BuiltinLintDiagnostics,
330 self.add_lint(lint, id, sp.into(), msg, diagnostic)
334 /// Declares a static item of type `&'static Lint`.
336 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
337 /// documentation and guidelines on writing lints.
339 /// The macro call should start with a doc comment explaining the lint
340 /// which will be embedded in the rustc user documentation book. It should
341 /// be written in markdown and have a format that looks like this:
343 /// ```rust,ignore (doc-example)
344 /// /// The `my_lint_name` lint detects [short explanation here].
349 /// /// [insert a concise example that triggers the lint]
354 /// /// ### Explanation
356 /// /// This should be a detailed explanation of *why* the lint exists,
357 /// /// and also include suggestions on how the user should fix the problem.
358 /// /// Try to keep the text simple enough that a beginner can understand,
359 /// /// and include links to other documentation for terminology that a
360 /// /// beginner may not be familiar with. If this is "allow" by default,
361 /// /// it should explain why (are there false positives or other issues?). If
362 /// /// this is a future-incompatible lint, it should say so, with text that
363 /// /// looks roughly like this:
365 /// /// This is a [future-incompatible] lint to transition this to a hard
366 /// /// error in the future. See [issue #xxxxx] for more details.
368 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
371 /// The `{{produces}}` tag will be automatically replaced with the output from
372 /// the example by the build system. If the lint example is too complex to run
373 /// as a simple example (for example, it needs an extern crate), mark the code
374 /// block with `ignore` and manually replace the `{{produces}}` line with the
375 /// expected output in a `text` code block.
377 /// If this is a rustdoc-only lint, then only include a brief introduction
378 /// with a link with the text `[rustdoc book]` so that the validator knows
379 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
381 /// Commands to view and test the documentation:
383 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
384 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
385 /// correct style, and that the code example actually emits the expected
388 /// If you have already built the compiler, and you want to make changes to
389 /// just the doc comments, then use the `--keep-stage=0` flag with the above
390 /// commands to avoid rebuilding the compiler.
392 macro_rules! declare_lint {
393 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
394 $crate::declare_lint!(
395 $(#[$attr])* $vis $NAME, $Level, $desc,
398 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
399 $(@feature_gate = $gate:expr;)?
400 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
403 $vis static $NAME: &$crate::Lint = &$crate::Lint {
404 name: stringify!($NAME),
405 default_level: $crate::$Level,
407 edition_lint_opts: None,
410 $(feature_gate: Some($gate),)*
411 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
413 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
415 ..$crate::Lint::default_fields_for_macro()
418 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
419 $lint_edition: expr => $edition_level: ident
422 $vis static $NAME: &$crate::Lint = &$crate::Lint {
423 name: stringify!($NAME),
424 default_level: $crate::$Level,
426 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
427 report_in_external_macro: false,
434 macro_rules! declare_tool_lint {
436 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
438 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
441 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
442 report_in_external_macro: $rep:expr
444 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
447 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
451 $vis static $NAME: &$crate::Lint = &$crate::Lint {
452 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
453 default_level: $crate::$Level,
455 edition_lint_opts: None,
456 report_in_external_macro: $external,
457 future_incompatible: None,
460 crate_level_only: false,
465 /// Declares a static `LintArray` and return it as an expression.
467 macro_rules! lint_array {
468 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
469 ($( $lint:expr ),*) => {{
474 pub type LintArray = Vec<&'static Lint>;
477 fn name(&self) -> &'static str;
480 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
482 macro_rules! impl_lint_pass {
483 ($ty:ty => [$($lint:expr),* $(,)?]) => {
484 impl $crate::LintPass for $ty {
485 fn name(&self) -> &'static str { stringify!($ty) }
488 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
493 /// Declares a type named `$name` which implements `LintPass`.
494 /// To the right of `=>` a comma separated list of `Lint` statics is given.
496 macro_rules! declare_lint_pass {
497 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
498 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
499 $crate::impl_lint_pass!($name => [$($lint),*]);