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