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