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