]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint_defs/src/lib.rs
Rollup merge of #103702 - WaffleLapkin:lift-sized-bounds-from-pointer-methods-where...
[rust.git] / compiler / rustc_lint_defs / src / lib.rs
1 #![feature(min_specialization)]
2 #![deny(rustc::untranslatable_diagnostic)]
3 #![deny(rustc::diagnostic_outside_of_impl)]
4
5 #[macro_use]
6 extern crate rustc_macros;
7
8 pub use self::Level::*;
9 use rustc_ast::node_id::{NodeId, NodeMap};
10 use rustc_ast::{AttrId, Attribute};
11 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
12 use rustc_error_messages::{DiagnosticMessage, MultiSpan};
13 use rustc_hir::HashStableContext;
14 use rustc_hir::HirId;
15 use rustc_span::edition::Edition;
16 use rustc_span::{sym, symbol::Ident, Span, Symbol};
17 use rustc_target::spec::abi::Abi;
18
19 use serde::{Deserialize, Serialize};
20
21 pub mod builtin;
22
23 #[macro_export]
24 macro_rules! pluralize {
25     ($x:expr) => {
26         if $x != 1 { "s" } else { "" }
27     };
28     ("has", $x:expr) => {
29         if $x == 1 { "has" } else { "have" }
30     };
31     ("is", $x:expr) => {
32         if $x == 1 { "is" } else { "are" }
33     };
34     ("was", $x:expr) => {
35         if $x == 1 { "was" } else { "were" }
36     };
37     ("this", $x:expr) => {
38         if $x == 1 { "this" } else { "these" }
39     };
40 }
41
42 /// Indicates the confidence in the correctness of a suggestion.
43 ///
44 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
45 /// to determine whether it should be automatically applied or if the user should be consulted
46 /// before applying the suggestion.
47 #[derive(Copy, Clone, Debug, Hash, Encodable, Decodable, Serialize, Deserialize)]
48 #[derive(PartialEq, Eq, PartialOrd, Ord)]
49 pub enum Applicability {
50     /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
51     /// This suggestion should be automatically applied.
52     ///
53     /// In case of multiple `MachineApplicable` suggestions (whether as part of
54     /// the same `multipart_suggestion` or not), all of them should be
55     /// automatically applied.
56     MachineApplicable,
57
58     /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
59     /// result in valid Rust code if it is applied.
60     MaybeIncorrect,
61
62     /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
63     /// cannot be applied automatically because it will not result in valid Rust code. The user
64     /// will need to fill in the placeholders.
65     HasPlaceholders,
66
67     /// The applicability of the suggestion is unknown.
68     Unspecified,
69 }
70
71 /// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
72 /// Expected `Diagnostic`s get the lint level `Expect` which stores the `LintExpectationId`
73 /// to match it with the actual expectation later on.
74 ///
75 /// The `LintExpectationId` has to be stable between compilations, as diagnostic
76 /// instances might be loaded from cache. Lint messages can be emitted during an
77 /// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
78 /// HIR tree. The AST doesn't have enough information to create a stable id. The
79 /// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
80 /// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
81 /// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
82 ///
83 /// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
84 /// identifies the lint inside the attribute and ensures that the IDs are unique.
85 ///
86 /// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
87 /// It's reasonable to assume that no user will define 2^16 attributes on one node or
88 /// have that amount of lints listed. `u16` values should therefore suffice.
89 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Encodable, Decodable)]
90 pub enum LintExpectationId {
91     /// Used for lints emitted during the `EarlyLintPass`. This id is not
92     /// hash stable and should not be cached.
93     Unstable { attr_id: AttrId, lint_index: Option<u16> },
94     /// The [`HirId`] that the lint expectation is attached to. This id is
95     /// stable and can be cached. The additional index ensures that nodes with
96     /// several expectations can correctly match diagnostics to the individual
97     /// expectation.
98     Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16>, attr_id: Option<AttrId> },
99 }
100
101 impl LintExpectationId {
102     pub fn is_stable(&self) -> bool {
103         match self {
104             LintExpectationId::Unstable { .. } => false,
105             LintExpectationId::Stable { .. } => true,
106         }
107     }
108
109     pub fn get_lint_index(&self) -> Option<u16> {
110         let (LintExpectationId::Unstable { lint_index, .. }
111         | LintExpectationId::Stable { lint_index, .. }) = self;
112
113         *lint_index
114     }
115
116     pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
117         let (LintExpectationId::Unstable { ref mut lint_index, .. }
118         | LintExpectationId::Stable { ref mut lint_index, .. }) = self;
119
120         *lint_index = new_lint_index
121     }
122
123     /// Prepares the id for hashing. Removes references to the ast.
124     /// Should only be called when the id is stable.
125     pub fn normalize(self) -> Self {
126         match self {
127             Self::Stable { hir_id, attr_index, lint_index, .. } => {
128                 Self::Stable { hir_id, attr_index, lint_index, attr_id: None }
129             }
130             Self::Unstable { .. } => {
131                 unreachable!("`normalize` called when `ExpectationId` is unstable")
132             }
133         }
134     }
135 }
136
137 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId {
138     #[inline]
139     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
140         match self {
141             LintExpectationId::Stable {
142                 hir_id,
143                 attr_index,
144                 lint_index: Some(lint_index),
145                 attr_id: _,
146             } => {
147                 hir_id.hash_stable(hcx, hasher);
148                 attr_index.hash_stable(hcx, hasher);
149                 lint_index.hash_stable(hcx, hasher);
150             }
151             _ => {
152                 unreachable!(
153                     "HashStable should only be called for filled and stable `LintExpectationId`"
154                 )
155             }
156         }
157     }
158 }
159
160 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
161     type KeyType = (HirId, u16, u16);
162
163     #[inline]
164     fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
165         match self {
166             LintExpectationId::Stable {
167                 hir_id,
168                 attr_index,
169                 lint_index: Some(lint_index),
170                 attr_id: _,
171             } => (*hir_id, *attr_index, *lint_index),
172             _ => {
173                 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
174             }
175         }
176     }
177 }
178
179 /// Setting for how to handle a lint.
180 ///
181 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
182 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, HashStable_Generic)]
183 pub enum Level {
184     /// The `allow` level will not issue any message.
185     Allow,
186     /// The `expect` level will suppress the lint message but in turn produce a message
187     /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
188     /// an initial level for a lint.
189     ///
190     /// Note that this still means that the lint is enabled in this position and should
191     /// be emitted, this will in turn fulfill the expectation and suppress the lint.
192     ///
193     /// See RFC 2383.
194     ///
195     /// The [`LintExpectationId`] is used to later link a lint emission to the actual
196     /// expectation. It can be ignored in most cases.
197     Expect(LintExpectationId),
198     /// The `warn` level will produce a warning if the lint was violated, however the
199     /// compiler will continue with its execution.
200     Warn,
201     /// This lint level is a special case of [`Warn`], that can't be overridden. This is used
202     /// to ensure that a lint can't be suppressed. This lint level can currently only be set
203     /// via the console and is therefore session specific.
204     ///
205     /// The [`LintExpectationId`] is intended to fulfill expectations marked via the
206     /// `#[expect]` attribute, that will still be suppressed due to the level.
207     ForceWarn(Option<LintExpectationId>),
208     /// The `deny` level will produce an error and stop further execution after the lint
209     /// pass is complete.
210     Deny,
211     /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
212     /// levels.
213     Forbid,
214 }
215
216 impl Level {
217     /// Converts a level to a lower-case string.
218     pub fn as_str(self) -> &'static str {
219         match self {
220             Level::Allow => "allow",
221             Level::Expect(_) => "expect",
222             Level::Warn => "warn",
223             Level::ForceWarn(_) => "force-warn",
224             Level::Deny => "deny",
225             Level::Forbid => "forbid",
226         }
227     }
228
229     /// Converts a lower-case string to a level. This will never construct the expect
230     /// level as that would require a [`LintExpectationId`]
231     pub fn from_str(x: &str) -> Option<Level> {
232         match x {
233             "allow" => Some(Level::Allow),
234             "warn" => Some(Level::Warn),
235             "deny" => Some(Level::Deny),
236             "forbid" => Some(Level::Forbid),
237             "expect" | _ => None,
238         }
239     }
240
241     /// Converts a symbol to a level.
242     pub fn from_attr(attr: &Attribute) -> Option<Level> {
243         match attr.name_or_empty() {
244             sym::allow => Some(Level::Allow),
245             sym::expect => Some(Level::Expect(LintExpectationId::Unstable {
246                 attr_id: attr.id,
247                 lint_index: None,
248             })),
249             sym::warn => Some(Level::Warn),
250             sym::deny => Some(Level::Deny),
251             sym::forbid => Some(Level::Forbid),
252             _ => None,
253         }
254     }
255
256     pub fn to_cmd_flag(self) -> &'static str {
257         match self {
258             Level::Warn => "-W",
259             Level::Deny => "-D",
260             Level::Forbid => "-F",
261             Level::Allow => "-A",
262             Level::ForceWarn(_) => "--force-warn",
263             Level::Expect(_) => {
264                 unreachable!("the expect level does not have a commandline flag")
265             }
266         }
267     }
268
269     pub fn is_error(self) -> bool {
270         match self {
271             Level::Allow | Level::Expect(_) | Level::Warn | Level::ForceWarn(_) => false,
272             Level::Deny | Level::Forbid => true,
273         }
274     }
275
276     pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
277         match self {
278             Level::Expect(id) | Level::ForceWarn(Some(id)) => Some(*id),
279             _ => None,
280         }
281     }
282 }
283
284 /// Specification of a single lint.
285 #[derive(Copy, Clone, Debug)]
286 pub struct Lint {
287     /// A string identifier for the lint.
288     ///
289     /// This identifies the lint in attributes and in command-line arguments.
290     /// In those contexts it is always lowercase, but this field is compared
291     /// in a way which is case-insensitive for ASCII characters. This allows
292     /// `declare_lint!()` invocations to follow the convention of upper-case
293     /// statics without repeating the name.
294     ///
295     /// The name is written with underscores, e.g., "unused_imports".
296     /// On the command line, underscores become dashes.
297     ///
298     /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
299     /// for naming guidelines.
300     pub name: &'static str,
301
302     /// Default level for the lint.
303     ///
304     /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
305     /// for guidelines on choosing a default level.
306     pub default_level: Level,
307
308     /// Description of the lint or the issue it detects.
309     ///
310     /// e.g., "imports that are never used"
311     pub desc: &'static str,
312
313     /// Starting at the given edition, default to the given lint level. If this is `None`, then use
314     /// `default_level`.
315     pub edition_lint_opts: Option<(Edition, Level)>,
316
317     /// `true` if this lint is reported even inside expansions of external macros.
318     pub report_in_external_macro: bool,
319
320     pub future_incompatible: Option<FutureIncompatibleInfo>,
321
322     pub is_plugin: bool,
323
324     /// `Some` if this lint is feature gated, otherwise `None`.
325     pub feature_gate: Option<Symbol>,
326
327     pub crate_level_only: bool,
328 }
329
330 /// Extra information for a future incompatibility lint.
331 #[derive(Copy, Clone, Debug)]
332 pub struct FutureIncompatibleInfo {
333     /// e.g., a URL for an issue/PR/RFC or error code
334     pub reference: &'static str,
335     /// The reason for the lint used by diagnostics to provide
336     /// the right help message
337     pub reason: FutureIncompatibilityReason,
338     /// Whether to explain the reason to the user.
339     ///
340     /// Set to false for lints that already include a more detailed
341     /// explanation.
342     pub explain_reason: bool,
343 }
344
345 /// The reason for future incompatibility
346 #[derive(Copy, Clone, Debug)]
347 pub enum FutureIncompatibilityReason {
348     /// This will be an error in a future release
349     /// for all editions
350     FutureReleaseError,
351     /// This will be an error in a future release, and
352     /// Cargo should create a report even for dependencies
353     FutureReleaseErrorReportNow,
354     /// Code that changes meaning in some way in a
355     /// future release.
356     FutureReleaseSemanticsChange,
357     /// Previously accepted code that will become an
358     /// error in the provided edition
359     EditionError(Edition),
360     /// Code that changes meaning in some way in
361     /// the provided edition
362     EditionSemanticsChange(Edition),
363     /// A custom reason.
364     Custom(&'static str),
365 }
366
367 impl FutureIncompatibilityReason {
368     pub fn edition(self) -> Option<Edition> {
369         match self {
370             Self::EditionError(e) => Some(e),
371             Self::EditionSemanticsChange(e) => Some(e),
372             _ => None,
373         }
374     }
375 }
376
377 impl FutureIncompatibleInfo {
378     pub const fn default_fields_for_macro() -> Self {
379         FutureIncompatibleInfo {
380             reference: "",
381             reason: FutureIncompatibilityReason::FutureReleaseError,
382             explain_reason: true,
383         }
384     }
385 }
386
387 impl Lint {
388     pub const fn default_fields_for_macro() -> Self {
389         Lint {
390             name: "",
391             default_level: Level::Forbid,
392             desc: "",
393             edition_lint_opts: None,
394             is_plugin: false,
395             report_in_external_macro: false,
396             future_incompatible: None,
397             feature_gate: None,
398             crate_level_only: false,
399         }
400     }
401
402     /// Gets the lint's name, with ASCII letters converted to lowercase.
403     pub fn name_lower(&self) -> String {
404         self.name.to_ascii_lowercase()
405     }
406
407     pub fn default_level(&self, edition: Edition) -> Level {
408         self.edition_lint_opts
409             .filter(|(e, _)| *e <= edition)
410             .map(|(_, l)| l)
411             .unwrap_or(self.default_level)
412     }
413 }
414
415 /// Identifies a lint known to the compiler.
416 #[derive(Clone, Copy, Debug)]
417 pub struct LintId {
418     // Identity is based on pointer equality of this field.
419     pub lint: &'static Lint,
420 }
421
422 impl PartialEq for LintId {
423     fn eq(&self, other: &LintId) -> bool {
424         std::ptr::eq(self.lint, other.lint)
425     }
426 }
427
428 impl Eq for LintId {}
429
430 impl std::hash::Hash for LintId {
431     fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
432         let ptr = self.lint as *const Lint;
433         ptr.hash(state);
434     }
435 }
436
437 impl LintId {
438     /// Gets the `LintId` for a `Lint`.
439     pub fn of(lint: &'static Lint) -> LintId {
440         LintId { lint }
441     }
442
443     pub fn lint_name_raw(&self) -> &'static str {
444         self.lint.name
445     }
446
447     /// Gets the name of the lint.
448     pub fn to_string(&self) -> String {
449         self.lint.name_lower()
450     }
451 }
452
453 impl<HCX> HashStable<HCX> for LintId {
454     #[inline]
455     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
456         self.lint_name_raw().hash_stable(hcx, hasher);
457     }
458 }
459
460 impl<HCX> ToStableHashKey<HCX> for LintId {
461     type KeyType = &'static str;
462
463     #[inline]
464     fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
465         self.lint_name_raw()
466     }
467 }
468
469 // This could be a closure, but then implementing derive trait
470 // becomes hacky (and it gets allocated).
471 #[derive(Debug)]
472 pub enum BuiltinLintDiagnostics {
473     Normal,
474     AbsPathWithModule(Span),
475     ProcMacroDeriveResolutionFallback(Span),
476     MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
477     ElidedLifetimesInPaths(usize, Span, bool, Span),
478     UnknownCrateTypes(Span, String, String),
479     UnusedImports(String, Vec<(Span, String)>, Option<Span>),
480     RedundantImport(Vec<(Span, bool)>, Ident),
481     DeprecatedMacro(Option<Symbol>, Span),
482     MissingAbi(Span, Abi),
483     UnusedDocComment(Span),
484     UnusedBuiltinAttribute {
485         attr_name: Symbol,
486         macro_name: String,
487         invoc_span: Span,
488     },
489     PatternsInFnsWithoutBody(Span, Ident),
490     LegacyDeriveHelpers(Span),
491     ProcMacroBackCompat(String),
492     OrPatternsBackCompat(Span, String),
493     ReservedPrefix(Span),
494     TrailingMacro(bool, Ident),
495     BreakWithLabelAndLoop(Span),
496     NamedAsmLabel(String),
497     UnicodeTextFlow(Span, String),
498     UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
499     DeprecatedWhereclauseLocation(Span, String),
500     SingleUseLifetime {
501         /// Span of the parameter which declares this lifetime.
502         param_span: Span,
503         /// Span of the code that should be removed when eliding this lifetime.
504         /// This span should include leading or trailing comma.
505         deletion_span: Span,
506         /// Span of the single use, or None if the lifetime is never used.
507         /// If true, the lifetime will be fully elided.
508         use_span: Option<(Span, bool)>,
509     },
510     NamedArgumentUsedPositionally {
511         /// Span where the named argument is used by position and will be replaced with the named
512         /// argument name
513         position_sp_to_replace: Option<Span>,
514         /// Span where the named argument is used by position and is used for lint messages
515         position_sp_for_msg: Option<Span>,
516         /// Span where the named argument's name is (so we know where to put the warning message)
517         named_arg_sp: Span,
518         /// String containing the named arguments name
519         named_arg_name: String,
520         /// Indicates if the named argument is used as a width/precision for formatting
521         is_formatting_arg: bool,
522     },
523 }
524
525 /// Lints that are buffered up early on in the `Session` before the
526 /// `LintLevels` is calculated.
527 pub struct BufferedEarlyLint {
528     /// The span of code that we are linting on.
529     pub span: MultiSpan,
530
531     /// The lint message.
532     pub msg: DiagnosticMessage,
533
534     /// The `NodeId` of the AST node that generated the lint.
535     pub node_id: NodeId,
536
537     /// A lint Id that can be passed to
538     /// `rustc_lint::early::EarlyContextAndPass::check_id`.
539     pub lint_id: LintId,
540
541     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
542     pub diagnostic: BuiltinLintDiagnostics,
543 }
544
545 #[derive(Default)]
546 pub struct LintBuffer {
547     pub map: NodeMap<Vec<BufferedEarlyLint>>,
548 }
549
550 impl LintBuffer {
551     pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
552         let arr = self.map.entry(early_lint.node_id).or_default();
553         arr.push(early_lint);
554     }
555
556     pub fn add_lint(
557         &mut self,
558         lint: &'static Lint,
559         node_id: NodeId,
560         span: MultiSpan,
561         msg: impl Into<DiagnosticMessage>,
562         diagnostic: BuiltinLintDiagnostics,
563     ) {
564         let lint_id = LintId::of(lint);
565         let msg = msg.into();
566         self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
567     }
568
569     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
570         self.map.remove(&id).unwrap_or_default()
571     }
572
573     pub fn buffer_lint(
574         &mut self,
575         lint: &'static Lint,
576         id: NodeId,
577         sp: impl Into<MultiSpan>,
578         msg: impl Into<DiagnosticMessage>,
579     ) {
580         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
581     }
582
583     pub fn buffer_lint_with_diagnostic(
584         &mut self,
585         lint: &'static Lint,
586         id: NodeId,
587         sp: impl Into<MultiSpan>,
588         msg: impl Into<DiagnosticMessage>,
589         diagnostic: BuiltinLintDiagnostics,
590     ) {
591         self.add_lint(lint, id, sp.into(), msg, diagnostic)
592     }
593 }
594
595 /// Declares a static item of type `&'static Lint`.
596 ///
597 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
598 /// documentation and guidelines on writing lints.
599 ///
600 /// The macro call should start with a doc comment explaining the lint
601 /// which will be embedded in the rustc user documentation book. It should
602 /// be written in markdown and have a format that looks like this:
603 ///
604 /// ```rust,ignore (doc-example)
605 /// /// The `my_lint_name` lint detects [short explanation here].
606 /// ///
607 /// /// ### Example
608 /// ///
609 /// /// ```rust
610 /// /// [insert a concise example that triggers the lint]
611 /// /// ```
612 /// ///
613 /// /// {{produces}}
614 /// ///
615 /// /// ### Explanation
616 /// ///
617 /// /// This should be a detailed explanation of *why* the lint exists,
618 /// /// and also include suggestions on how the user should fix the problem.
619 /// /// Try to keep the text simple enough that a beginner can understand,
620 /// /// and include links to other documentation for terminology that a
621 /// /// beginner may not be familiar with. If this is "allow" by default,
622 /// /// it should explain why (are there false positives or other issues?). If
623 /// /// this is a future-incompatible lint, it should say so, with text that
624 /// /// looks roughly like this:
625 /// ///
626 /// /// This is a [future-incompatible] lint to transition this to a hard
627 /// /// error in the future. See [issue #xxxxx] for more details.
628 /// ///
629 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
630 /// ```
631 ///
632 /// The `{{produces}}` tag will be automatically replaced with the output from
633 /// the example by the build system. If the lint example is too complex to run
634 /// as a simple example (for example, it needs an extern crate), mark the code
635 /// block with `ignore` and manually replace the `{{produces}}` line with the
636 /// expected output in a `text` code block.
637 ///
638 /// If this is a rustdoc-only lint, then only include a brief introduction
639 /// with a link with the text `[rustdoc book]` so that the validator knows
640 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
641 ///
642 /// Commands to view and test the documentation:
643 ///
644 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
645 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
646 ///   correct style, and that the code example actually emits the expected
647 ///   lint.
648 ///
649 /// If you have already built the compiler, and you want to make changes to
650 /// just the doc comments, then use the `--keep-stage=0` flag with the above
651 /// commands to avoid rebuilding the compiler.
652 #[macro_export]
653 macro_rules! declare_lint {
654     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
655         $crate::declare_lint!(
656             $(#[$attr])* $vis $NAME, $Level, $desc,
657         );
658     );
659     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
660      $(@feature_gate = $gate:expr;)?
661      $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)*  }; )?
662      $($v:ident),*) => (
663         $(#[$attr])*
664         $vis static $NAME: &$crate::Lint = &$crate::Lint {
665             name: stringify!($NAME),
666             default_level: $crate::$Level,
667             desc: $desc,
668             edition_lint_opts: None,
669             is_plugin: false,
670             $($v: true,)*
671             $(feature_gate: Some($gate),)*
672             $(future_incompatible: Some($crate::FutureIncompatibleInfo {
673                 $($field: $val,)*
674                 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
675             }),)*
676             ..$crate::Lint::default_fields_for_macro()
677         };
678     );
679     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
680      $lint_edition: expr => $edition_level: ident
681     ) => (
682         $(#[$attr])*
683         $vis static $NAME: &$crate::Lint = &$crate::Lint {
684             name: stringify!($NAME),
685             default_level: $crate::$Level,
686             desc: $desc,
687             edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
688             report_in_external_macro: false,
689             is_plugin: false,
690         };
691     );
692 }
693
694 #[macro_export]
695 macro_rules! declare_tool_lint {
696     (
697         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
698         $(, @feature_gate = $gate:expr;)?
699     ) => (
700         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?}
701     );
702     (
703         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
704         report_in_external_macro: $rep:expr
705         $(, @feature_gate = $gate:expr;)?
706     ) => (
707          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?}
708     );
709     (
710         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
711         $external:expr
712         $(, @feature_gate = $gate:expr;)?
713     ) => (
714         $(#[$attr])*
715         $vis static $NAME: &$crate::Lint = &$crate::Lint {
716             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
717             default_level: $crate::$Level,
718             desc: $desc,
719             edition_lint_opts: None,
720             report_in_external_macro: $external,
721             future_incompatible: None,
722             is_plugin: true,
723             $(feature_gate: Some($gate),)?
724             crate_level_only: false,
725             ..$crate::Lint::default_fields_for_macro()
726         };
727     );
728 }
729
730 /// Declares a static `LintArray` and return it as an expression.
731 #[macro_export]
732 macro_rules! lint_array {
733     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
734     ($( $lint:expr ),*) => {{
735         vec![$($lint),*]
736     }}
737 }
738
739 pub type LintArray = Vec<&'static Lint>;
740
741 pub trait LintPass {
742     fn name(&self) -> &'static str;
743 }
744
745 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
746 #[macro_export]
747 macro_rules! impl_lint_pass {
748     ($ty:ty => [$($lint:expr),* $(,)?]) => {
749         impl $crate::LintPass for $ty {
750             fn name(&self) -> &'static str { stringify!($ty) }
751         }
752         impl $ty {
753             pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
754         }
755     };
756 }
757
758 /// Declares a type named `$name` which implements `LintPass`.
759 /// To the right of `=>` a comma separated list of `Lint` statics is given.
760 #[macro_export]
761 macro_rules! declare_lint_pass {
762     ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
763         $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
764         $crate::impl_lint_pass!($name => [$($lint),*]);
765     };
766 }