]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint_defs/src/lib.rs
Rollup merge of #95809 - ytmimi:llvm_stamp_typo, 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     ElidedLifetimesInPaths(usize, Span, bool, Span),
422     UnknownCrateTypes(Span, String, String),
423     UnusedImports(String, Vec<(Span, String)>, Option<Span>),
424     RedundantImport(Vec<(Span, bool)>, Ident),
425     DeprecatedMacro(Option<Symbol>, Span),
426     MissingAbi(Span, Abi),
427     UnusedDocComment(Span),
428     UnusedBuiltinAttribute { attr_name: Symbol, macro_name: String, invoc_span: Span },
429     PatternsInFnsWithoutBody(Span, Ident),
430     LegacyDeriveHelpers(Span),
431     ExternDepSpec(String, ExternDepSpec),
432     ProcMacroBackCompat(String),
433     OrPatternsBackCompat(Span, String),
434     ReservedPrefix(Span),
435     TrailingMacro(bool, Ident),
436     BreakWithLabelAndLoop(Span),
437     NamedAsmLabel(String),
438     UnicodeTextFlow(Span, String),
439     UnexpectedCfg((Symbol, Span), Option<(Symbol, Span)>),
440     DeprecatedWhereclauseLocation(Span, String),
441 }
442
443 /// Lints that are buffered up early on in the `Session` before the
444 /// `LintLevels` is calculated.
445 pub struct BufferedEarlyLint {
446     /// The span of code that we are linting on.
447     pub span: MultiSpan,
448
449     /// The lint message.
450     pub msg: String,
451
452     /// The `NodeId` of the AST node that generated the lint.
453     pub node_id: NodeId,
454
455     /// A lint Id that can be passed to
456     /// `rustc_lint::early::EarlyContextAndPass::check_id`.
457     pub lint_id: LintId,
458
459     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
460     pub diagnostic: BuiltinLintDiagnostics,
461 }
462
463 #[derive(Default)]
464 pub struct LintBuffer {
465     pub map: NodeMap<Vec<BufferedEarlyLint>>,
466 }
467
468 impl LintBuffer {
469     pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
470         let arr = self.map.entry(early_lint.node_id).or_default();
471         arr.push(early_lint);
472     }
473
474     pub fn add_lint(
475         &mut self,
476         lint: &'static Lint,
477         node_id: NodeId,
478         span: MultiSpan,
479         msg: &str,
480         diagnostic: BuiltinLintDiagnostics,
481     ) {
482         let lint_id = LintId::of(lint);
483         let msg = msg.to_string();
484         self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
485     }
486
487     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
488         self.map.remove(&id).unwrap_or_default()
489     }
490
491     pub fn buffer_lint(
492         &mut self,
493         lint: &'static Lint,
494         id: NodeId,
495         sp: impl Into<MultiSpan>,
496         msg: &str,
497     ) {
498         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
499     }
500
501     pub fn buffer_lint_with_diagnostic(
502         &mut self,
503         lint: &'static Lint,
504         id: NodeId,
505         sp: impl Into<MultiSpan>,
506         msg: &str,
507         diagnostic: BuiltinLintDiagnostics,
508     ) {
509         self.add_lint(lint, id, sp.into(), msg, diagnostic)
510     }
511 }
512
513 /// Declares a static item of type `&'static Lint`.
514 ///
515 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
516 /// documentation and guidelines on writing lints.
517 ///
518 /// The macro call should start with a doc comment explaining the lint
519 /// which will be embedded in the rustc user documentation book. It should
520 /// be written in markdown and have a format that looks like this:
521 ///
522 /// ```rust,ignore (doc-example)
523 /// /// The `my_lint_name` lint detects [short explanation here].
524 /// ///
525 /// /// ### Example
526 /// ///
527 /// /// ```rust
528 /// /// [insert a concise example that triggers the lint]
529 /// /// ```
530 /// ///
531 /// /// {{produces}}
532 /// ///
533 /// /// ### Explanation
534 /// ///
535 /// /// This should be a detailed explanation of *why* the lint exists,
536 /// /// and also include suggestions on how the user should fix the problem.
537 /// /// Try to keep the text simple enough that a beginner can understand,
538 /// /// and include links to other documentation for terminology that a
539 /// /// beginner may not be familiar with. If this is "allow" by default,
540 /// /// it should explain why (are there false positives or other issues?). If
541 /// /// this is a future-incompatible lint, it should say so, with text that
542 /// /// looks roughly like this:
543 /// ///
544 /// /// This is a [future-incompatible] lint to transition this to a hard
545 /// /// error in the future. See [issue #xxxxx] for more details.
546 /// ///
547 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
548 /// ```
549 ///
550 /// The `{{produces}}` tag will be automatically replaced with the output from
551 /// the example by the build system. If the lint example is too complex to run
552 /// as a simple example (for example, it needs an extern crate), mark the code
553 /// block with `ignore` and manually replace the `{{produces}}` line with the
554 /// expected output in a `text` code block.
555 ///
556 /// If this is a rustdoc-only lint, then only include a brief introduction
557 /// with a link with the text `[rustdoc book]` so that the validator knows
558 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
559 ///
560 /// Commands to view and test the documentation:
561 ///
562 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
563 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
564 ///   correct style, and that the code example actually emits the expected
565 ///   lint.
566 ///
567 /// If you have already built the compiler, and you want to make changes to
568 /// just the doc comments, then use the `--keep-stage=0` flag with the above
569 /// commands to avoid rebuilding the compiler.
570 #[macro_export]
571 macro_rules! declare_lint {
572     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
573         $crate::declare_lint!(
574             $(#[$attr])* $vis $NAME, $Level, $desc,
575         );
576     );
577     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
578      $(@feature_gate = $gate:expr;)?
579      $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)*  }; )?
580      $($v:ident),*) => (
581         $(#[$attr])*
582         $vis static $NAME: &$crate::Lint = &$crate::Lint {
583             name: stringify!($NAME),
584             default_level: $crate::$Level,
585             desc: $desc,
586             edition_lint_opts: None,
587             is_plugin: false,
588             $($v: true,)*
589             $(feature_gate: Some($gate),)*
590             $(future_incompatible: Some($crate::FutureIncompatibleInfo {
591                 $($field: $val,)*
592                 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
593             }),)*
594             ..$crate::Lint::default_fields_for_macro()
595         };
596     );
597     ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
598      $lint_edition: expr => $edition_level: ident
599     ) => (
600         $(#[$attr])*
601         $vis static $NAME: &$crate::Lint = &$crate::Lint {
602             name: stringify!($NAME),
603             default_level: $crate::$Level,
604             desc: $desc,
605             edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
606             report_in_external_macro: false,
607             is_plugin: false,
608         };
609     );
610 }
611
612 #[macro_export]
613 macro_rules! declare_tool_lint {
614     (
615         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
616     ) => (
617         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
618     );
619     (
620         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
621         report_in_external_macro: $rep:expr
622     ) => (
623          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
624     );
625     (
626         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
627         $external:expr
628     ) => (
629         $(#[$attr])*
630         $vis static $NAME: &$crate::Lint = &$crate::Lint {
631             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
632             default_level: $crate::$Level,
633             desc: $desc,
634             edition_lint_opts: None,
635             report_in_external_macro: $external,
636             future_incompatible: None,
637             is_plugin: true,
638             feature_gate: None,
639             crate_level_only: false,
640         };
641     );
642 }
643
644 /// Declares a static `LintArray` and return it as an expression.
645 #[macro_export]
646 macro_rules! lint_array {
647     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
648     ($( $lint:expr ),*) => {{
649         vec![$($lint),*]
650     }}
651 }
652
653 pub type LintArray = Vec<&'static Lint>;
654
655 pub trait LintPass {
656     fn name(&self) -> &'static str;
657 }
658
659 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
660 #[macro_export]
661 macro_rules! impl_lint_pass {
662     ($ty:ty => [$($lint:expr),* $(,)?]) => {
663         impl $crate::LintPass for $ty {
664             fn name(&self) -> &'static str { stringify!($ty) }
665         }
666         impl $ty {
667             pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
668         }
669     };
670 }
671
672 /// Declares a type named `$name` which implements `LintPass`.
673 /// To the right of `=>` a comma separated list of `Lint` statics is given.
674 #[macro_export]
675 macro_rules! declare_lint_pass {
676     ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
677         $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
678         $crate::impl_lint_pass!($name => [$($lint),*]);
679     };
680 }