1use std::borrow::Cow;
2use std::fmt::Display;
34use rustc_data_structures::fx::FxIndexSet;
5use rustc_data_structures::stable_hasher::{
6StableCompare, StableHash, StableHashCtxt, StableHasher, ToStableHashKey,
7};
8use rustc_error_messages::{DiagArgValue, IntoDiagArg};
9use rustc_hir_id::{HirId, ItemLocalId};
10use rustc_macros::{Decodable, Encodable, StableHash};
11use rustc_span::def_id::DefPathHash;
12pub use rustc_span::edition::Edition;
13use rustc_span::{AttrId, Ident, Symbol, sym};
14use serde::{Deserialize, Serialize};
1516pub use self::Level::*;
1718pub mod builtin;
1920#[macro_export]
21macro_rules!pluralize {
22// Pluralize based on count (e.g., apples)
23($x:expr) => {
24if $x == 1 { "" } else { "s" }
25 };
26 ("has", $x:expr) => {
27if $x == 1 { "has" } else { "have" }
28 };
29 ("is", $x:expr) => {
30if $x == 1 { "is" } else { "are" }
31 };
32 ("was", $x:expr) => {
33if $x == 1 { "was" } else { "were" }
34 };
35 ("this", $x:expr) => {
36if $x == 1 { "this" } else { "these" }
37 };
38}
3940/// Grammatical tool for displaying messages to end users in a nice form.
41///
42/// Take a list of items and a function to turn those items into a `String`, and output a display
43/// friendly comma separated list of those items.
44// FIXME(estebank): this needs to be changed to go through the translation machinery.
45pub fn listify<T>(list: &[T], fmt: impl Fn(&T) -> String) -> Option<String> {
46Some(match list {
47 [only] => fmt(&only),
48 [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!(
49"{} and {}",
50 others.iter().map(|i| fmt(i)).collect::<Vec<_>>().join(", "),
51 fmt(&last),
52 ),
53 [] => return None,
54 })
55}
5657/// Indicates the confidence in the correctness of a suggestion.
58///
59/// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
60/// to determine whether it should be automatically applied or if the user should be consulted
61/// before applying the suggestion.
62#[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)]
63#[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)]
64pub enum Applicability {
65/// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
66 /// This suggestion should be automatically applied.
67 ///
68 /// In case of multiple `MachineApplicable` suggestions (whether as part of
69 /// the same `multipart_suggestion` or not), all of them should be
70 /// automatically applied.
71MachineApplicable,
7273/// The suggestion may be what the user intended, but it is uncertain. The suggestion should
74 /// result in valid Rust code if it is applied.
75MaybeIncorrect,
7677/// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
78 /// cannot be applied automatically because it will not result in valid Rust code. The user
79 /// will need to fill in the placeholders.
80HasPlaceholders,
8182/// The applicability of the suggestion is unknown.
83Unspecified,
84}
8586/// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`.
87/// Expected diagnostics get the lint level `Expect` which stores the `LintExpectationId`
88/// to match it with the actual expectation later on.
89///
90/// The `LintExpectationId` has to be stable between compilations, as diagnostic
91/// instances might be loaded from cache. Lint messages can be emitted during an
92/// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the
93/// HIR tree. The AST doesn't have enough information to create a stable id. The
94/// `LintExpectationId` will instead store the [`AttrId`] defining the expectation.
95/// These `LintExpectationId` will be updated to use the stable [`HirId`] once the
96/// AST has been lowered. The transformation is done by the `LintLevelsBuilder`
97///
98/// Each lint inside the `expect` attribute is tracked individually, the `lint_index`
99/// identifies the lint inside the attribute and ensures that the IDs are unique.
100///
101/// The index values have a type of `u16` to reduce the size of the `LintExpectationId`.
102/// It's reasonable to assume that no user will define 2^16 attributes on one node or
103/// have that amount of lints listed. `u16` values should therefore suffice.
104#[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)]
105pub enum LintExpectationId {
106/// Used for lints emitted during the `EarlyLintPass`. This id is not
107 /// hash stable and should not be cached.
108Unstable { attr_id: AttrId, lint_index: Option<u16> },
109/// The [`HirId`] that the lint expectation is attached to. This id is
110 /// stable and can be cached. The additional index ensures that nodes with
111 /// several expectations can correctly match diagnostics to the individual
112 /// expectation.
113Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16> },
114}
115116impl LintExpectationId {
117pub fn is_stable(&self) -> bool {
118match self {
119 LintExpectationId::Unstable { .. } => false,
120 LintExpectationId::Stable { .. } => true,
121 }
122 }
123124pub fn get_lint_index(&self) -> Option<u16> {
125let (LintExpectationId::Unstable { lint_index, .. }
126 | LintExpectationId::Stable { lint_index, .. }) = self;
127128*lint_index129 }
130131pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) {
132let (LintExpectationId::Unstable { lint_index, .. }
133 | LintExpectationId::Stable { lint_index, .. }) = self;
134135*lint_index = new_lint_index136 }
137}
138139impl StableHashfor LintExpectationId {
140#[inline]
141fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
142match self {
143 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
144hir_id.stable_hash(hcx, hasher);
145attr_index.stable_hash(hcx, hasher);
146lint_index.stable_hash(hcx, hasher);
147 }
148_ => {
149{
::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!(
150"StableHash should only be called for filled and stable `LintExpectationId`"
151)152 }
153 }
154 }
155}
156157impl ToStableHashKeyfor LintExpectationId {
158type KeyType = (DefPathHash, ItemLocalId, u16, u16);
159160#[inline]
161fn to_stable_hash_key<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx) -> Self::KeyType {
162match self {
163 LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
164let (def_path_hash, lint_idx) = hir_id.to_stable_hash_key(hcx);
165 (def_path_hash, lint_idx, *attr_index, *lint_index)
166 }
167_ => {
168{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("StableHash should only be called for a filled `LintExpectationId`")));
}unreachable!("StableHash should only be called for a filled `LintExpectationId`")169 }
170 }
171 }
172}
173174/// Setting for how to handle a lint.
175///
176/// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
177#[derive(
178#[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_hasher::StableHash for Level {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hasher::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
Level::Allow => {}
Level::Expect => {}
Level::Warn => {}
Level::ForceWarn => {}
Level::Deny => {}
Level::Forbid => {}
}
}
}
};StableHash179)]
180pub enum Level {
181/// The `allow` level will not issue any message.
182Allow,
183/// The `expect` level will suppress the lint message but in turn produce a message
184 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as
185 /// an initial level for a lint.
186 ///
187 /// Note that this still means that the lint is enabled in this position and should
188 /// be emitted, this will in turn fulfill the expectation and suppress the lint.
189 ///
190 /// See RFC 2383.
191 ///
192 /// Requires a [`LintExpectationId`] to later link a lint emission to the actual
193 /// expectation. It can be ignored in most cases.
194Expect,
195/// The `warn` level will produce a warning if the lint was violated, however the
196 /// compiler will continue with its execution.
197Warn,
198/// This lint level is a special case of [`Warn`], that can't be overridden. This is used
199 /// to ensure that a lint can't be suppressed. This lint level can currently only be set
200 /// via the console and is therefore session specific.
201 ///
202 /// Requires a [`LintExpectationId`] to fulfill expectations marked via the
203 /// `#[expect]` attribute, that will still be suppressed due to the level.
204ForceWarn,
205/// The `deny` level will produce an error and stop further execution after the lint
206 /// pass is complete.
207Deny,
208/// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous
209 /// levels.
210Forbid,
211}
212213impl Level {
214/// Converts a level to a lower-case string.
215pub fn as_str(self) -> &'static str {
216match self {
217 Level::Allow => "allow",
218 Level::Expect => "expect",
219 Level::Warn => "warn",
220 Level::ForceWarn => "force-warn",
221 Level::Deny => "deny",
222 Level::Forbid => "forbid",
223 }
224 }
225226/// Converts a lower-case string to a level. This will never construct the expect
227 /// level as that would require a [`LintExpectationId`].
228pub fn from_str(x: &str) -> Option<Self> {
229match x {
230"allow" => Some(Level::Allow),
231"warn" => Some(Level::Warn),
232"deny" => Some(Level::Deny),
233"forbid" => Some(Level::Forbid),
234"expect" | _ => None,
235 }
236 }
237238/// Converts an `Attribute` to a level.
239pub fn from_attr(
240 attr_name: Option<Symbol>,
241 attr_id: impl Fn() -> AttrId,
242 ) -> Option<(Self, Option<LintExpectationId>)> {
243attr_name.and_then(|name| Self::from_symbol(name, || Some(attr_id())))
244 }
245246/// Converts a `Symbol` to a level.
247pub fn from_symbol(
248 s: Symbol,
249 id: impl FnOnce() -> Option<AttrId>,
250 ) -> Option<(Self, Option<LintExpectationId>)> {
251match s {
252 sym::allow => Some((Level::Allow, None)),
253 sym::expect => {
254if let Some(attr_id) = id() {
255Some((
256 Level::Expect,
257Some(LintExpectationId::Unstable { attr_id, lint_index: None }),
258 ))
259 } else {
260None261 }
262 }
263 sym::warn => Some((Level::Warn, None)),
264 sym::deny => Some((Level::Deny, None)),
265 sym::forbid => Some((Level::Forbid, None)),
266_ => None,
267 }
268 }
269270pub fn to_cmd_flag(self) -> &'static str {
271match self {
272 Level::Warn => "-W",
273 Level::Deny => "-D",
274 Level::Forbid => "-F",
275 Level::Allow => "-A",
276 Level::ForceWarn => "--force-warn",
277 Level::Expect => {
278{
::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")279 }
280 }
281 }
282283pub fn is_error(self) -> bool {
284match self {
285 Level::Allow | Level::Expect | Level::Warn | Level::ForceWarn => false,
286 Level::Deny | Level::Forbid => true,
287 }
288 }
289}
290291impl IntoDiagArg for Level {
292fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
293 DiagArgValue::Str(Cow::Borrowed(self.to_cmd_flag()))
294 }
295}
296297/// Specification of a single lint.
298#[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)]
299pub struct Lint {
300/// A string identifier for the lint.
301 ///
302 /// This identifies the lint in attributes and in command-line arguments.
303 /// In those contexts it is always lowercase, but this field is compared
304 /// in a way which is case-insensitive for ASCII characters. This allows
305 /// `declare_lint!()` invocations to follow the convention of upper-case
306 /// statics without repeating the name.
307 ///
308 /// The name is written with underscores, e.g., "unused_imports".
309 /// On the command line, underscores become dashes.
310 ///
311 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
312 /// for naming guidelines.
313pub name: &'static str,
314315/// Default level for the lint.
316 ///
317 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
318 /// for guidelines on choosing a default level.
319pub default_level: Level,
320321/// Description of the lint or the issue it detects.
322 ///
323 /// e.g., "imports that are never used"
324pub desc: &'static str,
325326/// Starting at the given edition, default to the given lint level. If this is `None`, then use
327 /// `default_level`.
328pub edition_lint_opts: Option<(Edition, Level)>,
329330/// `true` if this lint is reported even inside expansions of external macros.
331pub report_in_external_macro: bool,
332333pub future_incompatible: Option<FutureIncompatibleInfo>,
334335/// `true` if this lint is being loaded by another tool (e.g. Clippy).
336pub is_externally_loaded: bool,
337338/// `Some` if this lint is feature gated, otherwise `None`.
339pub feature_gate: Option<Symbol>,
340341pub crate_level_only: bool,
342343/// `true` if this lint should not be filtered out under any circustamces
344 /// (e.g. the unknown_attributes lint)
345pub eval_always: bool,
346347/// `true` if this lint is unaffected by `-D warnings`
348pub ignore_deny_warnings: bool,
349}
350351/// Extra information for a future incompatibility lint.
352#[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)]
353pub struct FutureIncompatibleInfo {
354/// The reason for the lint used by diagnostics to provide
355 /// the right help message
356pub reason: FutureIncompatibilityReason,
357/// Whether to explain the reason to the user.
358 ///
359 /// Set to false for lints that already include a more detailed
360 /// explanation.
361pub explain_reason: bool,
362/// If set to `true`, this will make future incompatibility warnings show up in cargo's
363 /// reports.
364 ///
365 /// When a future incompatibility warning is first inroduced, set this to `false`
366 /// (or, rather, don't override the default). This allows crate developers an opportunity
367 /// to fix the warning before blasting all dependents with a warning they can't fix
368 /// (dependents have to wait for a new release of the affected crate to be published).
369 ///
370 /// After a lint has been in this state for a while, consider setting this to true, so it
371 /// warns for everyone. It is a good signal that it is ready if you can determine that all
372 /// or most affected crates on crates.io have been updated.
373pub report_in_deps: bool,
374}
375376#[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)]
377pub struct EditionFcw {
378pub edition: Edition,
379pub page_slug: &'static str,
380}
381382#[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)]
383pub struct ReleaseFcw {
384pub issue_number: usize,
385}
386387/// The reason for future incompatibility
388///
389/// Future-incompatible lints come in roughly two categories:
390///
391/// 1. There was a mistake in the compiler (such as a soundness issue), and
392/// we're trying to fix it, but it may be a breaking change.
393/// 2. A change across an Edition boundary, typically used for the
394/// introduction of new language features that can't otherwise be
395/// introduced in a backwards-compatible way.
396///
397/// See <https://rustc-dev-guide.rust-lang.org/bug-fix-procedure.html> and
398/// <https://rustc-dev-guide.rust-lang.org/diagnostics.html#future-incompatible-lints>
399/// for more information.
400#[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)]
401pub enum FutureIncompatibilityReason {
402/// This will be an error in a future release for all editions
403 ///
404 /// Choose this variant when you are first introducing a "future
405 /// incompatible" warning that is intended to eventually be fixed in the
406 /// future.
407 ///
408 /// After a lint has been in this state for a while and you feel like it is ready to graduate
409 /// to warning everyone, consider setting [`FutureIncompatibleInfo::report_in_deps`] to true.
410 /// (see its documentation for more guidance)
411 ///
412 /// After some period of time, lints with this variant can be turned into
413 /// hard errors (and the lint removed). Preferably when there is some
414 /// confidence that the number of impacted projects is very small (few
415 /// should have a broken dependency in their dependency tree).
416FutureReleaseError(ReleaseFcw),
417/// Code that changes meaning in some way in a
418 /// future release.
419 ///
420 /// Choose this variant when the semantics of existing code is changing,
421 /// (as opposed to [`FutureIncompatibilityReason::FutureReleaseError`],
422 /// which is for when code is going to be rejected in the future).
423FutureReleaseSemanticsChange(ReleaseFcw),
424/// Previously accepted code that will become an
425 /// error in the provided edition
426 ///
427 /// Choose this variant for code that you want to start rejecting across
428 /// an edition boundary. This will automatically include the lint in the
429 /// `rust-20xx-compatibility` lint group, which is used by `cargo fix
430 /// --edition` to do migrations. The lint *should* be auto-fixable with
431 /// [`Applicability::MachineApplicable`].
432 ///
433 /// The lint can either be `Allow` or `Warn` by default. If it is `Allow`,
434 /// users usually won't see this warning unless they are doing an edition
435 /// migration manually or there is a problem during the migration (cargo's
436 /// automatic migrations will force the level to `Warn`). If it is `Warn`
437 /// by default, users on all editions will see this warning (only do this
438 /// if you think it is important for everyone to be aware of the change,
439 /// and to encourage people to update their code on all editions).
440 ///
441 /// See also [`FutureIncompatibilityReason::EditionSemanticsChange`] if
442 /// you have code that is changing semantics across the edition (as
443 /// opposed to being rejected).
444EditionError(EditionFcw),
445/// Code that changes meaning in some way in
446 /// the provided edition
447 ///
448 /// This is the same as [`FutureIncompatibilityReason::EditionError`],
449 /// except for situations where the semantics change across an edition. It
450 /// slightly changes the text of the diagnostic, but is otherwise the
451 /// same.
452EditionSemanticsChange(EditionFcw),
453/// This will be an error in the provided edition *and* in a future
454 /// release.
455 ///
456 /// This variant a combination of [`FutureReleaseError`] and [`EditionError`].
457 /// This is useful in rare cases when we want to have "preview" of a breaking
458 /// change in an edition, but do a breaking change later on all editions anyway.
459 ///
460 /// [`EditionError`]: FutureIncompatibilityReason::EditionError
461 /// [`FutureReleaseError`]: FutureIncompatibilityReason::FutureReleaseError
462EditionAndFutureReleaseError(EditionFcw),
463/// This will change meaning in the provided edition *and* in a future
464 /// release.
465 ///
466 /// This variant a combination of [`FutureReleaseSemanticsChange`]
467 /// and [`EditionSemanticsChange`]. This is useful in rare cases when we
468 /// want to have "preview" of a breaking change in an edition, but do a
469 /// breaking change later on all editions anyway.
470 ///
471 /// [`EditionSemanticsChange`]: FutureIncompatibilityReason::EditionSemanticsChange
472 /// [`FutureReleaseSemanticsChange`]: FutureIncompatibilityReason::FutureReleaseSemanticsChange
473EditionAndFutureReleaseSemanticsChange(EditionFcw),
474/// A custom reason.
475 ///
476 /// Choose this variant if the built-in text of the diagnostic of the
477 /// other variants doesn't match your situation. This is behaviorally
478 /// equivalent to
479 /// [`FutureIncompatibilityReason::FutureReleaseError`].
480Custom(&'static str, ReleaseFcw),
481482/// Using the declare_lint macro a reason always needs to be specified.
483 /// So, this case can't actually be reached but a variant needs to exist for it.
484 /// Any code panics on seeing this variant. Do not use.
485Unreachable,
486}
487488impl FutureIncompatibleInfo {
489pub const fn default_fields_for_macro() -> Self {
490FutureIncompatibleInfo {
491 reason: FutureIncompatibilityReason::Unreachable,
492 explain_reason: true,
493 report_in_deps: false,
494 }
495 }
496}
497498impl FutureIncompatibilityReason {
499pub fn edition(self) -> Option<Edition> {
500match self {
501Self::EditionError(e)
502 | Self::EditionSemanticsChange(e)
503 | Self::EditionAndFutureReleaseError(e)
504 | Self::EditionAndFutureReleaseSemanticsChange(e) => Some(e.edition),
505506 FutureIncompatibilityReason::FutureReleaseError(_)
507 | FutureIncompatibilityReason::FutureReleaseSemanticsChange(_)
508 | FutureIncompatibilityReason::Custom(_, _) => None,
509Self::Unreachable => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
510 }
511 }
512513pub fn reference(&self) -> String {
514match self {
515Self::FutureReleaseSemanticsChange(release_fcw)
516 | Self::FutureReleaseError(release_fcw)
517 | Self::Custom(_, release_fcw) => release_fcw.to_string(),
518Self::EditionError(edition_fcw)
519 | Self::EditionSemanticsChange(edition_fcw)
520 | Self::EditionAndFutureReleaseError(edition_fcw)
521 | Self::EditionAndFutureReleaseSemanticsChange(edition_fcw) => edition_fcw.to_string(),
522Self::Unreachable => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
523 }
524 }
525}
526527impl Displayfor ReleaseFcw {
528fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
529let issue_number = self.issue_number;
530f.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}>")531 }
532}
533534impl Displayfor EditionFcw {
535fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
536f.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!(
537f,
538"<https://doc.rust-lang.org/edition-guide/{}/{}.html>",
539match self.edition {
540 Edition::Edition2015 => "rust-2015",
541 Edition::Edition2018 => "rust-2018",
542 Edition::Edition2021 => "rust-2021",
543 Edition::Edition2024 => "rust-2024",
544 Edition::EditionFuture => "future",
545 },
546self.page_slug,
547 )548 }
549}
550551impl Lint {
552pub const fn default_fields_for_macro() -> Self {
553Lint {
554 name: "",
555 default_level: Level::Forbid,
556 desc: "",
557 edition_lint_opts: None,
558 is_externally_loaded: false,
559 report_in_external_macro: false,
560 future_incompatible: None,
561 feature_gate: None,
562 crate_level_only: false,
563 eval_always: false,
564 ignore_deny_warnings: false,
565 }
566 }
567568/// Gets the lint's name, with ASCII letters converted to lowercase.
569pub fn name_lower(&self) -> String {
570self.name.to_ascii_lowercase()
571 }
572573pub fn default_level(&self, edition: Edition) -> Level {
574self.edition_lint_opts
575 .filter(|(e, _)| *e <= edition)
576 .map(|(_, l)| l)
577 .unwrap_or(self.default_level)
578 }
579}
580581/// Identifies a lint known to the compiler.
582#[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)]
583pub struct LintId {
584// Identity is based on pointer equality of this field.
585pub lint: &'static Lint,
586}
587588impl PartialEqfor LintId {
589fn eq(&self, other: &LintId) -> bool {
590 std::ptr::eq(self.lint, other.lint)
591 }
592}
593594impl Eqfor LintId {}
595596impl std::hash::Hashfor LintId {
597fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
598let ptr = self.lint as *const Lint;
599ptr.hash(state);
600 }
601}
602603impl LintId {
604/// Gets the `LintId` for a `Lint`.
605pub fn of(lint: &'static Lint) -> LintId {
606LintId { lint }
607 }
608609pub fn lint_name_raw(&self) -> &'static str {
610self.lint.name
611 }
612613/// Gets the name of the lint.
614pub fn to_string(&self) -> String {
615self.lint.name_lower()
616 }
617}
618619impl StableHashfor LintId {
620#[inline]
621fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
622self.lint_name_raw().stable_hash(hcx, hasher);
623 }
624}
625626impl ToStableHashKeyfor LintId {
627type KeyType = &'static str;
628629#[inline]
630fn to_stable_hash_key<Hcx>(&self, _: &mut Hcx) -> &'static str {
631self.lint_name_raw()
632 }
633}
634635impl StableComparefor LintId {
636const CAN_USE_UNSTABLE_SORT: bool = true;
637638fn stable_cmp(&self, other: &Self) -> std::cmp::Ordering {
639self.lint_name_raw().cmp(&other.lint_name_raw())
640 }
641}
642643#[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)]
644pub enum DeprecatedSinceKind {
645 InEffect,
646 InFuture,
647 InVersion(String),
648}
649650pub type RegisteredTools = FxIndexSet<Ident>;
651652/// Declares a static item of type `&'static Lint`.
653///
654/// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
655/// documentation and guidelines on writing lints.
656///
657/// The macro call should start with a doc comment explaining the lint
658/// which will be embedded in the rustc user documentation book. It should
659/// be written in markdown and have a format that looks like this:
660///
661/// ```rust,ignore (doc-example)
662/// /// The `my_lint_name` lint detects [short explanation here].
663/// ///
664/// /// ### Example
665/// ///
666/// /// ```rust
667/// /// [insert a concise example that triggers the lint]
668/// /// ```
669/// ///
670/// /// {{produces}}
671/// ///
672/// /// ### Explanation
673/// ///
674/// /// This should be a detailed explanation of *why* the lint exists,
675/// /// and also include suggestions on how the user should fix the problem.
676/// /// Try to keep the text simple enough that a beginner can understand,
677/// /// and include links to other documentation for terminology that a
678/// /// beginner may not be familiar with. If this is "allow" by default,
679/// /// it should explain why (are there false positives or other issues?). If
680/// /// this is a future-incompatible lint, it should say so, with text that
681/// /// looks roughly like this:
682/// ///
683/// /// This is a [future-incompatible] lint to transition this to a hard
684/// /// error in the future. See [issue #xxxxx] for more details.
685/// ///
686/// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
687/// ```
688///
689/// The `{{produces}}` tag will be automatically replaced with the output from
690/// the example by the build system. If the lint example is too complex to run
691/// as a simple example (for example, it needs an extern crate), mark the code
692/// block with `ignore` and manually replace the `{{produces}}` line with the
693/// expected output in a `text` code block.
694///
695/// If this is a rustdoc-only lint, then only include a brief introduction
696/// with a link with the text `[rustdoc book]` so that the validator knows
697/// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example).
698///
699/// Commands to view and test the documentation:
700///
701/// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it.
702/// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the
703/// correct style, and that the code example actually emits the expected
704/// lint.
705///
706/// If you have already built the compiler, and you want to make changes to
707/// just the doc comments, then use the `--keep-stage=0` flag with the above
708/// commands to avoid rebuilding the compiler.
709#[macro_export]
710macro_rules!declare_lint {
711 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
712$crate::declare_lint!(
713 $(#[$attr])* $vis $NAME, $Level, $desc,
714 );
715 );
716 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
717 $(@eval_always = $eval_always:literal)?
718$(@feature_gate = $gate:ident;)?
719$(@future_incompatible = FutureIncompatibleInfo {
720 reason: $reason:expr,
721 $($field:ident : $val:expr),* $(,)*
722 }; )?
723$(@edition $lint_edition:ident => $edition_level:ident;)?
724$($v:ident),*) => (
725 $(#[$attr])*
726$vis static $NAME: &$crate::Lint = &$crate::Lint {
727 name: stringify!($NAME),
728 default_level: $crate::$Level,
729 desc: $desc,
730 is_externally_loaded: false,
731 $($v: true,)*
732 $(feature_gate: Some(rustc_span::sym::$gate),)?
733$(future_incompatible: Some($crate::FutureIncompatibleInfo {
734 reason: $reason,
735 $($field: $val,)*
736 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
737 }),)?
738$(edition_lint_opts: Some(($crate::Edition::$lint_edition, $crate::$edition_level)),)?
739$(eval_always: $eval_always,)?
740..$crate::Lint::default_fields_for_macro()
741 };
742 );
743}
744745#[macro_export]
746macro_rules!declare_tool_lint {
747 (
748 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
749 $(, @eval_always = $eval_always:literal)?
750$(, @feature_gate = $gate:ident;)?
751) => (
752$crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @eval_always = $eval_always)? $(, @feature_gate = $gate;)?}
753 );
754 (
755 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
756 report_in_external_macro: $rep:expr
757 $(, @eval_always = $eval_always: literal)?
758$(, @feature_gate = $gate:ident;)?
759) => (
760$crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @eval_always = $eval_always)? $(, @feature_gate = $gate;)?}
761 );
762 (
763 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
764$external:expr
765 $(, @eval_always = $eval_always: literal)?
766$(, @feature_gate = $gate:ident;)?
767) => (
768 $(#[$attr])*
769$vis static $NAME: &$crate::Lint = &$crate::Lint {
770 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
771 default_level: $crate::$Level,
772 desc: $desc,
773 edition_lint_opts: None,
774 report_in_external_macro: $external,
775 future_incompatible: None,
776 is_externally_loaded: true,
777 $(feature_gate: Some(rustc_span::sym::$gate),)?
778crate_level_only: false,
779 $(eval_always: $eval_always,)?
780..$crate::Lint::default_fields_for_macro()
781 };
782 );
783}
784785pub type LintVec = Vec<&'static Lint>;
786787pub trait LintPass {
788fn name(&self) -> &'static str;
789fn get_lints(&self) -> LintVec;
790}
791792/// Implements `LintPass for $ty` with the given list of `Lint` statics.
793#[macro_export]
794macro_rules!impl_lint_pass {
795 ($ty:ty => [$($lint:expr),* $(,)?]) => {
796impl $crate::LintPass for $ty {
797fn name(&self) -> &'static str { stringify!($ty) }
798fn get_lints(&self) -> $crate::LintVec { vec![$($lint),*] }
799 }
800impl $ty {
801#[allow(unused)]
802pub fn lint_vec() -> $crate::LintVec { vec![$($lint),*] }
803 }
804 };
805}
806807/// Declares a type named `$name` which implements `LintPass`.
808/// To the right of `=>` a comma separated list of `Lint` statics is given.
809#[macro_export]
810macro_rules!declare_lint_pass {
811 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
812 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
813$crate::impl_lint_pass!($name => [$($lint),*]);
814 };
815}
816817#[macro_export]
818macro_rules!fcw {
819 (FutureReleaseError # $issue_number: literal) => {
820$crate:: FutureIncompatibilityReason::FutureReleaseError($crate::ReleaseFcw { issue_number: $issue_number })
821 };
822 (FutureReleaseSemanticsChange # $issue_number: literal) => {
823$crate::FutureIncompatibilityReason::FutureReleaseSemanticsChange($crate::ReleaseFcw {
824 issue_number: $issue_number,
825 })
826 };
827 ($description: literal # $issue_number: literal) => {
828$crate::FutureIncompatibilityReason::Custom($description, $crate::ReleaseFcw {
829 issue_number: $issue_number,
830 })
831 };
832 (EditionError $edition_name: tt $page_slug: literal) => {
833$crate::FutureIncompatibilityReason::EditionError($crate::EditionFcw {
834 edition: fcw!(@edition $edition_name),
835 page_slug: $page_slug,
836 })
837 };
838 (EditionSemanticsChange $edition_name: tt $page_slug: literal) => {
839$crate::FutureIncompatibilityReason::EditionSemanticsChange($crate::EditionFcw {
840 edition: fcw!(@edition $edition_name),
841 page_slug: $page_slug,
842 })
843 };
844 (EditionAndFutureReleaseSemanticsChange $edition_name: tt $page_slug: literal) => {
845$crate::FutureIncompatibilityReason::EditionAndFutureReleaseSemanticsChange($crate::EditionFcw {
846 edition: fcw!(@edition $edition_name),
847 page_slug: $page_slug,
848 })
849 };
850 (EditionAndFutureReleaseError $edition_name: tt $page_slug: literal) => {
851$crate::FutureIncompatibilityReason::EditionAndFutureReleaseError($crate::EditionFcw {
852 edition: fcw!(@edition $edition_name),
853 page_slug: $page_slug,
854 })
855 };
856 (@edition 2024) => {
857 rustc_span::edition::Edition::Edition2024
858 };
859 (@edition 2021) => {
860 rustc_span::edition::Edition::Edition2021
861 };
862 (@edition 2018) => {
863 rustc_span::edition::Edition::Edition2018
864 };
865}