]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint_defs/src/lib.rs
Rollup merge of #84913 - estebank:issue-84831, r=varkor
[rust.git] / compiler / rustc_lint_defs / src / lib.rs
1 #[macro_use]
2 extern crate rustc_macros;
3
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;
11
12 pub mod builtin;
13
14 #[macro_export]
15 macro_rules! pluralize {
16     ($x:expr) => {
17         if $x != 1 { "s" } else { "" }
18     };
19 }
20
21 /// Indicates the confidence in the correctness of a suggestion.
22 ///
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.
30     MachineApplicable,
31
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.
34     MaybeIncorrect,
35
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.
39     HasPlaceholders,
40
41     /// The applicability of the suggestion is unknown.
42     Unspecified,
43 }
44
45 /// Setting for how to handle a lint.
46 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
47 pub enum Level {
48     Allow,
49     Warn,
50     Deny,
51     Forbid,
52 }
53
54 rustc_data_structures::impl_stable_hash_via_hash!(Level);
55
56 impl Level {
57     /// Converts a level to a lower-case string.
58     pub fn as_str(self) -> &'static str {
59         match self {
60             Level::Allow => "allow",
61             Level::Warn => "warn",
62             Level::Deny => "deny",
63             Level::Forbid => "forbid",
64         }
65     }
66
67     /// Converts a lower-case string to a level.
68     pub fn from_str(x: &str) -> Option<Level> {
69         match x {
70             "allow" => Some(Level::Allow),
71             "warn" => Some(Level::Warn),
72             "deny" => Some(Level::Deny),
73             "forbid" => Some(Level::Forbid),
74             _ => None,
75         }
76     }
77
78     /// Converts a symbol to a level.
79     pub fn from_symbol(x: Symbol) -> Option<Level> {
80         match x {
81             sym::allow => Some(Level::Allow),
82             sym::warn => Some(Level::Warn),
83             sym::deny => Some(Level::Deny),
84             sym::forbid => Some(Level::Forbid),
85             _ => None,
86         }
87     }
88 }
89
90 /// Specification of a single lint.
91 #[derive(Copy, Clone, Debug)]
92 pub struct Lint {
93     /// A string identifier for the lint.
94     ///
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.
100     ///
101     /// The name is written with underscores, e.g., "unused_imports".
102     /// On the command line, underscores become dashes.
103     ///
104     /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
105     /// for naming guidelines.
106     pub name: &'static str,
107
108     /// Default level for the lint.
109     ///
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,
113
114     /// Description of the lint or the issue it detects.
115     ///
116     /// e.g., "imports that are never used"
117     pub desc: &'static str,
118
119     /// Starting at the given edition, default to the given lint level. If this is `None`, then use
120     /// `default_level`.
121     pub edition_lint_opts: Option<(Edition, Level)>,
122
123     /// `true` if this lint is reported even inside expansions of external macros.
124     pub report_in_external_macro: bool,
125
126     pub future_incompatible: Option<FutureIncompatibleInfo>,
127
128     pub is_plugin: bool,
129
130     /// `Some` if this lint is feature gated, otherwise `None`.
131     pub feature_gate: Option<Symbol>,
132
133     pub crate_level_only: bool,
134 }
135
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>,
148 }
149
150 #[derive(Copy, Clone, Debug)]
151 pub struct FutureBreakage {
152     pub date: Option<&'static str>,
153 }
154
155 impl FutureIncompatibleInfo {
156     pub const fn default_fields_for_macro() -> Self {
157         FutureIncompatibleInfo { reference: "", edition: None, future_breakage: None }
158     }
159 }
160
161 impl Lint {
162     pub const fn default_fields_for_macro() -> Self {
163         Lint {
164             name: "",
165             default_level: Level::Forbid,
166             desc: "",
167             edition_lint_opts: None,
168             is_plugin: false,
169             report_in_external_macro: false,
170             future_incompatible: None,
171             feature_gate: None,
172             crate_level_only: false,
173         }
174     }
175
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()
179     }
180
181     pub fn default_level(&self, edition: Edition) -> Level {
182         self.edition_lint_opts
183             .filter(|(e, _)| *e <= edition)
184             .map(|(_, l)| l)
185             .unwrap_or(self.default_level)
186     }
187 }
188
189 /// Identifies a lint known to the compiler.
190 #[derive(Clone, Copy, Debug)]
191 pub struct LintId {
192     // Identity is based on pointer equality of this field.
193     pub lint: &'static Lint,
194 }
195
196 impl PartialEq for LintId {
197     fn eq(&self, other: &LintId) -> bool {
198         std::ptr::eq(self.lint, other.lint)
199     }
200 }
201
202 impl Eq for LintId {}
203
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;
207         ptr.hash(state);
208     }
209 }
210
211 impl LintId {
212     /// Gets the `LintId` for a `Lint`.
213     pub fn of(lint: &'static Lint) -> LintId {
214         LintId { lint }
215     }
216
217     pub fn lint_name_raw(&self) -> &'static str {
218         self.lint.name
219     }
220
221     /// Gets the name of the lint.
222     pub fn to_string(&self) -> String {
223         self.lint.name_lower()
224     }
225 }
226
227 impl<HCX> HashStable<HCX> for LintId {
228     #[inline]
229     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
230         self.lint_name_raw().hash_stable(hcx, hasher);
231     }
232 }
233
234 impl<HCX> ToStableHashKey<HCX> for LintId {
235     type KeyType = &'static str;
236
237     #[inline]
238     fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
239         self.lint_name_raw()
240     }
241 }
242
243 // Duplicated from rustc_session::config::ExternDepSpec to avoid cyclic dependency
244 #[derive(PartialEq)]
245 pub enum ExternDepSpec {
246     Json(Json),
247     Raw(String),
248 }
249
250 // This could be a closure, but then implementing derive trait
251 // becomes hacky (and it gets allocated).
252 #[derive(PartialEq)]
253 pub enum BuiltinLintDiagnostics {
254     Normal,
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),
270     OrPatternsBackCompat(Span, String),
271 }
272
273 /// Lints that are buffered up early on in the `Session` before the
274 /// `LintLevels` is calculated.
275 #[derive(PartialEq)]
276 pub struct BufferedEarlyLint {
277     /// The span of code that we are linting on.
278     pub span: MultiSpan,
279
280     /// The lint message.
281     pub msg: String,
282
283     /// The `NodeId` of the AST node that generated the lint.
284     pub node_id: NodeId,
285
286     /// A lint Id that can be passed to
287     /// `rustc_lint::early::EarlyContextAndPass::check_id`.
288     pub lint_id: LintId,
289
290     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
291     pub diagnostic: BuiltinLintDiagnostics,
292 }
293
294 #[derive(Default)]
295 pub struct LintBuffer {
296     pub map: NodeMap<Vec<BufferedEarlyLint>>,
297 }
298
299 impl LintBuffer {
300     pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
301         let arr = self.map.entry(early_lint.node_id).or_default();
302         if !arr.contains(&early_lint) {
303             arr.push(early_lint);
304         }
305     }
306
307     pub fn add_lint(
308         &mut self,
309         lint: &'static Lint,
310         node_id: NodeId,
311         span: MultiSpan,
312         msg: &str,
313         diagnostic: BuiltinLintDiagnostics,
314     ) {
315         let lint_id = LintId::of(lint);
316         let msg = msg.to_string();
317         self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
318     }
319
320     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
321         self.map.remove(&id).unwrap_or_default()
322     }
323
324     pub fn buffer_lint(
325         &mut self,
326         lint: &'static Lint,
327         id: NodeId,
328         sp: impl Into<MultiSpan>,
329         msg: &str,
330     ) {
331         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
332     }
333
334     pub fn buffer_lint_with_diagnostic(
335         &mut self,
336         lint: &'static Lint,
337         id: NodeId,
338         sp: impl Into<MultiSpan>,
339         msg: &str,
340         diagnostic: BuiltinLintDiagnostics,
341     ) {
342         self.add_lint(lint, id, sp.into(), msg, diagnostic)
343     }
344 }
345
346 /// Declares a static item of type `&'static Lint`.
347 ///
348 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
349 /// documentation and guidelines on writing lints.
350 ///
351 /// The macro call should start with a doc comment explaining the lint
352 /// which will be embedded in the rustc user documentation book. It should
353 /// be written in markdown and have a format that looks like this:
354 ///
355 /// ```rust,ignore (doc-example)
356 /// /// The `my_lint_name` lint detects [short explanation here].
357 /// ///
358 /// /// ### Example
359 /// ///
360 /// /// ```rust
361 /// /// [insert a concise example that triggers the lint]
362 /// /// ```
363 /// ///
364 /// /// {{produces}}
365 /// ///
366 /// /// ### Explanation
367 /// ///
368 /// /// This should be a detailed explanation of *why* the lint exists,
369 /// /// and also include suggestions on how the user should fix the problem.
370 /// /// Try to keep the text simple enough that a beginner can understand,
371 /// /// and include links to other documentation for terminology that a
372 /// /// beginner may not be familiar with. If this is "allow" by default,
373 /// /// it should explain why (are there false positives or other issues?). If
374 /// /// this is a future-incompatible lint, it should say so, with text that
375 /// /// looks roughly like this:
376 /// ///
377 /// /// This is a [future-incompatible] lint to transition this to a hard
378 /// /// error in the future. See [issue #xxxxx] for more details.
379 /// ///
380 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
381 /// ```
382 ///
383 /// The `{{produces}}` tag will be automatically replaced with the output from
384 /// the example by the build system. If the lint example is too complex to run
385 /// as a simple example (for example, it needs an extern crate), mark the code
386 /// block with `ignore` and manually replace the `{{produces}}` line with the
387 /// expected output in a `text` code block.
388 ///
389 /// If this is a rustdoc-only lint, then only include a brief introduction
390 /// with a link with the text `[rustdoc book]` so that the validator knows
391 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
392 ///
393 /// Commands to view and test the documentation:
394 ///
395 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
396 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
397 ///   correct style, and that the code example actually emits the expected
398 ///   lint.
399 ///
400 /// If you have already built the compiler, and you want to make changes to
401 /// just the doc comments, then use the `--keep-stage=0` flag with the above
402 /// commands to avoid rebuilding the compiler.
403 #[macro_export]
404 macro_rules! declare_lint {
405     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
406         $crate::declare_lint!(
407             $(#[$attr])* $vis $NAME, $Level, $desc,
408         );
409     );
410     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
411      $(@feature_gate = $gate:expr;)?
412      $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)*  }; )?
413      $($v:ident),*) => (
414         $(#[$attr])*
415         $vis static $NAME: &$crate::Lint = &$crate::Lint {
416             name: stringify!($NAME),
417             default_level: $crate::$Level,
418             desc: $desc,
419             edition_lint_opts: None,
420             is_plugin: false,
421             $($v: true,)*
422             $(feature_gate: Some($gate),)*
423             $(future_incompatible: Some($crate::FutureIncompatibleInfo {
424                 $($field: $val,)*
425                 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
426             }),)*
427             ..$crate::Lint::default_fields_for_macro()
428         };
429     );
430     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
431      $lint_edition: expr => $edition_level: ident
432     ) => (
433         $(#[$attr])*
434         $vis static $NAME: &$crate::Lint = &$crate::Lint {
435             name: stringify!($NAME),
436             default_level: $crate::$Level,
437             desc: $desc,
438             edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
439             report_in_external_macro: false,
440             is_plugin: false,
441         };
442     );
443 }
444
445 #[macro_export]
446 macro_rules! declare_tool_lint {
447     (
448         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
449     ) => (
450         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
451     );
452     (
453         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
454         report_in_external_macro: $rep:expr
455     ) => (
456          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
457     );
458     (
459         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
460         $external:expr
461     ) => (
462         $(#[$attr])*
463         $vis static $NAME: &$crate::Lint = &$crate::Lint {
464             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
465             default_level: $crate::$Level,
466             desc: $desc,
467             edition_lint_opts: None,
468             report_in_external_macro: $external,
469             future_incompatible: None,
470             is_plugin: true,
471             feature_gate: None,
472             crate_level_only: false,
473         };
474     );
475 }
476
477 /// Declares a static `LintArray` and return it as an expression.
478 #[macro_export]
479 macro_rules! lint_array {
480     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
481     ($( $lint:expr ),*) => {{
482         vec![$($lint),*]
483     }}
484 }
485
486 pub type LintArray = Vec<&'static Lint>;
487
488 pub trait LintPass {
489     fn name(&self) -> &'static str;
490 }
491
492 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
493 #[macro_export]
494 macro_rules! impl_lint_pass {
495     ($ty:ty => [$($lint:expr),* $(,)?]) => {
496         impl $crate::LintPass for $ty {
497             fn name(&self) -> &'static str { stringify!($ty) }
498         }
499         impl $ty {
500             pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
501         }
502     };
503 }
504
505 /// Declares a type named `$name` which implements `LintPass`.
506 /// To the right of `=>` a comma separated list of `Lint` statics is given.
507 #[macro_export]
508 macro_rules! declare_lint_pass {
509     ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
510         $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
511         $crate::impl_lint_pass!($name => [$($lint),*]);
512     };
513 }