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