1 #![feature(min_specialization)]
4 extern crate rustc_macros;
6 pub use self::Level::*;
7 use rustc_ast::node_id::{NodeId, NodeMap};
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
9 use rustc_serialize::json::Json;
10 use rustc_span::edition::Edition;
11 use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
12 use rustc_target::spec::abi::Abi;
17 macro_rules! pluralize {
19 if $x != 1 { "s" } else { "" }
23 /// Indicates the confidence in the correctness of a suggestion.
25 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
26 /// to determine whether it should be automatically applied or if the user should be consulted
27 /// before applying the suggestion.
28 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
29 pub enum Applicability {
30 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
31 /// This suggestion should be automatically applied.
33 /// In case of multiple `MachineApplicable` suggestions (whether as part of
34 /// the same `multipart_suggestion` or not), all of them should be
35 /// automatically applied.
38 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
39 /// result in valid Rust code if it is applied.
42 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
43 /// cannot be applied automatically because it will not result in valid Rust code. The user
44 /// will need to fill in the placeholders.
47 /// The applicability of the suggestion is unknown.
51 rustc_index::newtype_index! {
52 /// FIXME: The lint expectation ID is currently a simple copy of the `AttrId`
53 /// that the expectation originated from. In the future it should be generated
54 /// by other means. This is for one to keep the IDs independent of each other
55 /// and also to ensure that it is actually stable between compilation sessions.
56 /// (The `AttrId` for instance, is not stable).
58 /// Additionally, it would be nice if this generation could be moved into
59 /// [`Level::from_symbol`] to have it all contained in one module and to
60 /// make it simpler to use.
61 pub struct LintExpectationId {
62 DEBUG_FORMAT = "LintExpectationId({})"
66 rustc_data_structures::impl_stable_hash_via_hash!(LintExpectationId);
68 impl<HCX> ToStableHashKey<HCX> for LintExpectationId {
72 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
77 /// Setting for how to handle a lint.
79 /// See: https://doc.rust-lang.org/rustc/lints/levels.html
80 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
82 /// The `allow` level will not issue any message.
84 /// The `expect` level will suppress the lint message but intern produce a message
85 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
86 /// an initial level for a lint.
88 /// Note that this still means that the lint is enabled in this position and should
89 /// be emitted, this will intern fulfill the expectation and suppress the lint.
93 /// The `LintExpectationId` is used to later link a lint emission to the actual
94 /// expectation. It can be ignored in most cases.
95 Expect(LintExpectationId),
96 /// The `warn` level will produce a warning if the lint was violated, however the
97 /// compiler will continue with its execution.
100 /// The `deny` level will produce an error and stop further execution after the lint
101 /// pass is complete.
103 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
108 rustc_data_structures::impl_stable_hash_via_hash!(Level);
111 /// Converts a level to a lower-case string.
112 pub fn as_str(self) -> &'static str {
114 Level::Allow => "allow",
115 Level::Expect(_) => "expect",
116 Level::Warn => "warn",
117 Level::ForceWarn => "force-warn",
118 Level::Deny => "deny",
119 Level::Forbid => "forbid",
123 /// Converts a lower-case string to a level. This will never construct the expect
124 /// level as that would require a [`LintExpectationId`]
125 pub fn from_str(x: &str) -> Option<Level> {
127 "allow" => Some(Level::Allow),
128 "warn" => Some(Level::Warn),
129 "deny" => Some(Level::Deny),
130 "forbid" => Some(Level::Forbid),
131 "expect" | _ => None,
135 /// Converts a symbol to a level.
136 pub fn from_symbol(x: Symbol, possible_lint_expect_id: u32) -> Option<Level> {
138 sym::allow => Some(Level::Allow),
139 sym::expect => Some(Level::Expect(LintExpectationId::from(possible_lint_expect_id))),
140 sym::warn => Some(Level::Warn),
141 sym::deny => Some(Level::Deny),
142 sym::forbid => Some(Level::Forbid),
148 /// Specification of a single lint.
149 #[derive(Copy, Clone, Debug)]
151 /// A string identifier for the lint.
153 /// This identifies the lint in attributes and in command-line arguments.
154 /// In those contexts it is always lowercase, but this field is compared
155 /// in a way which is case-insensitive for ASCII characters. This allows
156 /// `declare_lint!()` invocations to follow the convention of upper-case
157 /// statics without repeating the name.
159 /// The name is written with underscores, e.g., "unused_imports".
160 /// On the command line, underscores become dashes.
162 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
163 /// for naming guidelines.
164 pub name: &'static str,
166 /// Default level for the lint.
168 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
169 /// for guidelines on choosing a default level.
170 pub default_level: Level,
172 /// Description of the lint or the issue it detects.
174 /// e.g., "imports that are never used"
175 pub desc: &'static str,
177 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
179 pub edition_lint_opts: Option<(Edition, Level)>,
181 /// `true` if this lint is reported even inside expansions of external macros.
182 pub report_in_external_macro: bool,
184 pub future_incompatible: Option<FutureIncompatibleInfo>,
188 /// `Some` if this lint is feature gated, otherwise `None`.
189 pub feature_gate: Option<Symbol>,
191 pub crate_level_only: bool,
194 /// Extra information for a future incompatibility lint.
195 #[derive(Copy, Clone, Debug)]
196 pub struct FutureIncompatibleInfo {
197 /// e.g., a URL for an issue/PR/RFC or error code
198 pub reference: &'static str,
199 /// The reason for the lint used by diagnostics to provide
200 /// the right help message
201 pub reason: FutureIncompatibilityReason,
202 /// Whether to explain the reason to the user.
204 /// Set to false for lints that already include a more detailed
206 pub explain_reason: bool,
209 /// The reason for future incompatibility
210 #[derive(Copy, Clone, Debug)]
211 pub enum FutureIncompatibilityReason {
212 /// This will be an error in a future release
215 /// This will be an error in a future release, and
216 /// Cargo should create a report even for dependencies
217 FutureReleaseErrorReportNow,
218 /// Code that changes meaning in some way in a
220 FutureReleaseSemanticsChange,
221 /// Previously accepted code that will become an
222 /// error in the provided edition
223 EditionError(Edition),
224 /// Code that changes meaning in some way in
225 /// the provided edition
226 EditionSemanticsChange(Edition),
228 Custom(&'static str),
231 impl FutureIncompatibilityReason {
232 pub fn edition(self) -> Option<Edition> {
234 Self::EditionError(e) => Some(e),
235 Self::EditionSemanticsChange(e) => Some(e),
241 impl FutureIncompatibleInfo {
242 pub const fn default_fields_for_macro() -> Self {
243 FutureIncompatibleInfo {
245 reason: FutureIncompatibilityReason::FutureReleaseError,
246 explain_reason: true,
252 pub const fn default_fields_for_macro() -> Self {
255 default_level: Level::Forbid,
257 edition_lint_opts: None,
259 report_in_external_macro: false,
260 future_incompatible: None,
262 crate_level_only: false,
266 /// Gets the lint's name, with ASCII letters converted to lowercase.
267 pub fn name_lower(&self) -> String {
268 self.name.to_ascii_lowercase()
271 pub fn default_level(&self, edition: Edition) -> Level {
272 self.edition_lint_opts
273 .filter(|(e, _)| *e <= edition)
275 .unwrap_or(self.default_level)
279 /// Identifies a lint known to the compiler.
280 #[derive(Clone, Copy, Debug)]
282 // Identity is based on pointer equality of this field.
283 pub lint: &'static Lint,
286 impl PartialEq for LintId {
287 fn eq(&self, other: &LintId) -> bool {
288 std::ptr::eq(self.lint, other.lint)
292 impl Eq for LintId {}
294 impl std::hash::Hash for LintId {
295 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
296 let ptr = self.lint as *const Lint;
302 /// Gets the `LintId` for a `Lint`.
303 pub fn of(lint: &'static Lint) -> LintId {
307 pub fn lint_name_raw(&self) -> &'static str {
311 /// Gets the name of the lint.
312 pub fn to_string(&self) -> String {
313 self.lint.name_lower()
317 impl<HCX> HashStable<HCX> for LintId {
319 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
320 self.lint_name_raw().hash_stable(hcx, hasher);
324 impl<HCX> ToStableHashKey<HCX> for LintId {
325 type KeyType = &'static str;
328 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
333 // Duplicated from rustc_session::config::ExternDepSpec to avoid cyclic dependency
334 #[derive(PartialEq, Debug)]
335 pub enum ExternDepSpec {
340 // This could be a closure, but then implementing derive trait
341 // becomes hacky (and it gets allocated).
343 pub enum BuiltinLintDiagnostics {
345 AbsPathWithModule(Span),
346 ProcMacroDeriveResolutionFallback(Span),
347 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
348 UnknownCrateTypes(Span, String, String),
349 UnusedImports(String, Vec<(Span, String)>, Option<Span>),
350 RedundantImport(Vec<(Span, bool)>, Ident),
351 DeprecatedMacro(Option<Symbol>, Span),
352 MissingAbi(Span, Abi),
353 UnusedDocComment(Span),
354 UnusedBuiltinAttribute { attr_name: Symbol, macro_name: String, invoc_span: Span },
355 PatternsInFnsWithoutBody(Span, Ident),
356 LegacyDeriveHelpers(Span),
357 ExternDepSpec(String, ExternDepSpec),
358 ProcMacroBackCompat(String),
359 OrPatternsBackCompat(Span, String),
360 ReservedPrefix(Span),
361 TrailingMacro(bool, Ident),
362 BreakWithLabelAndLoop(Span),
363 NamedAsmLabel(String),
364 UnicodeTextFlow(Span, String),
365 UnexpectedCfg(Span, Symbol, Option<Symbol>),
368 /// Lints that are buffered up early on in the `Session` before the
369 /// `LintLevels` is calculated.
370 pub struct BufferedEarlyLint {
371 /// The span of code that we are linting on.
374 /// The lint message.
377 /// The `NodeId` of the AST node that generated the lint.
380 /// A lint Id that can be passed to
381 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
384 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
385 pub diagnostic: BuiltinLintDiagnostics,
389 pub struct LintBuffer {
390 pub map: NodeMap<Vec<BufferedEarlyLint>>,
394 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
395 let arr = self.map.entry(early_lint.node_id).or_default();
396 arr.push(early_lint);
405 diagnostic: BuiltinLintDiagnostics,
407 let lint_id = LintId::of(lint);
408 let msg = msg.to_string();
409 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
412 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
413 self.map.remove(&id).unwrap_or_default()
420 sp: impl Into<MultiSpan>,
423 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
426 pub fn buffer_lint_with_diagnostic(
430 sp: impl Into<MultiSpan>,
432 diagnostic: BuiltinLintDiagnostics,
434 self.add_lint(lint, id, sp.into(), msg, diagnostic)
438 /// Declares a static item of type `&'static Lint`.
440 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
441 /// documentation and guidelines on writing lints.
443 /// The macro call should start with a doc comment explaining the lint
444 /// which will be embedded in the rustc user documentation book. It should
445 /// be written in markdown and have a format that looks like this:
447 /// ```rust,ignore (doc-example)
448 /// /// The `my_lint_name` lint detects [short explanation here].
453 /// /// [insert a concise example that triggers the lint]
458 /// /// ### Explanation
460 /// /// This should be a detailed explanation of *why* the lint exists,
461 /// /// and also include suggestions on how the user should fix the problem.
462 /// /// Try to keep the text simple enough that a beginner can understand,
463 /// /// and include links to other documentation for terminology that a
464 /// /// beginner may not be familiar with. If this is "allow" by default,
465 /// /// it should explain why (are there false positives or other issues?). If
466 /// /// this is a future-incompatible lint, it should say so, with text that
467 /// /// looks roughly like this:
469 /// /// This is a [future-incompatible] lint to transition this to a hard
470 /// /// error in the future. See [issue #xxxxx] for more details.
472 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
475 /// The `{{produces}}` tag will be automatically replaced with the output from
476 /// the example by the build system. If the lint example is too complex to run
477 /// as a simple example (for example, it needs an extern crate), mark the code
478 /// block with `ignore` and manually replace the `{{produces}}` line with the
479 /// expected output in a `text` code block.
481 /// If this is a rustdoc-only lint, then only include a brief introduction
482 /// with a link with the text `[rustdoc book]` so that the validator knows
483 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
485 /// Commands to view and test the documentation:
487 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
488 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
489 /// correct style, and that the code example actually emits the expected
492 /// If you have already built the compiler, and you want to make changes to
493 /// just the doc comments, then use the `--keep-stage=0` flag with the above
494 /// commands to avoid rebuilding the compiler.
496 macro_rules! declare_lint {
497 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
498 $crate::declare_lint!(
499 $(#[$attr])* $vis $NAME, $Level, $desc,
502 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
503 $(@feature_gate = $gate:expr;)?
504 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
507 $vis static $NAME: &$crate::Lint = &$crate::Lint {
508 name: stringify!($NAME),
509 default_level: $crate::$Level,
511 edition_lint_opts: None,
514 $(feature_gate: Some($gate),)*
515 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
517 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
519 ..$crate::Lint::default_fields_for_macro()
522 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
523 $lint_edition: expr => $edition_level: ident
526 $vis static $NAME: &$crate::Lint = &$crate::Lint {
527 name: stringify!($NAME),
528 default_level: $crate::$Level,
530 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
531 report_in_external_macro: false,
538 macro_rules! declare_tool_lint {
540 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
542 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
545 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
546 report_in_external_macro: $rep:expr
548 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
551 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
555 $vis static $NAME: &$crate::Lint = &$crate::Lint {
556 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
557 default_level: $crate::$Level,
559 edition_lint_opts: None,
560 report_in_external_macro: $external,
561 future_incompatible: None,
564 crate_level_only: false,
569 /// Declares a static `LintArray` and return it as an expression.
571 macro_rules! lint_array {
572 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
573 ($( $lint:expr ),*) => {{
578 pub type LintArray = Vec<&'static Lint>;
581 fn name(&self) -> &'static str;
584 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
586 macro_rules! impl_lint_pass {
587 ($ty:ty => [$($lint:expr),* $(,)?]) => {
588 impl $crate::LintPass for $ty {
589 fn name(&self) -> &'static str { stringify!($ty) }
592 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
597 /// Declares a type named `$name` which implements `LintPass`.
598 /// To the right of `=>` a comma separated list of `Lint` statics is given.
600 macro_rules! declare_lint_pass {
601 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
602 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
603 $crate::impl_lint_pass!($name => [$($lint),*]);