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