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