]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint_defs/src/lib.rs
Auto merge of #81728 - Qwaz:fix-80335, r=joshtriplett
[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 }
271
272 /// Lints that are buffered up early on in the `Session` before the
273 /// `LintLevels` is calculated.
274 #[derive(PartialEq)]
275 pub struct BufferedEarlyLint {
276     /// The span of code that we are linting on.
277     pub span: MultiSpan,
278
279     /// The lint message.
280     pub msg: String,
281
282     /// The `NodeId` of the AST node that generated the lint.
283     pub node_id: NodeId,
284
285     /// A lint Id that can be passed to
286     /// `rustc_lint::early::EarlyContextAndPass::check_id`.
287     pub lint_id: LintId,
288
289     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
290     pub diagnostic: BuiltinLintDiagnostics,
291 }
292
293 #[derive(Default)]
294 pub struct LintBuffer {
295     pub map: NodeMap<Vec<BufferedEarlyLint>>,
296 }
297
298 impl LintBuffer {
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);
303         }
304     }
305
306     pub fn add_lint(
307         &mut self,
308         lint: &'static Lint,
309         node_id: NodeId,
310         span: MultiSpan,
311         msg: &str,
312         diagnostic: BuiltinLintDiagnostics,
313     ) {
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 });
317     }
318
319     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
320         self.map.remove(&id).unwrap_or_default()
321     }
322
323     pub fn buffer_lint(
324         &mut self,
325         lint: &'static Lint,
326         id: NodeId,
327         sp: impl Into<MultiSpan>,
328         msg: &str,
329     ) {
330         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
331     }
332
333     pub fn buffer_lint_with_diagnostic(
334         &mut self,
335         lint: &'static Lint,
336         id: NodeId,
337         sp: impl Into<MultiSpan>,
338         msg: &str,
339         diagnostic: BuiltinLintDiagnostics,
340     ) {
341         self.add_lint(lint, id, sp.into(), msg, diagnostic)
342     }
343 }
344
345 /// Declares a static item of type `&'static Lint`.
346 ///
347 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
348 /// documentation and guidelines on writing lints.
349 ///
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:
353 ///
354 /// ```rust,ignore (doc-example)
355 /// /// The `my_lint_name` lint detects [short explanation here].
356 /// ///
357 /// /// ### Example
358 /// ///
359 /// /// ```rust
360 /// /// [insert a concise example that triggers the lint]
361 /// /// ```
362 /// ///
363 /// /// {{produces}}
364 /// ///
365 /// /// ### Explanation
366 /// ///
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:
375 /// ///
376 /// /// This is a [future-incompatible] lint to transition this to a hard
377 /// /// error in the future. See [issue #xxxxx] for more details.
378 /// ///
379 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
380 /// ```
381 ///
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.
387 ///
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).
391 ///
392 /// Commands to view and test the documentation:
393 ///
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
397 ///   lint.
398 ///
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.
402 #[macro_export]
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,
407         );
408     );
409     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
410      $(@feature_gate = $gate:expr;)?
411      $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)*  }; )?
412      $($v:ident),*) => (
413         $(#[$attr])*
414         $vis static $NAME: &$crate::Lint = &$crate::Lint {
415             name: stringify!($NAME),
416             default_level: $crate::$Level,
417             desc: $desc,
418             edition_lint_opts: None,
419             is_plugin: false,
420             $($v: true,)*
421             $(feature_gate: Some($gate),)*
422             $(future_incompatible: Some($crate::FutureIncompatibleInfo {
423                 $($field: $val,)*
424                 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
425             }),)*
426             ..$crate::Lint::default_fields_for_macro()
427         };
428     );
429     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
430      $lint_edition: expr => $edition_level: ident
431     ) => (
432         $(#[$attr])*
433         $vis static $NAME: &$crate::Lint = &$crate::Lint {
434             name: stringify!($NAME),
435             default_level: $crate::$Level,
436             desc: $desc,
437             edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
438             report_in_external_macro: false,
439             is_plugin: false,
440         };
441     );
442 }
443
444 #[macro_export]
445 macro_rules! declare_tool_lint {
446     (
447         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
448     ) => (
449         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
450     );
451     (
452         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
453         report_in_external_macro: $rep:expr
454     ) => (
455          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
456     );
457     (
458         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
459         $external:expr
460     ) => (
461         $(#[$attr])*
462         $vis static $NAME: &$crate::Lint = &$crate::Lint {
463             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
464             default_level: $crate::$Level,
465             desc: $desc,
466             edition_lint_opts: None,
467             report_in_external_macro: $external,
468             future_incompatible: None,
469             is_plugin: true,
470             feature_gate: None,
471             crate_level_only: false,
472         };
473     );
474 }
475
476 /// Declares a static `LintArray` and return it as an expression.
477 #[macro_export]
478 macro_rules! lint_array {
479     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
480     ($( $lint:expr ),*) => {{
481         vec![$($lint),*]
482     }}
483 }
484
485 pub type LintArray = Vec<&'static Lint>;
486
487 pub trait LintPass {
488     fn name(&self) -> &'static str;
489 }
490
491 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
492 #[macro_export]
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) }
497         }
498         impl $ty {
499             pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
500         }
501     };
502 }
503
504 /// Declares a type named `$name` which implements `LintPass`.
505 /// To the right of `=>` a comma separated list of `Lint` statics is given.
506 #[macro_export]
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),*]);
511     };
512 }