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