]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint_defs/src/lib.rs
Rollup merge of #81466 - sasurau4:fix/enhance-sugget-mut-method-for-loop, r=oli-obk
[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 }
270
271 /// Lints that are buffered up early on in the `Session` before the
272 /// `LintLevels` is calculated.
273 #[derive(PartialEq)]
274 pub struct BufferedEarlyLint {
275     /// The span of code that we are linting on.
276     pub span: MultiSpan,
277
278     /// The lint message.
279     pub msg: String,
280
281     /// The `NodeId` of the AST node that generated the lint.
282     pub node_id: NodeId,
283
284     /// A lint Id that can be passed to
285     /// `rustc_lint::early::EarlyContextAndPass::check_id`.
286     pub lint_id: LintId,
287
288     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
289     pub diagnostic: BuiltinLintDiagnostics,
290 }
291
292 #[derive(Default)]
293 pub struct LintBuffer {
294     pub map: NodeMap<Vec<BufferedEarlyLint>>,
295 }
296
297 impl LintBuffer {
298     pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
299         let arr = self.map.entry(early_lint.node_id).or_default();
300         if !arr.contains(&early_lint) {
301             arr.push(early_lint);
302         }
303     }
304
305     pub fn add_lint(
306         &mut self,
307         lint: &'static Lint,
308         node_id: NodeId,
309         span: MultiSpan,
310         msg: &str,
311         diagnostic: BuiltinLintDiagnostics,
312     ) {
313         let lint_id = LintId::of(lint);
314         let msg = msg.to_string();
315         self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
316     }
317
318     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
319         self.map.remove(&id).unwrap_or_default()
320     }
321
322     pub fn buffer_lint(
323         &mut self,
324         lint: &'static Lint,
325         id: NodeId,
326         sp: impl Into<MultiSpan>,
327         msg: &str,
328     ) {
329         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
330     }
331
332     pub fn buffer_lint_with_diagnostic(
333         &mut self,
334         lint: &'static Lint,
335         id: NodeId,
336         sp: impl Into<MultiSpan>,
337         msg: &str,
338         diagnostic: BuiltinLintDiagnostics,
339     ) {
340         self.add_lint(lint, id, sp.into(), msg, diagnostic)
341     }
342 }
343
344 /// Declares a static item of type `&'static Lint`.
345 ///
346 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
347 /// documentation and guidelines on writing lints.
348 ///
349 /// The macro call should start with a doc comment explaining the lint
350 /// which will be embedded in the rustc user documentation book. It should
351 /// be written in markdown and have a format that looks like this:
352 ///
353 /// ```rust,ignore (doc-example)
354 /// /// The `my_lint_name` lint detects [short explanation here].
355 /// ///
356 /// /// ### Example
357 /// ///
358 /// /// ```rust
359 /// /// [insert a concise example that triggers the lint]
360 /// /// ```
361 /// ///
362 /// /// {{produces}}
363 /// ///
364 /// /// ### Explanation
365 /// ///
366 /// /// This should be a detailed explanation of *why* the lint exists,
367 /// /// and also include suggestions on how the user should fix the problem.
368 /// /// Try to keep the text simple enough that a beginner can understand,
369 /// /// and include links to other documentation for terminology that a
370 /// /// beginner may not be familiar with. If this is "allow" by default,
371 /// /// it should explain why (are there false positives or other issues?). If
372 /// /// this is a future-incompatible lint, it should say so, with text that
373 /// /// looks roughly like this:
374 /// ///
375 /// /// This is a [future-incompatible] lint to transition this to a hard
376 /// /// error in the future. See [issue #xxxxx] for more details.
377 /// ///
378 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
379 /// ```
380 ///
381 /// The `{{produces}}` tag will be automatically replaced with the output from
382 /// the example by the build system. If the lint example is too complex to run
383 /// as a simple example (for example, it needs an extern crate), mark the code
384 /// block with `ignore` and manually replace the `{{produces}}` line with the
385 /// expected output in a `text` code block.
386 ///
387 /// If this is a rustdoc-only lint, then only include a brief introduction
388 /// with a link with the text `[rustdoc book]` so that the validator knows
389 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
390 ///
391 /// Commands to view and test the documentation:
392 ///
393 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
394 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
395 ///   correct style, and that the code example actually emits the expected
396 ///   lint.
397 ///
398 /// If you have already built the compiler, and you want to make changes to
399 /// just the doc comments, then use the `--keep-stage=0` flag with the above
400 /// commands to avoid rebuilding the compiler.
401 #[macro_export]
402 macro_rules! declare_lint {
403     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
404         $crate::declare_lint!(
405             $(#[$attr])* $vis $NAME, $Level, $desc,
406         );
407     );
408     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
409      $(@feature_gate = $gate:expr;)?
410      $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)*  }; )?
411      $($v:ident),*) => (
412         $(#[$attr])*
413         $vis static $NAME: &$crate::Lint = &$crate::Lint {
414             name: stringify!($NAME),
415             default_level: $crate::$Level,
416             desc: $desc,
417             edition_lint_opts: None,
418             is_plugin: false,
419             $($v: true,)*
420             $(feature_gate: Some($gate),)*
421             $(future_incompatible: Some($crate::FutureIncompatibleInfo {
422                 $($field: $val,)*
423                 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
424             }),)*
425             ..$crate::Lint::default_fields_for_macro()
426         };
427     );
428     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
429      $lint_edition: expr => $edition_level: ident
430     ) => (
431         $(#[$attr])*
432         $vis static $NAME: &$crate::Lint = &$crate::Lint {
433             name: stringify!($NAME),
434             default_level: $crate::$Level,
435             desc: $desc,
436             edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
437             report_in_external_macro: false,
438             is_plugin: false,
439         };
440     );
441 }
442
443 #[macro_export]
444 macro_rules! declare_tool_lint {
445     (
446         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
447     ) => (
448         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
449     );
450     (
451         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
452         report_in_external_macro: $rep:expr
453     ) => (
454          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
455     );
456     (
457         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
458         $external:expr
459     ) => (
460         $(#[$attr])*
461         $vis static $NAME: &$crate::Lint = &$crate::Lint {
462             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
463             default_level: $crate::$Level,
464             desc: $desc,
465             edition_lint_opts: None,
466             report_in_external_macro: $external,
467             future_incompatible: None,
468             is_plugin: true,
469             feature_gate: None,
470             crate_level_only: false,
471         };
472     );
473 }
474
475 /// Declares a static `LintArray` and return it as an expression.
476 #[macro_export]
477 macro_rules! lint_array {
478     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
479     ($( $lint:expr ),*) => {{
480         vec![$($lint),*]
481     }}
482 }
483
484 pub type LintArray = Vec<&'static Lint>;
485
486 pub trait LintPass {
487     fn name(&self) -> &'static str;
488 }
489
490 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
491 #[macro_export]
492 macro_rules! impl_lint_pass {
493     ($ty:ty => [$($lint:expr),* $(,)?]) => {
494         impl $crate::LintPass for $ty {
495             fn name(&self) -> &'static str { stringify!($ty) }
496         }
497         impl $ty {
498             pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
499         }
500     };
501 }
502
503 /// Declares a type named `$name` which implements `LintPass`.
504 /// To the right of `=>` a comma separated list of `Lint` statics is given.
505 #[macro_export]
506 macro_rules! declare_lint_pass {
507     ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
508         $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
509         $crate::impl_lint_pass!($name => [$($lint),*]);
510     };
511 }