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