]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint_defs/src/lib.rs
b3d98747dcfa2cd60362ed3bae7ae6e0bd608ab3
[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     /// The reason for the lint used by diagnostics to provide
146     /// the right help message
147     pub reason: FutureIncompatibilityReason,
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 /// The reason for future incompatibility
155 #[derive(Copy, Clone, Debug)]
156 pub enum FutureIncompatibilityReason {
157     /// This will be an error in a future release
158     /// for all editions
159     FutureReleaseError,
160     /// Previously accepted code that will become an
161     /// error in the provided edition
162     EditionError(Edition),
163     /// Code that changes meaning in some way in
164     /// the provided edition
165     EditionSemanticsChange(Edition),
166 }
167
168 impl FutureIncompatibilityReason {
169     pub fn edition(self) -> Option<Edition> {
170         match self {
171             Self::EditionError(e) => Some(e),
172             Self::EditionSemanticsChange(e) => Some(e),
173             _ => None,
174         }
175     }
176 }
177
178 #[derive(Copy, Clone, Debug)]
179 pub struct FutureBreakage {
180     pub date: Option<&'static str>,
181 }
182
183 impl FutureIncompatibleInfo {
184     pub const fn default_fields_for_macro() -> Self {
185         FutureIncompatibleInfo {
186             reference: "",
187             reason: FutureIncompatibilityReason::FutureReleaseError,
188             future_breakage: None,
189         }
190     }
191 }
192
193 impl Lint {
194     pub const fn default_fields_for_macro() -> Self {
195         Lint {
196             name: "",
197             default_level: Level::Forbid,
198             desc: "",
199             edition_lint_opts: None,
200             is_plugin: false,
201             report_in_external_macro: false,
202             future_incompatible: None,
203             feature_gate: None,
204             crate_level_only: false,
205         }
206     }
207
208     /// Gets the lint's name, with ASCII letters converted to lowercase.
209     pub fn name_lower(&self) -> String {
210         self.name.to_ascii_lowercase()
211     }
212
213     pub fn default_level(&self, edition: Edition) -> Level {
214         self.edition_lint_opts
215             .filter(|(e, _)| *e <= edition)
216             .map(|(_, l)| l)
217             .unwrap_or(self.default_level)
218     }
219 }
220
221 /// Identifies a lint known to the compiler.
222 #[derive(Clone, Copy, Debug)]
223 pub struct LintId {
224     // Identity is based on pointer equality of this field.
225     pub lint: &'static Lint,
226 }
227
228 impl PartialEq for LintId {
229     fn eq(&self, other: &LintId) -> bool {
230         std::ptr::eq(self.lint, other.lint)
231     }
232 }
233
234 impl Eq for LintId {}
235
236 impl std::hash::Hash for LintId {
237     fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
238         let ptr = self.lint as *const Lint;
239         ptr.hash(state);
240     }
241 }
242
243 impl LintId {
244     /// Gets the `LintId` for a `Lint`.
245     pub fn of(lint: &'static Lint) -> LintId {
246         LintId { lint }
247     }
248
249     pub fn lint_name_raw(&self) -> &'static str {
250         self.lint.name
251     }
252
253     /// Gets the name of the lint.
254     pub fn to_string(&self) -> String {
255         self.lint.name_lower()
256     }
257 }
258
259 impl<HCX> HashStable<HCX> for LintId {
260     #[inline]
261     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
262         self.lint_name_raw().hash_stable(hcx, hasher);
263     }
264 }
265
266 impl<HCX> ToStableHashKey<HCX> for LintId {
267     type KeyType = &'static str;
268
269     #[inline]
270     fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
271         self.lint_name_raw()
272     }
273 }
274
275 // Duplicated from rustc_session::config::ExternDepSpec to avoid cyclic dependency
276 #[derive(PartialEq)]
277 pub enum ExternDepSpec {
278     Json(Json),
279     Raw(String),
280 }
281
282 // This could be a closure, but then implementing derive trait
283 // becomes hacky (and it gets allocated).
284 #[derive(PartialEq)]
285 pub enum BuiltinLintDiagnostics {
286     Normal,
287     BareTraitObject(Span, /* is_global */ bool),
288     AbsPathWithModule(Span),
289     ProcMacroDeriveResolutionFallback(Span),
290     MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
291     ElidedLifetimesInPaths(usize, Span, bool, Span, String),
292     UnknownCrateTypes(Span, String, String),
293     UnusedImports(String, Vec<(Span, String)>),
294     RedundantImport(Vec<(Span, bool)>, Ident),
295     DeprecatedMacro(Option<Symbol>, Span),
296     MissingAbi(Span, Abi),
297     UnusedDocComment(Span),
298     PatternsInFnsWithoutBody(Span, Ident),
299     LegacyDeriveHelpers(Span),
300     ExternDepSpec(String, ExternDepSpec),
301     ProcMacroBackCompat(String),
302     OrPatternsBackCompat(Span, String),
303 }
304
305 /// Lints that are buffered up early on in the `Session` before the
306 /// `LintLevels` is calculated.
307 #[derive(PartialEq)]
308 pub struct BufferedEarlyLint {
309     /// The span of code that we are linting on.
310     pub span: MultiSpan,
311
312     /// The lint message.
313     pub msg: String,
314
315     /// The `NodeId` of the AST node that generated the lint.
316     pub node_id: NodeId,
317
318     /// A lint Id that can be passed to
319     /// `rustc_lint::early::EarlyContextAndPass::check_id`.
320     pub lint_id: LintId,
321
322     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
323     pub diagnostic: BuiltinLintDiagnostics,
324 }
325
326 #[derive(Default)]
327 pub struct LintBuffer {
328     pub map: NodeMap<Vec<BufferedEarlyLint>>,
329 }
330
331 impl LintBuffer {
332     pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
333         let arr = self.map.entry(early_lint.node_id).or_default();
334         if !arr.contains(&early_lint) {
335             arr.push(early_lint);
336         }
337     }
338
339     pub fn add_lint(
340         &mut self,
341         lint: &'static Lint,
342         node_id: NodeId,
343         span: MultiSpan,
344         msg: &str,
345         diagnostic: BuiltinLintDiagnostics,
346     ) {
347         let lint_id = LintId::of(lint);
348         let msg = msg.to_string();
349         self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
350     }
351
352     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
353         self.map.remove(&id).unwrap_or_default()
354     }
355
356     pub fn buffer_lint(
357         &mut self,
358         lint: &'static Lint,
359         id: NodeId,
360         sp: impl Into<MultiSpan>,
361         msg: &str,
362     ) {
363         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
364     }
365
366     pub fn buffer_lint_with_diagnostic(
367         &mut self,
368         lint: &'static Lint,
369         id: NodeId,
370         sp: impl Into<MultiSpan>,
371         msg: &str,
372         diagnostic: BuiltinLintDiagnostics,
373     ) {
374         self.add_lint(lint, id, sp.into(), msg, diagnostic)
375     }
376 }
377
378 /// Declares a static item of type `&'static Lint`.
379 ///
380 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
381 /// documentation and guidelines on writing lints.
382 ///
383 /// The macro call should start with a doc comment explaining the lint
384 /// which will be embedded in the rustc user documentation book. It should
385 /// be written in markdown and have a format that looks like this:
386 ///
387 /// ```rust,ignore (doc-example)
388 /// /// The `my_lint_name` lint detects [short explanation here].
389 /// ///
390 /// /// ### Example
391 /// ///
392 /// /// ```rust
393 /// /// [insert a concise example that triggers the lint]
394 /// /// ```
395 /// ///
396 /// /// {{produces}}
397 /// ///
398 /// /// ### Explanation
399 /// ///
400 /// /// This should be a detailed explanation of *why* the lint exists,
401 /// /// and also include suggestions on how the user should fix the problem.
402 /// /// Try to keep the text simple enough that a beginner can understand,
403 /// /// and include links to other documentation for terminology that a
404 /// /// beginner may not be familiar with. If this is "allow" by default,
405 /// /// it should explain why (are there false positives or other issues?). If
406 /// /// this is a future-incompatible lint, it should say so, with text that
407 /// /// looks roughly like this:
408 /// ///
409 /// /// This is a [future-incompatible] lint to transition this to a hard
410 /// /// error in the future. See [issue #xxxxx] for more details.
411 /// ///
412 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
413 /// ```
414 ///
415 /// The `{{produces}}` tag will be automatically replaced with the output from
416 /// the example by the build system. If the lint example is too complex to run
417 /// as a simple example (for example, it needs an extern crate), mark the code
418 /// block with `ignore` and manually replace the `{{produces}}` line with the
419 /// expected output in a `text` code block.
420 ///
421 /// If this is a rustdoc-only lint, then only include a brief introduction
422 /// with a link with the text `[rustdoc book]` so that the validator knows
423 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
424 ///
425 /// Commands to view and test the documentation:
426 ///
427 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
428 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
429 ///   correct style, and that the code example actually emits the expected
430 ///   lint.
431 ///
432 /// If you have already built the compiler, and you want to make changes to
433 /// just the doc comments, then use the `--keep-stage=0` flag with the above
434 /// commands to avoid rebuilding the compiler.
435 #[macro_export]
436 macro_rules! declare_lint {
437     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
438         $crate::declare_lint!(
439             $(#[$attr])* $vis $NAME, $Level, $desc,
440         );
441     );
442     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
443      $(@feature_gate = $gate:expr;)?
444      $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)*  }; )?
445      $($v:ident),*) => (
446         $(#[$attr])*
447         $vis static $NAME: &$crate::Lint = &$crate::Lint {
448             name: stringify!($NAME),
449             default_level: $crate::$Level,
450             desc: $desc,
451             edition_lint_opts: None,
452             is_plugin: false,
453             $($v: true,)*
454             $(feature_gate: Some($gate),)*
455             $(future_incompatible: Some($crate::FutureIncompatibleInfo {
456                 $($field: $val,)*
457                 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
458             }),)*
459             ..$crate::Lint::default_fields_for_macro()
460         };
461     );
462     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
463      $lint_edition: expr => $edition_level: ident
464     ) => (
465         $(#[$attr])*
466         $vis static $NAME: &$crate::Lint = &$crate::Lint {
467             name: stringify!($NAME),
468             default_level: $crate::$Level,
469             desc: $desc,
470             edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
471             report_in_external_macro: false,
472             is_plugin: false,
473         };
474     );
475 }
476
477 #[macro_export]
478 macro_rules! declare_tool_lint {
479     (
480         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
481     ) => (
482         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
483     );
484     (
485         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
486         report_in_external_macro: $rep:expr
487     ) => (
488          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
489     );
490     (
491         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
492         $external:expr
493     ) => (
494         $(#[$attr])*
495         $vis static $NAME: &$crate::Lint = &$crate::Lint {
496             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
497             default_level: $crate::$Level,
498             desc: $desc,
499             edition_lint_opts: None,
500             report_in_external_macro: $external,
501             future_incompatible: None,
502             is_plugin: true,
503             feature_gate: None,
504             crate_level_only: false,
505         };
506     );
507 }
508
509 /// Declares a static `LintArray` and return it as an expression.
510 #[macro_export]
511 macro_rules! lint_array {
512     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
513     ($( $lint:expr ),*) => {{
514         vec![$($lint),*]
515     }}
516 }
517
518 pub type LintArray = Vec<&'static Lint>;
519
520 pub trait LintPass {
521     fn name(&self) -> &'static str;
522 }
523
524 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
525 #[macro_export]
526 macro_rules! impl_lint_pass {
527     ($ty:ty => [$($lint:expr),* $(,)?]) => {
528         impl $crate::LintPass for $ty {
529             fn name(&self) -> &'static str { stringify!($ty) }
530         }
531         impl $ty {
532             pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
533         }
534     };
535 }
536
537 /// Declares a type named `$name` which implements `LintPass`.
538 /// To the right of `=>` a comma separated list of `Lint` statics is given.
539 #[macro_export]
540 macro_rules! declare_lint_pass {
541     ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
542         $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
543         $crate::impl_lint_pass!($name => [$($lint),*]);
544     };
545 }