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}
;
13 macro_rules
! pluralize
{
15 if $x
!= 1 { "s" }
else { "" }
19 /// Indicates the confidence in the correctness of a suggestion.
21 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
22 /// to determine whether it should be automatically applied or if the user should be consulted
23 /// before applying the suggestion.
24 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
25 pub enum Applicability
{
26 /// The suggestion is definitely what the user intended. This suggestion should be
27 /// automatically applied.
30 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
31 /// result in valid Rust code if it is applied.
34 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
35 /// cannot be applied automatically because it will not result in valid Rust code. The user
36 /// will need to fill in the placeholders.
39 /// The applicability of the suggestion is unknown.
43 /// Setting for how to handle a lint.
44 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
52 rustc_data_structures
::impl_stable_hash_via_hash
!(Level
);
55 /// Converts a level to a lower-case string.
56 pub fn as_str(self) -> &'
static str {
58 Level
::Allow
=> "allow",
59 Level
::Warn
=> "warn",
60 Level
::Deny
=> "deny",
61 Level
::Forbid
=> "forbid",
65 /// Converts a lower-case string to a level.
66 pub fn from_str(x
: &str) -> Option
<Level
> {
68 "allow" => Some(Level
::Allow
),
69 "warn" => Some(Level
::Warn
),
70 "deny" => Some(Level
::Deny
),
71 "forbid" => Some(Level
::Forbid
),
76 /// Converts a symbol to a level.
77 pub fn from_symbol(x
: Symbol
) -> Option
<Level
> {
79 sym
::allow
=> Some(Level
::Allow
),
80 sym
::warn
=> Some(Level
::Warn
),
81 sym
::deny
=> Some(Level
::Deny
),
82 sym
::forbid
=> Some(Level
::Forbid
),
88 /// Specification of a single lint.
89 #[derive(Copy, Clone, Debug)]
91 /// A string identifier for the lint.
93 /// This identifies the lint in attributes and in command-line arguments.
94 /// In those contexts it is always lowercase, but this field is compared
95 /// in a way which is case-insensitive for ASCII characters. This allows
96 /// `declare_lint!()` invocations to follow the convention of upper-case
97 /// statics without repeating the name.
99 /// The name is written with underscores, e.g., "unused_imports".
100 /// On the command line, underscores become dashes.
102 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
103 /// for naming guidelines.
104 pub name
: &'
static str,
106 /// Default level for the lint.
108 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
109 /// for guidelines on choosing a default level.
110 pub default_level
: Level
,
112 /// Description of the lint or the issue it detects.
114 /// e.g., "imports that are never used"
115 pub desc
: &'
static str,
117 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
119 pub edition_lint_opts
: Option
<(Edition
, Level
)>,
121 /// `true` if this lint is reported even inside expansions of external macros.
122 pub report_in_external_macro
: bool
,
124 pub future_incompatible
: Option
<FutureIncompatibleInfo
>,
128 /// `Some` if this lint is feature gated, otherwise `None`.
129 pub feature_gate
: Option
<Symbol
>,
131 pub crate_level_only
: bool
,
134 /// Extra information for a future incompatibility lint.
135 #[derive(Copy, Clone, Debug)]
136 pub struct FutureIncompatibleInfo
{
137 /// e.g., a URL for an issue/PR/RFC or error code
138 pub reference
: &'
static str,
139 /// If this is an edition fixing lint, the edition in which
140 /// this lint becomes obsolete
141 pub edition
: Option
<Edition
>,
142 /// Information about a future breakage, which will
143 /// be emitted in JSON messages to be displayed by Cargo
144 /// for upstream deps
145 pub future_breakage
: Option
<FutureBreakage
>,
148 #[derive(Copy, Clone, Debug)]
149 pub struct FutureBreakage
{
150 pub date
: Option
<&'
static str>,
153 impl FutureIncompatibleInfo
{
154 pub const fn default_fields_for_macro() -> Self {
155 FutureIncompatibleInfo { reference: "", edition: None, future_breakage: None }
160 pub const fn default_fields_for_macro() -> Self {
163 default_level
: Level
::Forbid
,
165 edition_lint_opts
: None
,
167 report_in_external_macro
: false,
168 future_incompatible
: None
,
170 crate_level_only
: false,
174 /// Gets the lint's name, with ASCII letters converted to lowercase.
175 pub fn name_lower(&self) -> String
{
176 self.name
.to_ascii_lowercase()
179 pub fn default_level(&self, edition
: Edition
) -> Level
{
180 self.edition_lint_opts
181 .filter(|(e
, _
)| *e
<= edition
)
183 .unwrap_or(self.default_level
)
187 /// Identifies a lint known to the compiler.
188 #[derive(Clone, Copy, Debug)]
190 // Identity is based on pointer equality of this field.
191 pub lint
: &'
static Lint
,
194 impl PartialEq
for LintId
{
195 fn eq(&self, other
: &LintId
) -> bool
{
196 std
::ptr
::eq(self.lint
, other
.lint
)
200 impl Eq
for LintId {}
202 impl std
::hash
::Hash
for LintId
{
203 fn hash
<H
: std
::hash
::Hasher
>(&self, state
: &mut H
) {
204 let ptr
= self.lint
as *const Lint
;
210 /// Gets the `LintId` for a `Lint`.
211 pub fn of(lint
: &'
static Lint
) -> LintId
{
215 pub fn lint_name_raw(&self) -> &'
static str {
219 /// Gets the name of the lint.
220 pub fn to_string(&self) -> String
{
221 self.lint
.name_lower()
225 impl<HCX
> HashStable
<HCX
> for LintId
{
227 fn hash_stable(&self, hcx
: &mut HCX
, hasher
: &mut StableHasher
) {
228 self.lint_name_raw().hash_stable(hcx
, hasher
);
232 impl<HCX
> ToStableHashKey
<HCX
> for LintId
{
233 type KeyType
= &'
static str;
236 fn to_stable_hash_key(&self, _
: &HCX
) -> &'
static str {
241 // This could be a closure, but then implementing derive trait
242 // becomes hacky (and it gets allocated).
244 pub enum BuiltinLintDiagnostics
{
246 BareTraitObject(Span
, /* is_global */ bool
),
247 AbsPathWithModule(Span
),
248 ProcMacroDeriveResolutionFallback(Span
),
249 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span
),
250 ElidedLifetimesInPaths(usize, Span
, bool
, Span
, String
),
251 UnknownCrateTypes(Span
, String
, String
),
252 UnusedImports(String
, Vec
<(Span
, String
)>),
253 RedundantImport(Vec
<(Span
, bool
)>, Ident
),
254 DeprecatedMacro(Option
<Symbol
>, Span
),
255 UnusedDocComment(Span
),
258 /// Lints that are buffered up early on in the `Session` before the
259 /// `LintLevels` is calculated.
261 pub struct BufferedEarlyLint
{
262 /// The span of code that we are linting on.
265 /// The lint message.
268 /// The `NodeId` of the AST node that generated the lint.
271 /// A lint Id that can be passed to
272 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
275 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
276 pub diagnostic
: BuiltinLintDiagnostics
,
280 pub struct LintBuffer
{
281 pub map
: NodeMap
<Vec
<BufferedEarlyLint
>>,
285 pub fn add_early_lint(&mut self, early_lint
: BufferedEarlyLint
) {
286 let arr
= self.map
.entry(early_lint
.node_id
).or_default();
287 if !arr
.contains(&early_lint
) {
288 arr
.push(early_lint
);
298 diagnostic
: BuiltinLintDiagnostics
,
300 let lint_id
= LintId
::of(lint
);
301 let msg
= msg
.to_string();
302 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic }
);
305 pub fn take(&mut self, id
: NodeId
) -> Vec
<BufferedEarlyLint
> {
306 self.map
.remove(&id
).unwrap_or_default()
313 sp
: impl Into
<MultiSpan
>,
316 self.add_lint(lint
, id
, sp
.into(), msg
, BuiltinLintDiagnostics
::Normal
)
319 pub fn buffer_lint_with_diagnostic(
323 sp
: impl Into
<MultiSpan
>,
325 diagnostic
: BuiltinLintDiagnostics
,
327 self.add_lint(lint
, id
, sp
.into(), msg
, diagnostic
)
331 /// Declares a static item of type `&'static Lint`.
333 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
334 /// documentation and guidelines on writing lints.
336 /// The macro call should start with a doc comment explaining the lint
337 /// which will be embedded in the rustc user documentation book. It should
338 /// be written in markdown and have a format that looks like this:
340 /// ```rust,ignore (doc-example)
341 /// /// The `my_lint_name` lint detects [short explanation here].
346 /// /// [insert a concise example that triggers the lint]
351 /// /// ### Explanation
353 /// /// This should be a detailed explanation of *why* the lint exists,
354 /// /// and also include suggestions on how the user should fix the problem.
355 /// /// Try to keep the text simple enough that a beginner can understand,
356 /// /// and include links to other documentation for terminology that a
357 /// /// beginner may not be familiar with. If this is "allow" by default,
358 /// /// it should explain why (are there false positives or other issues?). If
359 /// /// this is a future-incompatible lint, it should say so, with text that
360 /// /// looks roughly like this:
362 /// /// This is a [future-incompatible] lint to transition this to a hard
363 /// /// error in the future. See [issue #xxxxx] for more details.
365 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
368 /// The `{{produces}}` tag will be automatically replaced with the output from
369 /// the example by the build system. If the lint example is too complex to run
370 /// as a simple example (for example, it needs an extern crate), mark the code
371 /// block with `ignore` and manually replace the `{{produces}}` line with the
372 /// expected output in a `text` code block.
374 /// If this is a rustdoc-only lint, then only include a brief introduction
375 /// with a link with the text `[rustdoc book]` so that the validator knows
376 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
378 /// Commands to view and test the documentation:
380 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
381 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
382 /// correct style, and that the code example actually emits the expected
385 /// If you have already built the compiler, and you want to make changes to
386 /// just the doc comments, then use the `--keep-stage=0` flag with the above
387 /// commands to avoid rebuilding the compiler.
389 macro_rules
! declare_lint
{
390 ($
(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
391 $
crate::declare_lint
!(
392 $
(#[$attr])* $vis $NAME, $Level, $desc,
395 ($
(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
396 $
(@feature_gate
= $gate
:expr
;)?
397 $
(@future_incompatible
= FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }
; )?
400 $vis
static $NAME
: &$
crate::Lint
= &$
crate::Lint
{
401 name
: stringify
!($NAME
),
402 default_level
: $
crate::$Level
,
404 edition_lint_opts
: None
,
407 $
(feature_gate
: Some($gate
),)*
408 $
(future_incompatible
: Some($
crate::FutureIncompatibleInfo
{
410 ..$
crate::FutureIncompatibleInfo
::default_fields_for_macro()
412 ..$
crate::Lint
::default_fields_for_macro()
415 ($
(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
416 $lint_edition
: expr
=> $edition_level
: ident
419 $vis
static $NAME
: &$
crate::Lint
= &$
crate::Lint
{
420 name
: stringify
!($NAME
),
421 default_level
: $
crate::$Level
,
423 edition_lint_opts
: Some(($lint_edition
, $
crate::Level
::$edition_level
)),
424 report_in_external_macro
: false,
431 macro_rules
! declare_tool_lint
{
433 $
(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
435 $
crate::declare_tool_lint
!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
438 $
(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
439 report_in_external_macro
: $rep
:expr
441 $
crate::declare_tool_lint
!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
444 $
(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
448 $vis
static $NAME
: &$
crate::Lint
= &$
crate::Lint
{
449 name
: &concat
!(stringify
!($tool
), "::", stringify
!($NAME
)),
450 default_level
: $
crate::$Level
,
452 edition_lint_opts
: None
,
453 report_in_external_macro
: $external
,
454 future_incompatible
: None
,
457 crate_level_only
: false,
462 /// Declares a static `LintArray` and return it as an expression.
464 macro_rules
! lint_array
{
465 ($
( $lint
:expr
),* ,) => { lint_array!( $($lint),* ) }
;
466 ($
( $lint
:expr
),*) => {{
471 pub type LintArray
= Vec
<&'
static Lint
>;
474 fn name(&self) -> &'
static str;
477 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
479 macro_rules
! impl_lint_pass
{
480 ($ty
:ty
=> [$
($lint
:expr
),* $
(,)?
]) => {
481 impl $
crate::LintPass
for $ty
{
482 fn name(&self) -> &'
static str { stringify!($ty) }
485 pub fn get_lints() -> $
crate::LintArray { $crate::lint_array!($($lint),*) }
490 /// Declares a type named `$name` which implements `LintPass`.
491 /// To the right of `=>` a comma separated list of `Lint` statics is given.
493 macro_rules
! declare_lint_pass
{
494 ($
(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
495 $
(#[$m])* #[derive(Copy, Clone)] pub struct $name;
496 $
crate::impl_lint_pass
!($name
=> [$
($lint
),*]);