rustc_lint_defs/lib.rs
1use std::borrow::Cow;
2
3use rustc_ast::AttrId;
4use rustc_ast::attr::AttributeExt;
5use rustc_data_structures::fx::FxIndexSet;
6use rustc_data_structures::stable_hasher::{
7 HashStable, StableCompare, StableHasher, ToStableHashKey,
8};
9use rustc_error_messages::{DiagArgValue, DiagMessage, IntoDiagArg, MultiSpan};
10use rustc_hir_id::{HashStableContext, HirId, ItemLocalId};
11use rustc_macros::{Decodable, Encodable, HashStable_Generic};
12use rustc_span::def_id::DefPathHash;
13pub use rustc_span::edition::Edition;
14use rustc_span::{Ident, Span, Symbol, sym};
15use serde::{Deserialize, Serialize};
16
17pub use self::Level::*;
18
19pub mod builtin;
20
21#[macro_export]
22macro_rules! pluralize {
23 // Pluralize based on count (e.g., apples)
24 ($x:expr) => {
25 if $x == 1 { "" } else { "s" }
26 };
27 ("has", $x:expr) => {
28 if $x == 1 { "has" } else { "have" }
29 };
30 ("is", $x:expr) => {
31 if $x == 1 { "is" } else { "are" }
32 };
33 ("was", $x:expr) => {
34 if $x == 1 { "was" } else { "were" }
35 };
36 ("this", $x:expr) => {
37 if $x == 1 { "this" } else { "these" }
38 };
39}
40
41/// Grammatical tool for displaying messages to end users in a nice form.
42///
43/// Take a list of items and a function to turn those items into a `String`, and output a display
44/// friendly comma separated list of those items.
45// FIXME(estebank): this needs to be changed to go through the translation machinery.
46pub fn listify<T>(list: &[T], fmt: impl Fn(&T) -> String) -> Option<String> {
47 Some(match list {
48 [only] => fmt(&only),
49 [others @ .., last] => format!(
50 "{} and {}",
51 others.iter().map(|i| fmt(i)).collect::<Vec<_>>().join(", "),
52 fmt(&last),
53 ),
54 [] => return None,
55 })
56}
57
58/// Indicates the confidence in the correctness of a suggestion.
59///
60/// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
61/// to determine whether it should be automatically applied or if the user should be consulted
62/// before applying the suggestion.
63#[derive(Copy, Clone, Debug, Hash, Encodable, Decodable, Serialize, Deserialize)]
64#[derive(PartialEq, Eq, PartialOrd, Ord)]
65pub enum Applicability {
66 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
67 /// This suggestion should be automatically applied.
68 ///
69 /// In case of multiple `MachineApplicable` suggestions (whether as part of
70 /// the same `multipart_suggestion` or not), all of them should be
71 /// automatically applied.
72 MachineApplicable,
73
74 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
75 /// result in valid Rust code if it is applied.
76 MaybeIncorrect,
77
78 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
79 /// cannot be applied automatically because it will not result in valid Rust code. The user
80 /// will need to fill in the placeholders.
81 HasPlaceholders,
82
83 /// The applicability of the suggestion is unknown.
84 Unspecified,
85}
86
87/// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
88/// Expected diagnostics get the lint level `Expect` which stores the `LintExpectationId`
89/// to match it with the actual expectation later on.
90///
91/// The `LintExpectationId` has to be stable between compilations, as diagnostic
92/// instances might be loaded from cache. Lint messages can be emitted during an
93/// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
94/// HIR tree. The AST doesn't have enough information to create a stable id. The
95/// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
96/// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
97/// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
98///
99/// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
100/// identifies the lint inside the attribute and ensures that the IDs are unique.
101///
102/// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
103/// It's reasonable to assume that no user will define 2^16 attributes on one node or
104/// have that amount of lints listed. `u16` values should therefore suffice.
105#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Encodable, Decodable)]
106pub enum LintExpectationId {
107 /// Used for lints emitted during the `EarlyLintPass`. This id is not
108 /// hash stable and should not be cached.
109 Unstable { attr_id: AttrId, lint_index: Option<u16> },
110 /// The [`HirId`] that the lint expectation is attached to. This id is
111 /// stable and can be cached. The additional index ensures that nodes with
112 /// several expectations can correctly match diagnostics to the individual
113 /// expectation.
114 Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16> },
115}
116
117impl LintExpectationId {
118 pub fn is_stable(&self) -> bool {
119 match self {
120 LintExpectationId::Unstable { .. } => false,
121 LintExpectationId::Stable { .. } => true,
122 }
123 }
124
125 pub fn get_lint_index(&self) -> Option<u16> {
126 let (LintExpectationId::Unstable { lint_index, .. }
127 | LintExpectationId::Stable { lint_index, .. }) = self;
128
129 *lint_index
130 }
131
132 pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
133 let (LintExpectationId::Unstable { lint_index, .. }
134 | LintExpectationId::Stable { lint_index, .. }) = self;
135
136 *lint_index = new_lint_index
137 }
138}
139
140impl<HCX: HashStableContext> HashStable<HCX> for LintExpectationId {
141 #[inline]
142 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
143 match self {
144 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
145 hir_id.hash_stable(hcx, hasher);
146 attr_index.hash_stable(hcx, hasher);
147 lint_index.hash_stable(hcx, hasher);
148 }
149 _ => {
150 unreachable!(
151 "HashStable should only be called for filled and stable `LintExpectationId`"
152 )
153 }
154 }
155 }
156}
157
158impl<HCX: HashStableContext> ToStableHashKey<HCX> for LintExpectationId {
159 type KeyType = (DefPathHash, ItemLocalId, u16, u16);
160
161 #[inline]
162 fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType {
163 match self {
164 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
165 let (def_path_hash, lint_idx) = hir_id.to_stable_hash_key(hcx);
166 (def_path_hash, lint_idx, *attr_index, *lint_index)
167 }
168 _ => {
169 unreachable!("HashStable should only be called for a filled `LintExpectationId`")
170 }
171 }
172 }
173}
174
175/// Setting for how to handle a lint.
176///
177/// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
178#[derive(
179 Clone,
180 Copy,
181 PartialEq,
182 PartialOrd,
183 Eq,
184 Ord,
185 Debug,
186 Hash,
187 Encodable,
188 Decodable,
189 HashStable_Generic
190)]
191pub enum Level {
192 /// The `allow` level will not issue any message.
193 Allow,
194 /// The `expect` level will suppress the lint message but in turn produce a message
195 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
196 /// an initial level for a lint.
197 ///
198 /// Note that this still means that the lint is enabled in this position and should
199 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
200 ///
201 /// See RFC 2383.
202 ///
203 /// Requires a [`LintExpectationId`] to later link a lint emission to the actual
204 /// expectation. It can be ignored in most cases.
205 Expect,
206 /// The `warn` level will produce a warning if the lint was violated, however the
207 /// compiler will continue with its execution.
208 Warn,
209 /// This lint level is a special case of [`Warn`], that can't be overridden. This is used
210 /// to ensure that a lint can't be suppressed. This lint level can currently only be set
211 /// via the console and is therefore session specific.
212 ///
213 /// Requires a [`LintExpectationId`] to fulfill expectations marked via the
214 /// `#[expect]` attribute, that will still be suppressed due to the level.
215 ForceWarn,
216 /// The `deny` level will produce an error and stop further execution after the lint
217 /// pass is complete.
218 Deny,
219 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
220 /// levels.
221 Forbid,
222}
223
224impl Level {
225 /// Converts a level to a lower-case string.
226 pub fn as_str(self) -> &'static str {
227 match self {
228 Level::Allow => "allow",
229 Level::Expect => "expect",
230 Level::Warn => "warn",
231 Level::ForceWarn => "force-warn",
232 Level::Deny => "deny",
233 Level::Forbid => "forbid",
234 }
235 }
236
237 /// Converts a lower-case string to a level. This will never construct the expect
238 /// level as that would require a [`LintExpectationId`].
239 pub fn from_str(x: &str) -> Option<Self> {
240 match x {
241 "allow" => Some(Level::Allow),
242 "warn" => Some(Level::Warn),
243 "deny" => Some(Level::Deny),
244 "forbid" => Some(Level::Forbid),
245 "expect" | _ => None,
246 }
247 }
248
249 /// Converts an `Attribute` to a level.
250 pub fn from_attr(attr: &impl AttributeExt) -> Option<(Self, Option<LintExpectationId>)> {
251 attr.name().and_then(|name| Self::from_symbol(name, || Some(attr.id())))
252 }
253
254 /// Converts a `Symbol` to a level.
255 pub fn from_symbol(
256 s: Symbol,
257 id: impl FnOnce() -> Option<AttrId>,
258 ) -> Option<(Self, Option<LintExpectationId>)> {
259 match s {
260 sym::allow => Some((Level::Allow, None)),
261 sym::expect => {
262 if let Some(attr_id) = id() {
263 Some((
264 Level::Expect,
265 Some(LintExpectationId::Unstable { attr_id, lint_index: None }),
266 ))
267 } else {
268 None
269 }
270 }
271 sym::warn => Some((Level::Warn, None)),
272 sym::deny => Some((Level::Deny, None)),
273 sym::forbid => Some((Level::Forbid, None)),
274 _ => None,
275 }
276 }
277
278 pub fn to_cmd_flag(self) -> &'static str {
279 match self {
280 Level::Warn => "-W",
281 Level::Deny => "-D",
282 Level::Forbid => "-F",
283 Level::Allow => "-A",
284 Level::ForceWarn => "--force-warn",
285 Level::Expect => {
286 unreachable!("the expect level does not have a commandline flag")
287 }
288 }
289 }
290
291 pub fn is_error(self) -> bool {
292 match self {
293 Level::Allow | Level::Expect | Level::Warn | Level::ForceWarn => false,
294 Level::Deny | Level::Forbid => true,
295 }
296 }
297}
298
299impl IntoDiagArg for Level {
300 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
301 DiagArgValue::Str(Cow::Borrowed(self.to_cmd_flag()))
302 }
303}
304
305/// Specification of a single lint.
306#[derive(Copy, Clone, Debug)]
307pub struct Lint {
308 /// A string identifier for the lint.
309 ///
310 /// This identifies the lint in attributes and in command-line arguments.
311 /// In those contexts it is always lowercase, but this field is compared
312 /// in a way which is case-insensitive for ASCII characters. This allows
313 /// `declare_lint!()` invocations to follow the convention of upper-case
314 /// statics without repeating the name.
315 ///
316 /// The name is written with underscores, e.g., "unused_imports".
317 /// On the command line, underscores become dashes.
318 ///
319 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
320 /// for naming guidelines.
321 pub name: &'static str,
322
323 /// Default level for the lint.
324 ///
325 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
326 /// for guidelines on choosing a default level.
327 pub default_level: Level,
328
329 /// Description of the lint or the issue it detects.
330 ///
331 /// e.g., "imports that are never used"
332 pub desc: &'static str,
333
334 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
335 /// `default_level`.
336 pub edition_lint_opts: Option<(Edition, Level)>,
337
338 /// `true` if this lint is reported even inside expansions of external macros.
339 pub report_in_external_macro: bool,
340
341 pub future_incompatible: Option<FutureIncompatibleInfo>,
342
343 /// `true` if this lint is being loaded by another tool (e.g. Clippy).
344 pub is_externally_loaded: bool,
345
346 /// `Some` if this lint is feature gated, otherwise `None`.
347 pub feature_gate: Option<Symbol>,
348
349 pub crate_level_only: bool,
350
351 /// `true` if this lint should not be filtered out under any circustamces
352 /// (e.g. the unknown_attributes lint)
353 pub eval_always: bool,
354}
355
356/// Extra information for a future incompatibility lint.
357#[derive(Copy, Clone, Debug)]
358pub struct FutureIncompatibleInfo {
359 /// e.g., a URL for an issue/PR/RFC or error code
360 pub reference: &'static str,
361 /// The reason for the lint used by diagnostics to provide
362 /// the right help message
363 pub reason: FutureIncompatibilityReason,
364 /// Whether to explain the reason to the user.
365 ///
366 /// Set to false for lints that already include a more detailed
367 /// explanation.
368 pub explain_reason: bool,
369 /// If set to `true`, this will make future incompatibility warnings show up in cargo's
370 /// reports.
371 ///
372 /// When a future incompatibility warning is first inroduced, set this to `false`
373 /// (or, rather, don't override the default). This allows crate developers an opportunity
374 /// to fix the warning before blasting all dependents with a warning they can't fix
375 /// (dependents have to wait for a new release of the affected crate to be published).
376 ///
377 /// After a lint has been in this state for a while, consider setting this to true, so it
378 /// warns for everyone. It is a good signal that it is ready if you can determine that all
379 /// or most affected crates on crates.io have been updated.
380 pub report_in_deps: bool,
381}
382
383/// The reason for future incompatibility
384///
385/// Future-incompatible lints come in roughly two categories:
386///
387/// 1. There was a mistake in the compiler (such as a soundness issue), and
388/// we're trying to fix it, but it may be a breaking change.
389/// 2. A change across an Edition boundary, typically used for the
390/// introduction of new language features that can't otherwise be
391/// introduced in a backwards-compatible way.
392///
393/// See <https://rustc-dev-guide.rust-lang.org/bug-fix-procedure.html> and
394/// <https://rustc-dev-guide.rust-lang.org/diagnostics.html#future-incompatible-lints>
395/// for more information.
396#[derive(Copy, Clone, Debug)]
397pub enum FutureIncompatibilityReason {
398 /// This will be an error in a future release for all editions
399 ///
400 /// Choose this variant when you are first introducing a "future
401 /// incompatible" warning that is intended to eventually be fixed in the
402 /// future.
403 ///
404 /// After a lint has been in this state for a while and you feel like it is ready to graduate
405 /// to warning everyone, consider setting [`FutureIncompatibleInfo::report_in_deps`] to true.
406 /// (see it's documentation for more guidance)
407 ///
408 /// After some period of time, lints with this variant can be turned into
409 /// hard errors (and the lint removed). Preferably when there is some
410 /// confidence that the number of impacted projects is very small (few
411 /// should have a broken dependency in their dependency tree).
412 FutureReleaseError,
413 /// Code that changes meaning in some way in a
414 /// future release.
415 ///
416 /// Choose this variant when the semantics of existing code is changing,
417 /// (as opposed to [`FutureIncompatibilityReason::FutureReleaseError`],
418 /// which is for when code is going to be rejected in the future).
419 FutureReleaseSemanticsChange,
420 /// Previously accepted code that will become an
421 /// error in the provided edition
422 ///
423 /// Choose this variant for code that you want to start rejecting across
424 /// an edition boundary. This will automatically include the lint in the
425 /// `rust-20xx-compatibility` lint group, which is used by `cargo fix
426 /// --edition` to do migrations. The lint *should* be auto-fixable with
427 /// [`Applicability::MachineApplicable`].
428 ///
429 /// The lint can either be `Allow` or `Warn` by default. If it is `Allow`,
430 /// users usually won't see this warning unless they are doing an edition
431 /// migration manually or there is a problem during the migration (cargo's
432 /// automatic migrations will force the level to `Warn`). If it is `Warn`
433 /// by default, users on all editions will see this warning (only do this
434 /// if you think it is important for everyone to be aware of the change,
435 /// and to encourage people to update their code on all editions).
436 ///
437 /// See also [`FutureIncompatibilityReason::EditionSemanticsChange`] if
438 /// you have code that is changing semantics across the edition (as
439 /// opposed to being rejected).
440 EditionError(Edition),
441 /// Code that changes meaning in some way in
442 /// the provided edition
443 ///
444 /// This is the same as [`FutureIncompatibilityReason::EditionError`],
445 /// except for situations where the semantics change across an edition. It
446 /// slightly changes the text of the diagnostic, but is otherwise the
447 /// same.
448 EditionSemanticsChange(Edition),
449 /// This will be an error in the provided edition *and* in a future
450 /// release.
451 ///
452 /// This variant a combination of [`FutureReleaseError`] and [`EditionError`].
453 /// This is useful in rare cases when we want to have "preview" of a breaking
454 /// change in an edition, but do a breaking change later on all editions anyway.
455 ///
456 /// [`EditionError`]: FutureIncompatibilityReason::EditionError
457 /// [`FutureReleaseError`]: FutureIncompatibilityReason::FutureReleaseError
458 EditionAndFutureReleaseError(Edition),
459 /// This will change meaning in the provided edition *and* in a future
460 /// release.
461 ///
462 /// This variant a combination of [`FutureReleaseSemanticsChange`]
463 /// and [`EditionSemanticsChange`]. This is useful in rare cases when we
464 /// want to have "preview" of a breaking change in an edition, but do a
465 /// breaking change later on all editions anyway.
466 ///
467 /// [`EditionSemanticsChange`]: FutureIncompatibilityReason::EditionSemanticsChange
468 /// [`FutureReleaseSemanticsChange`]: FutureIncompatibilityReason::FutureReleaseSemanticsChange
469 EditionAndFutureReleaseSemanticsChange(Edition),
470 /// A custom reason.
471 ///
472 /// Choose this variant if the built-in text of the diagnostic of the
473 /// other variants doesn't match your situation. This is behaviorally
474 /// equivalent to
475 /// [`FutureIncompatibilityReason::FutureReleaseError`].
476 Custom(&'static str),
477}
478
479impl FutureIncompatibilityReason {
480 pub fn edition(self) -> Option<Edition> {
481 match self {
482 Self::EditionError(e)
483 | Self::EditionSemanticsChange(e)
484 | Self::EditionAndFutureReleaseError(e)
485 | Self::EditionAndFutureReleaseSemanticsChange(e) => Some(e),
486
487 FutureIncompatibilityReason::FutureReleaseError
488 | FutureIncompatibilityReason::FutureReleaseSemanticsChange
489 | FutureIncompatibilityReason::Custom(_) => None,
490 }
491 }
492}
493
494impl FutureIncompatibleInfo {
495 pub const fn default_fields_for_macro() -> Self {
496 FutureIncompatibleInfo {
497 reference: "",
498 reason: FutureIncompatibilityReason::FutureReleaseError,
499 explain_reason: true,
500 report_in_deps: false,
501 }
502 }
503}
504
505impl Lint {
506 pub const fn default_fields_for_macro() -> Self {
507 Lint {
508 name: "",
509 default_level: Level::Forbid,
510 desc: "",
511 edition_lint_opts: None,
512 is_externally_loaded: false,
513 report_in_external_macro: false,
514 future_incompatible: None,
515 feature_gate: None,
516 crate_level_only: false,
517 eval_always: false,
518 }
519 }
520
521 /// Gets the lint's name, with ASCII letters converted to lowercase.
522 pub fn name_lower(&self) -> String {
523 self.name.to_ascii_lowercase()
524 }
525
526 pub fn default_level(&self, edition: Edition) -> Level {
527 self.edition_lint_opts
528 .filter(|(e, _)| *e <= edition)
529 .map(|(_, l)| l)
530 .unwrap_or(self.default_level)
531 }
532}
533
534/// Identifies a lint known to the compiler.
535#[derive(Clone, Copy, Debug)]
536pub struct LintId {
537 // Identity is based on pointer equality of this field.
538 pub lint: &'static Lint,
539}
540
541impl PartialEq for LintId {
542 fn eq(&self, other: &LintId) -> bool {
543 std::ptr::eq(self.lint, other.lint)
544 }
545}
546
547impl Eq for LintId {}
548
549impl std::hash::Hash for LintId {
550 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
551 let ptr = self.lint as *const Lint;
552 ptr.hash(state);
553 }
554}
555
556impl LintId {
557 /// Gets the `LintId` for a `Lint`.
558 pub fn of(lint: &'static Lint) -> LintId {
559 LintId { lint }
560 }
561
562 pub fn lint_name_raw(&self) -> &'static str {
563 self.lint.name
564 }
565
566 /// Gets the name of the lint.
567 pub fn to_string(&self) -> String {
568 self.lint.name_lower()
569 }
570}
571
572impl<HCX> HashStable<HCX> for LintId {
573 #[inline]
574 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
575 self.lint_name_raw().hash_stable(hcx, hasher);
576 }
577}
578
579impl<HCX> ToStableHashKey<HCX> for LintId {
580 type KeyType = &'static str;
581
582 #[inline]
583 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
584 self.lint_name_raw()
585 }
586}
587
588impl StableCompare for LintId {
589 const CAN_USE_UNSTABLE_SORT: bool = true;
590
591 fn stable_cmp(&self, other: &Self) -> std::cmp::Ordering {
592 self.lint_name_raw().cmp(&other.lint_name_raw())
593 }
594}
595
596#[derive(Debug)]
597pub struct AmbiguityErrorDiag {
598 pub msg: String,
599 pub span: Span,
600 pub label_span: Span,
601 pub label_msg: String,
602 pub note_msg: String,
603 pub b1_span: Span,
604 pub b1_note_msg: String,
605 pub b1_help_msgs: Vec<String>,
606 pub b2_span: Span,
607 pub b2_note_msg: String,
608 pub b2_help_msgs: Vec<String>,
609}
610
611#[derive(Debug, Clone)]
612pub enum DeprecatedSinceKind {
613 InEffect,
614 InFuture,
615 InVersion(String),
616}
617
618// This could be a closure, but then implementing derive trait
619// becomes hacky (and it gets allocated).
620#[derive(Debug)]
621pub enum BuiltinLintDiag {
622 AbsPathWithModule(Span),
623 ElidedLifetimesInPaths(usize, Span, bool, Span),
624 UnusedImports {
625 remove_whole_use: bool,
626 num_to_remove: usize,
627 remove_spans: Vec<Span>,
628 test_module_span: Option<Span>,
629 span_snippets: Vec<String>,
630 },
631 RedundantImport(Vec<(Span, bool)>, Ident),
632 DeprecatedMacro {
633 suggestion: Option<Symbol>,
634 suggestion_span: Span,
635 note: Option<Symbol>,
636 path: String,
637 since_kind: DeprecatedSinceKind,
638 },
639 PatternsInFnsWithoutBody {
640 span: Span,
641 ident: Ident,
642 is_foreign: bool,
643 },
644 ReservedPrefix(Span, String),
645 /// `'r#` in edition < 2021.
646 RawPrefix(Span),
647 /// `##` or `#"` in edition < 2024.
648 ReservedString {
649 is_string: bool,
650 suggestion: Span,
651 },
652 BreakWithLabelAndLoop(Span),
653 UnicodeTextFlow(Span, String),
654 UnexpectedCfgName((Symbol, Span), Option<(Symbol, Span)>),
655 UnexpectedCfgValue((Symbol, Span), Option<(Symbol, Span)>),
656 DeprecatedWhereclauseLocation(Span, Option<(Span, String)>),
657 SingleUseLifetime {
658 /// Span of the parameter which declares this lifetime.
659 param_span: Span,
660 /// Span of the code that should be removed when eliding this lifetime.
661 /// This span should include leading or trailing comma.
662 deletion_span: Option<Span>,
663 /// Span of the single use, or None if the lifetime is never used.
664 /// If true, the lifetime will be fully elided.
665 use_span: Option<(Span, bool)>,
666 ident: Ident,
667 },
668 NamedArgumentUsedPositionally {
669 /// Span where the named argument is used by position and will be replaced with the named
670 /// argument name
671 position_sp_to_replace: Option<Span>,
672 /// Span where the named argument is used by position and is used for lint messages
673 position_sp_for_msg: Option<Span>,
674 /// Span where the named argument's name is (so we know where to put the warning message)
675 named_arg_sp: Span,
676 /// String containing the named arguments name
677 named_arg_name: String,
678 /// Indicates if the named argument is used as a width/precision for formatting
679 is_formatting_arg: bool,
680 },
681 ExternCrateNotIdiomatic {
682 vis_span: Span,
683 ident_span: Span,
684 },
685 AmbiguousGlobImports {
686 diag: AmbiguityErrorDiag,
687 },
688 AmbiguousGlobReexports {
689 /// The name for which collision(s) have occurred.
690 name: String,
691 /// The name space for which the collision(s) occurred in.
692 namespace: String,
693 /// Span where the name is first re-exported.
694 first_reexport_span: Span,
695 /// Span where the same name is also re-exported.
696 duplicate_reexport_span: Span,
697 },
698 HiddenGlobReexports {
699 /// The name of the local binding which shadows the glob re-export.
700 name: String,
701 /// The namespace for which the shadowing occurred in.
702 namespace: String,
703 /// The glob reexport that is shadowed by the local binding.
704 glob_reexport_span: Span,
705 /// The local binding that shadows the glob reexport.
706 private_item_span: Span,
707 },
708 UnusedQualifications {
709 /// The span of the unnecessarily-qualified path to remove.
710 removal_span: Span,
711 },
712 UnsafeAttrOutsideUnsafe {
713 attribute_name_span: Span,
714 sugg_spans: (Span, Span),
715 },
716 AssociatedConstElidedLifetime {
717 elided: bool,
718 span: Span,
719 lifetimes_in_scope: MultiSpan,
720 },
721 RedundantImportVisibility {
722 span: Span,
723 max_vis: String,
724 import_vis: String,
725 },
726 UnknownDiagnosticAttribute {
727 span: Span,
728 typo_name: Option<Symbol>,
729 },
730 PrivateExternCrateReexport {
731 source: Ident,
732 extern_crate_span: Span,
733 },
734 MacroIsPrivate(Ident),
735 UnusedMacroDefinition(Symbol),
736 MacroRuleNeverUsed(usize, Symbol),
737 UnstableFeature(DiagMessage),
738 UnusedCrateDependency {
739 extern_crate: Symbol,
740 local_crate: Symbol,
741 },
742 IllFormedAttributeInput {
743 suggestions: Vec<String>,
744 docs: Option<&'static str>,
745 },
746 OutOfScopeMacroCalls {
747 span: Span,
748 path: String,
749 location: String,
750 },
751}
752
753pub type RegisteredTools = FxIndexSet<Ident>;
754
755/// Declares a static item of type `&'static Lint`.
756///
757/// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
758/// documentation and guidelines on writing lints.
759///
760/// The macro call should start with a doc comment explaining the lint
761/// which will be embedded in the rustc user documentation book. It should
762/// be written in markdown and have a format that looks like this:
763///
764/// ```rust,ignore (doc-example)
765/// /// The `my_lint_name` lint detects [short explanation here].
766/// ///
767/// /// ### Example
768/// ///
769/// /// ```rust
770/// /// [insert a concise example that triggers the lint]
771/// /// ```
772/// ///
773/// /// {{produces}}
774/// ///
775/// /// ### Explanation
776/// ///
777/// /// This should be a detailed explanation of *why* the lint exists,
778/// /// and also include suggestions on how the user should fix the problem.
779/// /// Try to keep the text simple enough that a beginner can understand,
780/// /// and include links to other documentation for terminology that a
781/// /// beginner may not be familiar with. If this is "allow" by default,
782/// /// it should explain why (are there false positives or other issues?). If
783/// /// this is a future-incompatible lint, it should say so, with text that
784/// /// looks roughly like this:
785/// ///
786/// /// This is a [future-incompatible] lint to transition this to a hard
787/// /// error in the future. See [issue #xxxxx] for more details.
788/// ///
789/// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
790/// ```
791///
792/// The `{{produces}}` tag will be automatically replaced with the output from
793/// the example by the build system. If the lint example is too complex to run
794/// as a simple example (for example, it needs an extern crate), mark the code
795/// block with `ignore` and manually replace the `{{produces}}` line with the
796/// expected output in a `text` code block.
797///
798/// If this is a rustdoc-only lint, then only include a brief introduction
799/// with a link with the text `[rustdoc book]` so that the validator knows
800/// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
801///
802/// Commands to view and test the documentation:
803///
804/// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
805/// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
806/// correct style, and that the code example actually emits the expected
807/// lint.
808///
809/// If you have already built the compiler, and you want to make changes to
810/// just the doc comments, then use the `--keep-stage=0` flag with the above
811/// commands to avoid rebuilding the compiler.
812#[macro_export]
813macro_rules! declare_lint {
814 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
815 $crate::declare_lint!(
816 $(#[$attr])* $vis $NAME, $Level, $desc,
817 );
818 );
819 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
820 $(@eval_always = $eval_always:literal)?
821 $(@feature_gate = $gate:ident;)?
822 $(@future_incompatible = FutureIncompatibleInfo {
823 reason: $reason:expr,
824 $($field:ident : $val:expr),* $(,)*
825 }; )?
826 $(@edition $lint_edition:ident => $edition_level:ident;)?
827 $($v:ident),*) => (
828 $(#[$attr])*
829 $vis static $NAME: &$crate::Lint = &$crate::Lint {
830 name: stringify!($NAME),
831 default_level: $crate::$Level,
832 desc: $desc,
833 is_externally_loaded: false,
834 $($v: true,)*
835 $(feature_gate: Some(rustc_span::sym::$gate),)?
836 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
837 reason: $reason,
838 $($field: $val,)*
839 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
840 }),)?
841 $(edition_lint_opts: Some(($crate::Edition::$lint_edition, $crate::$edition_level)),)?
842 $(eval_always: $eval_always,)?
843 ..$crate::Lint::default_fields_for_macro()
844 };
845 );
846}
847
848#[macro_export]
849macro_rules! declare_tool_lint {
850 (
851 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
852 $(, @eval_always = $eval_always:literal)?
853 $(, @feature_gate = $gate:ident;)?
854 ) => (
855 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @eval_always = $eval_always)? $(, @feature_gate = $gate;)?}
856 );
857 (
858 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
859 report_in_external_macro: $rep:expr
860 $(, @eval_always = $eval_always: literal)?
861 $(, @feature_gate = $gate:ident;)?
862 ) => (
863 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @eval_always = $eval_always)? $(, @feature_gate = $gate;)?}
864 );
865 (
866 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
867 $external:expr
868 $(, @eval_always = $eval_always: literal)?
869 $(, @feature_gate = $gate:ident;)?
870 ) => (
871 $(#[$attr])*
872 $vis static $NAME: &$crate::Lint = &$crate::Lint {
873 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
874 default_level: $crate::$Level,
875 desc: $desc,
876 edition_lint_opts: None,
877 report_in_external_macro: $external,
878 future_incompatible: None,
879 is_externally_loaded: true,
880 $(feature_gate: Some(rustc_span::sym::$gate),)?
881 crate_level_only: false,
882 $(eval_always: $eval_always,)?
883 ..$crate::Lint::default_fields_for_macro()
884 };
885 );
886}
887
888pub type LintVec = Vec<&'static Lint>;
889
890pub trait LintPass {
891 fn name(&self) -> &'static str;
892 fn get_lints(&self) -> LintVec;
893}
894
895/// Implements `LintPass for $ty` with the given list of `Lint` statics.
896#[macro_export]
897macro_rules! impl_lint_pass {
898 ($ty:ty => [$($lint:expr),* $(,)?]) => {
899 impl $crate::LintPass for $ty {
900 fn name(&self) -> &'static str { stringify!($ty) }
901 fn get_lints(&self) -> $crate::LintVec { vec![$($lint),*] }
902 }
903 impl $ty {
904 #[allow(unused)]
905 pub fn lint_vec() -> $crate::LintVec { vec![$($lint),*] }
906 }
907 };
908}
909
910/// Declares a type named `$name` which implements `LintPass`.
911/// To the right of `=>` a comma separated list of `Lint` statics is given.
912#[macro_export]
913macro_rules! declare_lint_pass {
914 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
915 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
916 $crate::impl_lint_pass!($name => [$($lint),*]);
917 };
918}