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