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