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
),
269 ProcMacroBackCompat(String
),
272 /// Lints that are buffered up early on in the `Session` before the
273 /// `LintLevels` is calculated.
275 pub struct BufferedEarlyLint
{
276 /// The span of code that we are linting on.
279 /// The lint message.
282 /// The `NodeId` of the AST node that generated the lint.
285 /// A lint Id that can be passed to
286 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
289 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
290 pub diagnostic
: BuiltinLintDiagnostics
,
294 pub struct LintBuffer
{
295 pub map
: NodeMap
<Vec
<BufferedEarlyLint
>>,
299 pub fn add_early_lint(&mut self, early_lint
: BufferedEarlyLint
) {
300 let arr
= self.map
.entry(early_lint
.node_id
).or_default();
301 if !arr
.contains(&early_lint
) {
302 arr
.push(early_lint
);
312 diagnostic
: BuiltinLintDiagnostics
,
314 let lint_id
= LintId
::of(lint
);
315 let msg
= msg
.to_string();
316 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic }
);
319 pub fn take(&mut self, id
: NodeId
) -> Vec
<BufferedEarlyLint
> {
320 self.map
.remove(&id
).unwrap_or_default()
327 sp
: impl Into
<MultiSpan
>,
330 self.add_lint(lint
, id
, sp
.into(), msg
, BuiltinLintDiagnostics
::Normal
)
333 pub fn buffer_lint_with_diagnostic(
337 sp
: impl Into
<MultiSpan
>,
339 diagnostic
: BuiltinLintDiagnostics
,
341 self.add_lint(lint
, id
, sp
.into(), msg
, diagnostic
)
345 /// Declares a static item of type `&'static Lint`.
347 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
348 /// documentation and guidelines on writing lints.
350 /// The macro call should start with a doc comment explaining the lint
351 /// which will be embedded in the rustc user documentation book. It should
352 /// be written in markdown and have a format that looks like this:
354 /// ```rust,ignore (doc-example)
355 /// /// The `my_lint_name` lint detects [short explanation here].
360 /// /// [insert a concise example that triggers the lint]
365 /// /// ### Explanation
367 /// /// This should be a detailed explanation of *why* the lint exists,
368 /// /// and also include suggestions on how the user should fix the problem.
369 /// /// Try to keep the text simple enough that a beginner can understand,
370 /// /// and include links to other documentation for terminology that a
371 /// /// beginner may not be familiar with. If this is "allow" by default,
372 /// /// it should explain why (are there false positives or other issues?). If
373 /// /// this is a future-incompatible lint, it should say so, with text that
374 /// /// looks roughly like this:
376 /// /// This is a [future-incompatible] lint to transition this to a hard
377 /// /// error in the future. See [issue #xxxxx] for more details.
379 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
382 /// The `{{produces}}` tag will be automatically replaced with the output from
383 /// the example by the build system. If the lint example is too complex to run
384 /// as a simple example (for example, it needs an extern crate), mark the code
385 /// block with `ignore` and manually replace the `{{produces}}` line with the
386 /// expected output in a `text` code block.
388 /// If this is a rustdoc-only lint, then only include a brief introduction
389 /// with a link with the text `[rustdoc book]` so that the validator knows
390 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
392 /// Commands to view and test the documentation:
394 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
395 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
396 /// correct style, and that the code example actually emits the expected
399 /// If you have already built the compiler, and you want to make changes to
400 /// just the doc comments, then use the `--keep-stage=0` flag with the above
401 /// commands to avoid rebuilding the compiler.
403 macro_rules
! declare_lint
{
404 ($
(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
405 $
crate::declare_lint
!(
406 $
(#[$attr])* $vis $NAME, $Level, $desc,
409 ($
(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
410 $
(@feature_gate
= $gate
:expr
;)?
411 $
(@future_incompatible
= FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }
; )?
414 $vis
static $NAME
: &$
crate::Lint
= &$
crate::Lint
{
415 name
: stringify
!($NAME
),
416 default_level
: $
crate::$Level
,
418 edition_lint_opts
: None
,
421 $
(feature_gate
: Some($gate
),)*
422 $
(future_incompatible
: Some($
crate::FutureIncompatibleInfo
{
424 ..$
crate::FutureIncompatibleInfo
::default_fields_for_macro()
426 ..$
crate::Lint
::default_fields_for_macro()
429 ($
(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
430 $lint_edition
: expr
=> $edition_level
: ident
433 $vis
static $NAME
: &$
crate::Lint
= &$
crate::Lint
{
434 name
: stringify
!($NAME
),
435 default_level
: $
crate::$Level
,
437 edition_lint_opts
: Some(($lint_edition
, $
crate::Level
::$edition_level
)),
438 report_in_external_macro
: false,
445 macro_rules
! declare_tool_lint
{
447 $
(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
449 $
crate::declare_tool_lint
!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
452 $
(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
453 report_in_external_macro
: $rep
:expr
455 $
crate::declare_tool_lint
!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
458 $
(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
462 $vis
static $NAME
: &$
crate::Lint
= &$
crate::Lint
{
463 name
: &concat
!(stringify
!($tool
), "::", stringify
!($NAME
)),
464 default_level
: $
crate::$Level
,
466 edition_lint_opts
: None
,
467 report_in_external_macro
: $external
,
468 future_incompatible
: None
,
471 crate_level_only
: false,
476 /// Declares a static `LintArray` and return it as an expression.
478 macro_rules
! lint_array
{
479 ($
( $lint
:expr
),* ,) => { lint_array!( $($lint),* ) }
;
480 ($
( $lint
:expr
),*) => {{
485 pub type LintArray
= Vec
<&'
static Lint
>;
488 fn name(&self) -> &'
static str;
491 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
493 macro_rules
! impl_lint_pass
{
494 ($ty
:ty
=> [$
($lint
:expr
),* $
(,)?
]) => {
495 impl $
crate::LintPass
for $ty
{
496 fn name(&self) -> &'
static str { stringify!($ty) }
499 pub fn get_lints() -> $
crate::LintArray { $crate::lint_array!($($lint),*) }
504 /// Declares a type named `$name` which implements `LintPass`.
505 /// To the right of `=>` a comma separated list of `Lint` statics is given.
507 macro_rules
! declare_lint_pass
{
508 ($
(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
509 $
(#[$m])* #[derive(Copy, Clone)] pub struct $name;
510 $
crate::impl_lint_pass
!($name
=> [$
($lint
),*]);