Skip to main content

rustc_lint_defs/
lib.rs

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