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, or maintains the exact meaning of the code.
29 /// This suggestion should be automatically applied.
31 /// In case of multiple `MachineApplicable` suggestions (whether as part of
32 /// the same `multipart_suggestion` or not), all of them should be
33 /// automatically applied.
36 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
37 /// result in valid Rust code if it is applied.
40 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
41 /// cannot be applied automatically because it will not result in valid Rust code. The user
42 /// will need to fill in the placeholders.
45 /// The applicability of the suggestion is unknown.
49 /// Setting for how to handle a lint.
50 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
59 rustc_data_structures::impl_stable_hash_via_hash!(Level);
62 /// Converts a level to a lower-case string.
63 pub fn as_str(self) -> &'static str {
65 Level::Allow => "allow",
66 Level::Warn => "warn",
67 Level::ForceWarn => "force-warn",
68 Level::Deny => "deny",
69 Level::Forbid => "forbid",
73 /// Converts a lower-case string to a level.
74 pub fn from_str(x: &str) -> Option<Level> {
76 "allow" => Some(Level::Allow),
77 "warn" => Some(Level::Warn),
78 "deny" => Some(Level::Deny),
79 "forbid" => Some(Level::Forbid),
84 /// Converts a symbol to a level.
85 pub fn from_symbol(x: Symbol) -> Option<Level> {
87 sym::allow => Some(Level::Allow),
88 sym::warn => Some(Level::Warn),
89 sym::deny => Some(Level::Deny),
90 sym::forbid => Some(Level::Forbid),
96 /// Specification of a single lint.
97 #[derive(Copy, Clone, Debug)]
99 /// A string identifier for the lint.
101 /// This identifies the lint in attributes and in command-line arguments.
102 /// In those contexts it is always lowercase, but this field is compared
103 /// in a way which is case-insensitive for ASCII characters. This allows
104 /// `declare_lint!()` invocations to follow the convention of upper-case
105 /// statics without repeating the name.
107 /// The name is written with underscores, e.g., "unused_imports".
108 /// On the command line, underscores become dashes.
110 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
111 /// for naming guidelines.
112 pub name: &'static str,
114 /// Default level for the lint.
116 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
117 /// for guidelines on choosing a default level.
118 pub default_level: Level,
120 /// Description of the lint or the issue it detects.
122 /// e.g., "imports that are never used"
123 pub desc: &'static str,
125 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
127 pub edition_lint_opts: Option<(Edition, Level)>,
129 /// `true` if this lint is reported even inside expansions of external macros.
130 pub report_in_external_macro: bool,
132 pub future_incompatible: Option<FutureIncompatibleInfo>,
136 /// `Some` if this lint is feature gated, otherwise `None`.
137 pub feature_gate: Option<Symbol>,
139 pub crate_level_only: bool,
142 /// Extra information for a future incompatibility lint.
143 #[derive(Copy, Clone, Debug)]
144 pub struct FutureIncompatibleInfo {
145 /// e.g., a URL for an issue/PR/RFC or error code
146 pub reference: &'static str,
147 /// The reason for the lint used by diagnostics to provide
148 /// the right help message
149 pub reason: FutureIncompatibilityReason,
150 /// Whether to explain the reason to the user.
152 /// Set to false for lints that already include a more detailed
154 pub explain_reason: bool,
157 /// The reason for future incompatibility
158 #[derive(Copy, Clone, Debug)]
159 pub enum FutureIncompatibilityReason {
160 /// This will be an error in a future release
163 /// This will be an error in a future release, and
164 /// Cargo should create a report even for dependencies
165 FutureReleaseErrorReportNow,
166 /// Code that changes meaning in some way in a
168 FutureReleaseSemanticsChange,
169 /// Previously accepted code that will become an
170 /// error in the provided edition
171 EditionError(Edition),
172 /// Code that changes meaning in some way in
173 /// the provided edition
174 EditionSemanticsChange(Edition),
176 Custom(&'static str),
179 impl FutureIncompatibilityReason {
180 pub fn edition(self) -> Option<Edition> {
182 Self::EditionError(e) => Some(e),
183 Self::EditionSemanticsChange(e) => Some(e),
189 impl FutureIncompatibleInfo {
190 pub const fn default_fields_for_macro() -> Self {
191 FutureIncompatibleInfo {
193 reason: FutureIncompatibilityReason::FutureReleaseError,
194 explain_reason: true,
200 pub const fn default_fields_for_macro() -> Self {
203 default_level: Level::Forbid,
205 edition_lint_opts: None,
207 report_in_external_macro: false,
208 future_incompatible: None,
210 crate_level_only: false,
214 /// Gets the lint's name, with ASCII letters converted to lowercase.
215 pub fn name_lower(&self) -> String {
216 self.name.to_ascii_lowercase()
219 pub fn default_level(&self, edition: Edition) -> Level {
220 self.edition_lint_opts
221 .filter(|(e, _)| *e <= edition)
223 .unwrap_or(self.default_level)
227 /// Identifies a lint known to the compiler.
228 #[derive(Clone, Copy, Debug)]
230 // Identity is based on pointer equality of this field.
231 pub lint: &'static Lint,
234 impl PartialEq for LintId {
235 fn eq(&self, other: &LintId) -> bool {
236 std::ptr::eq(self.lint, other.lint)
240 impl Eq for LintId {}
242 impl std::hash::Hash for LintId {
243 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
244 let ptr = self.lint as *const Lint;
250 /// Gets the `LintId` for a `Lint`.
251 pub fn of(lint: &'static Lint) -> LintId {
255 pub fn lint_name_raw(&self) -> &'static str {
259 /// Gets the name of the lint.
260 pub fn to_string(&self) -> String {
261 self.lint.name_lower()
265 impl<HCX> HashStable<HCX> for LintId {
267 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
268 self.lint_name_raw().hash_stable(hcx, hasher);
272 impl<HCX> ToStableHashKey<HCX> for LintId {
273 type KeyType = &'static str;
276 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
281 // Duplicated from rustc_session::config::ExternDepSpec to avoid cyclic dependency
282 #[derive(PartialEq, Debug)]
283 pub enum ExternDepSpec {
288 // This could be a closure, but then implementing derive trait
289 // becomes hacky (and it gets allocated).
291 pub enum BuiltinLintDiagnostics {
293 AbsPathWithModule(Span),
294 ProcMacroDeriveResolutionFallback(Span),
295 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
296 UnknownCrateTypes(Span, String, String),
297 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
298 RedundantImport(Vec<(Span, bool)>, Ident),
299 DeprecatedMacro(Option<Symbol>, Span),
300 MissingAbi(Span, Abi),
301 UnusedDocComment(Span),
302 UnusedBuiltinAttribute { attr_name: Symbol, macro_name: String, invoc_span: Span },
303 PatternsInFnsWithoutBody(Span, Ident),
304 LegacyDeriveHelpers(Span),
305 ExternDepSpec(String, ExternDepSpec),
306 ProcMacroBackCompat(String),
307 OrPatternsBackCompat(Span, String),
308 ReservedPrefix(Span),
309 TrailingMacro(bool, Ident),
310 BreakWithLabelAndLoop(Span),
311 NamedAsmLabel(String),
312 UnicodeTextFlow(Span, String),
315 /// Lints that are buffered up early on in the `Session` before the
316 /// `LintLevels` is calculated.
317 pub struct BufferedEarlyLint {
318 /// The span of code that we are linting on.
321 /// The lint message.
324 /// The `NodeId` of the AST node that generated the lint.
327 /// A lint Id that can be passed to
328 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
331 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
332 pub diagnostic: BuiltinLintDiagnostics,
336 pub struct LintBuffer {
337 pub map: NodeMap<Vec<BufferedEarlyLint>>,
341 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
342 let arr = self.map.entry(early_lint.node_id).or_default();
343 arr.push(early_lint);
352 diagnostic: BuiltinLintDiagnostics,
354 let lint_id = LintId::of(lint);
355 let msg = msg.to_string();
356 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
359 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
360 self.map.remove(&id).unwrap_or_default()
367 sp: impl Into<MultiSpan>,
370 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
373 pub fn buffer_lint_with_diagnostic(
377 sp: impl Into<MultiSpan>,
379 diagnostic: BuiltinLintDiagnostics,
381 self.add_lint(lint, id, sp.into(), msg, diagnostic)
385 /// Declares a static item of type `&'static Lint`.
387 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
388 /// documentation and guidelines on writing lints.
390 /// The macro call should start with a doc comment explaining the lint
391 /// which will be embedded in the rustc user documentation book. It should
392 /// be written in markdown and have a format that looks like this:
394 /// ```rust,ignore (doc-example)
395 /// /// The `my_lint_name` lint detects [short explanation here].
400 /// /// [insert a concise example that triggers the lint]
405 /// /// ### Explanation
407 /// /// This should be a detailed explanation of *why* the lint exists,
408 /// /// and also include suggestions on how the user should fix the problem.
409 /// /// Try to keep the text simple enough that a beginner can understand,
410 /// /// and include links to other documentation for terminology that a
411 /// /// beginner may not be familiar with. If this is "allow" by default,
412 /// /// it should explain why (are there false positives or other issues?). If
413 /// /// this is a future-incompatible lint, it should say so, with text that
414 /// /// looks roughly like this:
416 /// /// This is a [future-incompatible] lint to transition this to a hard
417 /// /// error in the future. See [issue #xxxxx] for more details.
419 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
422 /// The `{{produces}}` tag will be automatically replaced with the output from
423 /// the example by the build system. If the lint example is too complex to run
424 /// as a simple example (for example, it needs an extern crate), mark the code
425 /// block with `ignore` and manually replace the `{{produces}}` line with the
426 /// expected output in a `text` code block.
428 /// If this is a rustdoc-only lint, then only include a brief introduction
429 /// with a link with the text `[rustdoc book]` so that the validator knows
430 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
432 /// Commands to view and test the documentation:
434 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
435 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
436 /// correct style, and that the code example actually emits the expected
439 /// If you have already built the compiler, and you want to make changes to
440 /// just the doc comments, then use the `--keep-stage=0` flag with the above
441 /// commands to avoid rebuilding the compiler.
443 macro_rules! declare_lint {
444 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
445 $crate::declare_lint!(
446 $(#[$attr])* $vis $NAME, $Level, $desc,
449 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
450 $(@feature_gate = $gate:expr;)?
451 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
454 $vis static $NAME: &$crate::Lint = &$crate::Lint {
455 name: stringify!($NAME),
456 default_level: $crate::$Level,
458 edition_lint_opts: None,
461 $(feature_gate: Some($gate),)*
462 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
464 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
466 ..$crate::Lint::default_fields_for_macro()
469 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
470 $lint_edition: expr => $edition_level: ident
473 $vis static $NAME: &$crate::Lint = &$crate::Lint {
474 name: stringify!($NAME),
475 default_level: $crate::$Level,
477 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
478 report_in_external_macro: false,
485 macro_rules! declare_tool_lint {
487 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
489 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
492 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
493 report_in_external_macro: $rep:expr
495 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
498 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
502 $vis static $NAME: &$crate::Lint = &$crate::Lint {
503 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
504 default_level: $crate::$Level,
506 edition_lint_opts: None,
507 report_in_external_macro: $external,
508 future_incompatible: None,
511 crate_level_only: false,
516 /// Declares a static `LintArray` and return it as an expression.
518 macro_rules! lint_array {
519 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
520 ($( $lint:expr ),*) => {{
525 pub type LintArray = Vec<&'static Lint>;
528 fn name(&self) -> &'static str;
531 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
533 macro_rules! impl_lint_pass {
534 ($ty:ty => [$($lint:expr),* $(,)?]) => {
535 impl $crate::LintPass for $ty {
536 fn name(&self) -> &'static str { stringify!($ty) }
539 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
544 /// Declares a type named `$name` which implements `LintPass`.
545 /// To the right of `=>` a comma separated list of `Lint` statics is given.
547 macro_rules! declare_lint_pass {
548 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
549 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
550 $crate::impl_lint_pass!($name => [$($lint),*]);