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